Skip to main content

waft_rendering/
sliver_multi_box_adaptor.rs

1//! Flutter counterpart: `rendering/sliver_multi_box_adaptor.dart`.
2//!
3//! Semantics wait; see `PORTING.md`.
4
5use std::any::{Any, TypeId};
6use std::fmt::{self, Debug, Display};
7use std::rc::Rc;
8
9use indexmap::IndexMap;
10use waft_embedder::{Matrix4, Offset};
11use waft_foundation::{
12    App, DiagnosticPropertiesBuilder, DiagnosticableTreeNode, DiagnosticsNode,
13    DiagnosticsTreeStyle, Handle, display_or_null, message,
14};
15use waft_painting::{Axis, AxisDirection};
16
17use crate::box_::{AnyRenderBox, BoxConstraints, BoxHitTestResult};
18use crate::object::{
19    AnyRenderObject, ContainerParentData, ContainerParentDataMixin, ContainerRenderObjectBase,
20    ContainerRenderObjectMixin, ParentData, RenderHandle, RenderObject, zero_matrix,
21};
22use crate::painting_context::PaintingContext;
23use crate::pipeline_owner::PipelineOwner;
24use crate::sliver::{
25    RenderSliver, RenderSliverHelpers, SliverConstraints, SliverHitTestResult,
26    SliverLogicalParentData, apply_growth_direction_to_axis_direction,
27};
28
29/// A delegate used by [`RenderSliverMultiBoxAdaptor`] to manage its children.
30///
31/// [`RenderSliverMultiBoxAdaptor`] objects reify their children lazily to avoid spending
32/// resources on children that are not visible in the viewport. This delegate lets these objects
33/// create and remove children as well as estimate the total scroll offset extent occupied by the
34/// full child list.
35///
36/// The widget layer implements this; the render object holds it as an
37/// [`Rc<dyn RenderSliverBoxChildManager>`].
38pub trait RenderSliverBoxChildManager {
39    /// Called during layout when a new child is needed.
40    ///
41    /// The child should be inserted into the child list in the appropriate position, after the
42    /// `after` child (at the start of the list if `after` is `None`). Its index and scroll
43    /// offsets will automatically be set appropriately.
44    ///
45    /// The `index` argument gives the index of the child to show. It is possible for negative
46    /// indices to be requested. For example: if the user scrolls from child 0 to child 10, and
47    /// then those children get much smaller, and then the user scrolls back up again, this
48    /// method will eventually be asked to produce a child for index -1.
49    ///
50    /// If no child corresponds to `index`, then do nothing.
51    ///
52    /// Which child is indicated by index zero depends on the
53    /// [`crate::GrowthDirection`] specified in the `constraints` of the
54    /// [`RenderSliverMultiBoxAdaptor`].
55    ///
56    /// During a call to this method it is valid to remove other children from the
57    /// [`RenderSliverMultiBoxAdaptor`] object if they were not created during this frame and have
58    /// not yet been updated during this frame. It is not valid to add any other children to this
59    /// render object.
60    fn create_child(&self, app: &mut App, index: i32, after: Option<AnyRenderBox>);
61
62    /// Remove the given child from the child list.
63    ///
64    /// Called by [`RenderSliverMultiBoxAdaptor::collect_garbage`], which itself is called from
65    /// the adaptor's `perform_layout`.
66    ///
67    /// The index of the given child can be obtained using
68    /// [`RenderSliverMultiBoxAdaptor::index_of`].
69    fn remove_child(&self, app: &mut App, child: AnyRenderBox);
70
71    /// Called to estimate the total scrollable extents of this object.
72    ///
73    /// Must return the total distance from the start of the child with the earliest possible
74    /// index to the end of the child with the last possible index.
75    fn estimate_max_scroll_offset(
76        &self,
77        app: &App,
78        constraints: SliverConstraints,
79        first_index: Option<i32>,
80        last_index: Option<i32>,
81        leading_scroll_offset: Option<f64>,
82        trailing_scroll_offset: Option<f64>,
83    ) -> f64;
84
85    /// Called to obtain a precise measure of the total number of children.
86    ///
87    /// Must return the number that is one greater than the greatest `index` for which
88    /// [`create_child`](Self::create_child) will actually create a child.
89    ///
90    /// This is used when `create_child` cannot add a child for a positive `index`, to determine
91    /// the precise dimensions of the sliver. It will not be called if `create_child` is always
92    /// able to create a child (e.g. for an infinite list).
93    fn child_count(&self, app: &mut App) -> i32;
94
95    /// The best available estimate of [`child_count`](Self::child_count), or `None` if no
96    /// estimate is available.
97    fn estimated_child_count(&self, app: &App) -> Option<i32> {
98        let _ = app;
99        None
100    }
101
102    /// Called during [`RenderSliverMultiBoxAdaptor::insert`] or
103    /// [`RenderSliverMultiBoxAdaptor::move_child`].
104    ///
105    /// Implementors must ensure that the [`SliverMultiBoxAdaptorParentData::index`] field of the
106    /// child's parent data accurately reflects the child's index in the child list after this
107    /// function returns.
108    fn did_adopt_child(&self, app: &mut App, child: AnyRenderBox);
109
110    /// Called during layout to indicate whether this object provided insufficient children for
111    /// the [`RenderSliverMultiBoxAdaptor`] to fill the
112    /// [`SliverConstraints::remaining_paint_extent`].
113    ///
114    /// Typically called unconditionally at the start of layout with `false` and then later
115    /// called with `true` when the adaptor fails to create a child required to fill the
116    /// remaining paint extent.
117    fn set_did_underflow(&self, app: &mut App, value: bool);
118
119    /// Called at the beginning of layout to indicate that layout is about to occur.
120    fn did_start_layout(&self, app: &mut App) {
121        let _ = app;
122    }
123
124    /// Called at the end of layout to indicate that layout is now complete.
125    fn did_finish_layout(&self, app: &mut App) {
126        let _ = app;
127    }
128
129    /// In debug mode, asserts that this manager is not expecting any modifications to the
130    /// [`RenderSliverMultiBoxAdaptor`]'s child list.
131    ///
132    /// This function always returns true.
133    fn debug_assert_child_list_locked(&self, app: &App) -> bool {
134        let _ = app;
135        true
136    }
137}
138
139/// Parent data structure used by [`RenderSliverWithKeepAliveMixin`].
140///
141/// Flutter's `KeepAliveParentDataMixin`: the half a parent data embeds and answers from
142/// [`ParentData::provide`], which is how `KeepAlive` finds it.
143#[derive(Clone, Copy, Debug, Default)]
144pub struct KeepAliveParentData {
145    /// Whether to keep the child alive even when it is no longer visible.
146    pub keep_alive: bool,
147    kept_alive: bool,
148}
149
150impl KeepAliveParentData {
151    /// Parent data that does not keep its child alive.
152    pub const fn new() -> KeepAliveParentData {
153        KeepAliveParentData {
154            keep_alive: false,
155            kept_alive: false,
156        }
157    }
158
159    /// Whether the widget is currently being kept alive, i.e. has
160    /// [`keep_alive`](Self::keep_alive) set to true and is offscreen.
161    pub fn kept_alive(&self) -> bool {
162        self.kept_alive
163    }
164}
165
166/// This trait exists to dissociate `KeepAlive` from [`RenderSliverMultiBoxAdaptor`].
167///
168/// [`setup_parent_data`](Self::setup_parent_data) must be implemented to use a parent data type
169/// that embeds a [`KeepAliveParentData`].
170pub trait RenderSliverWithKeepAliveMixin: RenderSliver {
171    /// Alerts the developer that the child's parent data needs to embed a
172    /// [`KeepAliveParentData`].
173    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
174        let _ = self;
175        debug_assert!(
176            child
177                .parent_data(app)
178                .is_some_and(|parent_data| parent_data.part::<KeepAliveParentData>().is_some())
179        );
180    }
181}
182
183/// Parent data structure used by [`RenderSliverMultiBoxAdaptor`].
184#[derive(Debug)]
185pub struct SliverMultiBoxAdaptorParentData {
186    sliver_logical: SliverLogicalParentData,
187    container: ContainerParentData<AnyRenderBox>,
188    keep_alive: KeepAliveParentData,
189    /// The index of this child according to the [`RenderSliverBoxChildManager`].
190    pub index: Option<i32>,
191}
192
193impl SliverMultiBoxAdaptorParentData {
194    /// Creates parent data with no index and no layout offset.
195    pub const fn new() -> SliverMultiBoxAdaptorParentData {
196        SliverMultiBoxAdaptorParentData {
197            sliver_logical: SliverLogicalParentData::new(),
198            container: ContainerParentData::new(),
199            keep_alive: KeepAliveParentData::new(),
200            index: None,
201        }
202    }
203
204    /// See [`SliverLogicalParentData::layout_offset`].
205    pub fn layout_offset(&self) -> Option<f64> {
206        self.sliver_logical.layout_offset
207    }
208
209    /// Sets [`layout_offset`](Self::layout_offset).
210    pub fn set_layout_offset(&mut self, value: Option<f64>) {
211        self.sliver_logical.layout_offset = value;
212    }
213
214    /// See [`KeepAliveParentData::keep_alive`].
215    pub fn keep_alive(&self) -> bool {
216        self.keep_alive.keep_alive
217    }
218
219    /// Sets [`keep_alive`](Self::keep_alive).
220    pub fn set_keep_alive(&mut self, value: bool) {
221        self.keep_alive.keep_alive = value;
222    }
223
224    /// See [`KeepAliveParentData::kept_alive`].
225    pub fn kept_alive(&self) -> bool {
226        self.keep_alive.kept_alive
227    }
228}
229
230impl Default for SliverMultiBoxAdaptorParentData {
231    fn default() -> SliverMultiBoxAdaptorParentData {
232        SliverMultiBoxAdaptorParentData::new()
233    }
234}
235
236impl ParentData for SliverMultiBoxAdaptorParentData {
237    fn detach(&mut self) {
238        ContainerParentDataMixin::detach(self);
239    }
240
241    fn provide(&self, id: TypeId) -> Option<&dyn Any> {
242        if id == TypeId::of::<SliverMultiBoxAdaptorParentData>() {
243            return Some(self);
244        }
245        if id == TypeId::of::<KeepAliveParentData>() {
246            return Some(&self.keep_alive);
247        }
248        self.sliver_logical.provide(id)
249    }
250
251    fn provide_mut(&mut self, id: TypeId) -> Option<&mut dyn Any> {
252        if id == TypeId::of::<SliverMultiBoxAdaptorParentData>() {
253            return Some(self);
254        }
255        if id == TypeId::of::<KeepAliveParentData>() {
256            return Some(&mut self.keep_alive);
257        }
258        self.sliver_logical.provide_mut(id)
259    }
260}
261
262impl ContainerParentDataMixin for SliverMultiBoxAdaptorParentData {
263    type ChildType = AnyRenderBox;
264
265    fn container_parent_data(&self) -> &ContainerParentData<AnyRenderBox> {
266        &self.container
267    }
268
269    fn container_parent_data_mut(&mut self) -> &mut ContainerParentData<AnyRenderBox> {
270        &mut self.container
271    }
272}
273
274impl Display for SliverMultiBoxAdaptorParentData {
275    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
276        write!(f, "index={}; ", display_or_null(&self.index))?;
277        if self.keep_alive() {
278            f.write_str("keepAlive; ")?;
279        }
280        Display::fmt(&self.sliver_logical, f)
281    }
282}
283
284/// Gives `child`, whose parent data `drop_child` cleared, `sliver`'s kind of parent data again
285/// holding `saved`, marked kept alive.
286///
287/// Dart re-assigns the parent data object it saved before `dropChild` nulled it. Here the object
288/// is gone, so the sliver's own [`RenderObject::setup_parent_data`] makes a new one (a grid's,
289/// for a grid) and the saved fields are written back. A subclass's own fields, such as a grid
290/// tile's cross-axis offset, start empty: a kept-alive child is neither painted nor hit, and it
291/// is laid out again before it shows.
292fn restore_parent_data<T: RenderSliverMultiBoxAdaptor>(
293    sliver: RenderHandle<T>,
294    app: &mut App,
295    child: AnyRenderBox,
296    saved: KeptSlot,
297) {
298    RenderObject::setup_parent_data(sliver, app, child.as_object());
299    let restored = child
300        .as_object()
301        .parent_data_of_mut::<SliverMultiBoxAdaptorParentData>(app);
302    restored.set_layout_offset(saved.layout_offset);
303    restored.set_keep_alive(saved.keep_alive);
304    restored.index = saved.index;
305    restored.keep_alive.kept_alive = true;
306}
307
308/// The fields of a child's [`SliverMultiBoxAdaptorParentData`] that a move into or out of the
309/// keep-alive bucket keeps.
310#[derive(Clone, Copy)]
311struct KeptSlot {
312    layout_offset: Option<f64>,
313    keep_alive: bool,
314    index: Option<i32>,
315}
316
317impl KeptSlot {
318    fn of(parent_data: &SliverMultiBoxAdaptorParentData) -> KeptSlot {
319        KeptSlot {
320            layout_offset: parent_data.layout_offset(),
321            keep_alive: parent_data.keep_alive(),
322            index: parent_data.index,
323        }
324    }
325}
326
327/// Flutter's `RenderSliverMultiBoxAdaptor` fields.
328pub struct RenderSliverMultiBoxAdaptorData {
329    child_manager: Rc<dyn RenderSliverBoxChildManager>,
330    /// The nodes being kept alive despite not being visible.
331    keep_alive_bucket: IndexMap<i32, AnyRenderBox>,
332    debug_dangling_keep_alives: Vec<AnyRenderBox>,
333    debug_child_integrity_enabled: bool,
334}
335
336impl RenderSliverMultiBoxAdaptorData {
337    /// Creates the state of a sliver with multiple box children.
338    pub fn new(
339        child_manager: Rc<dyn RenderSliverBoxChildManager>,
340    ) -> RenderSliverMultiBoxAdaptorData {
341        RenderSliverMultiBoxAdaptorData {
342            child_manager,
343            keep_alive_bucket: IndexMap::new(),
344            debug_dangling_keep_alives: Vec::new(),
345            debug_child_integrity_enabled: true,
346        }
347    }
348}
349
350/// Implements [`RenderSliverMultiBoxAdaptor`] field accessors for an `adaptor` field.
351#[macro_export]
352macro_rules! render_sliver_multi_box_adaptor_accessors {
353    () => {
354        fn adaptor_data(
355            self: $crate::RenderHandle<Self>,
356            app: &::waft_foundation::App,
357        ) -> &$crate::RenderSliverMultiBoxAdaptorData {
358            &self.get(app).adaptor
359        }
360        fn adaptor_data_mut(
361            self: $crate::RenderHandle<Self>,
362            app: &mut ::waft_foundation::App,
363        ) -> &mut $crate::RenderSliverMultiBoxAdaptorData {
364            &mut self.get_mut(app).adaptor
365        }
366    };
367}
368
369/// A sliver with multiple box children.
370///
371/// [`RenderSliverMultiBoxAdaptor`] is a base class for slivers that have multiple box children.
372/// The children are managed by a [`RenderSliverBoxChildManager`], which lets implementors create
373/// children lazily during layout. Typically implementors will create only those children that are
374/// actually needed to fill the [`SliverConstraints::remaining_paint_extent`].
375///
376/// The contract for adding and removing children from this render object is more strict than for
377/// normal render objects:
378///
379/// * Children can be removed except during a layout pass if they have already been laid out
380///   during that layout pass.
381/// * Children cannot be added except during a call to
382///   [`child_manager`](Self::child_manager), and then only if there is no child corresponding to
383///   that index (or the child corresponding to that index was first removed).
384///
385/// See also:
386///
387///  * [`crate::RenderSliverToBoxAdapter`], which has a single box child.
388///  * [`crate::RenderSliverList`], which places its children in a linear array.
389///  * [`crate::RenderSliverFixedExtentList`], which places its children in a linear array with a
390///    fixed extent in the main axis.
391pub trait RenderSliverMultiBoxAdaptor:
392    RenderSliver
393    + RenderSliverHelpers
394    + RenderSliverWithKeepAliveMixin
395    + ContainerRenderObjectMixin<
396        ChildType = AnyRenderBox,
397        ParentDataType = SliverMultiBoxAdaptorParentData,
398    >
399{
400    /// Mixin field access.
401    fn adaptor_data(self: RenderHandle<Self>, app: &App) -> &RenderSliverMultiBoxAdaptorData;
402
403    /// See [`adaptor_data`](Self::adaptor_data).
404    fn adaptor_data_mut(
405        self: RenderHandle<Self>,
406        app: &mut App,
407    ) -> &mut RenderSliverMultiBoxAdaptorData;
408
409    /// The delegate that manages the children of this object.
410    ///
411    /// Rather than having a concrete list of children, a [`RenderSliverMultiBoxAdaptor`] uses a
412    /// [`RenderSliverBoxChildManager`] to create children during layout in order to fill the
413    /// [`SliverConstraints::remaining_paint_extent`].
414    fn child_manager(self: RenderHandle<Self>, app: &App) -> Rc<dyn RenderSliverBoxChildManager> {
415        Rc::clone(&self.adaptor_data(app).child_manager)
416    }
417
418    /// The body of Flutter's `setupParentData` override.
419    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
420        if !child.parent_data_is::<SliverMultiBoxAdaptorParentData>(app) {
421            child.set_parent_data(app, SliverMultiBoxAdaptorParentData::new());
422        }
423    }
424
425    /// Whether the integrity check is enabled.
426    ///
427    /// The integrity check consists of:
428    ///
429    /// 1. Verify that the children index in the child list is in ascending order.
430    /// 2. Verify that there is no dangling keep-alive child as the result of
431    ///    [`move_child`](Self::move_child).
432    fn debug_child_integrity_enabled(self: RenderHandle<Self>, app: &App) -> bool {
433        self.adaptor_data(app).debug_child_integrity_enabled
434    }
435
436    /// Sets [`debug_child_integrity_enabled`](Self::debug_child_integrity_enabled), immediately
437    /// performing an integrity check.
438    fn set_debug_child_integrity_enabled(self: RenderHandle<Self>, app: &mut App, enabled: bool) {
439        if !cfg!(debug_assertions) {
440            return;
441        }
442        self.adaptor_data_mut(app).debug_child_integrity_enabled = enabled;
443        debug_assert!(self.debug_verify_child_order(app));
444        debug_assert!(
445            !enabled || self.adaptor_data(app).debug_dangling_keep_alives.is_empty(),
446            "a keep-alive child was left dangling by move_child"
447        );
448    }
449
450    /// Flutter's `_debugAssertChildListLocked`.
451    fn debug_assert_child_list_locked(self: RenderHandle<Self>, app: &App) -> bool {
452        self.child_manager(app).debug_assert_child_list_locked(app)
453    }
454
455    /// Verify that the child list index is in strictly increasing order.
456    ///
457    /// This has no effect in release builds.
458    fn debug_verify_child_order(self: RenderHandle<Self>, app: &App) -> bool {
459        if self.debug_child_integrity_enabled(app) {
460            let mut child = self.first_child(app);
461            while let Some(current) = child {
462                let index = self.index_of(app, current);
463                child = self.child_after(app, current);
464                debug_assert!(child.is_none_or(|next| self.index_of(app, next) > index));
465            }
466        }
467        true
468    }
469
470    /// The body of Flutter's `insert` override.
471    fn insert(
472        self: RenderHandle<Self>,
473        app: &mut App,
474        child: AnyRenderBox,
475        after: Option<AnyRenderBox>,
476    ) {
477        debug_assert!(
478            !self
479                .adaptor_data(app)
480                .keep_alive_bucket
481                .values()
482                .any(|kept| *kept == child)
483        );
484        ContainerRenderObjectBase::insert(self, app, child, after);
485        self.did_adopt_child(app, child);
486        debug_assert!(self.first_child(app).is_some());
487        debug_assert!(self.debug_verify_child_order(app));
488    }
489
490    /// The body of Flutter's `adoptChild` override, run after a child joins the child list.
491    ///
492    /// Flutter overrides `RenderObject.adoptChild`; here the tree operation is not virtual, so
493    /// the two callers ([`insert`](Self::insert) and Dart's `_destroyOrCacheChild`, which takes
494    /// `super.adoptChild`) decide whether it runs.
495    fn did_adopt_child(self: RenderHandle<Self>, app: &mut App, child: AnyRenderBox) {
496        let kept_alive = child
497            .as_object()
498            .parent_data_of::<SliverMultiBoxAdaptorParentData>(app)
499            .kept_alive();
500        if !kept_alive {
501            self.child_manager(app).did_adopt_child(app, child);
502        }
503    }
504
505    /// The body of Flutter's `move` override.
506    ///
507    /// There are two scenarios:
508    ///
509    /// 1. The child is not kept alive. The child is in the child list maintained by
510    ///    [`ContainerRenderObjectMixin`]. We can call the inherited body and update the parent
511    ///    data with the new slot.
512    ///
513    /// 2. The child is kept alive. In this case, the child is no longer in the child list but
514    ///    might be stored in the keep-alive bucket. We need to update the location of the child
515    ///    in the bucket.
516    fn move_child(
517        self: RenderHandle<Self>,
518        app: &mut App,
519        child: AnyRenderBox,
520        after: Option<AnyRenderBox>,
521    ) {
522        let child_parent_data = child
523            .as_object()
524            .parent_data_of::<SliverMultiBoxAdaptorParentData>(app);
525        let (kept_alive, index) = (child_parent_data.kept_alive(), child_parent_data.index);
526        if !kept_alive {
527            ContainerRenderObjectBase::move_child(self, app, child, after);
528            // updates the slot in the parent data
529            self.child_manager(app).did_adopt_child(app, child);
530            // Its slot may change even if the inherited body does not change the position. In
531            // this case, we still want to mark as needs layout.
532            self.mark_needs_layout(app);
533            return;
534        }
535        // If the child in the bucket is not the current child, that means someone has already
536        // moved and replaced the current child, and we cannot remove this child.
537        if let Some(index) = index
538            && self.adaptor_data(app).keep_alive_bucket.get(&index) == Some(&child)
539        {
540            self.adaptor_data_mut(app)
541                .keep_alive_bucket
542                .shift_remove(&index);
543        }
544        if cfg!(debug_assertions) {
545            self.adaptor_data_mut(app)
546                .debug_dangling_keep_alives
547                .retain(|dangling| *dangling != child);
548        }
549        // Update the slot and reinsert back to the keep-alive bucket in the new slot.
550        self.child_manager(app).did_adopt_child(app, child);
551        // If there is an existing child in the new slot, that means that child will be moved to
552        // another index. In other cases, the existing child should have been removed by
553        // update_child. Thus, it is ok to overwrite it.
554        let new_index = child
555            .as_object()
556            .parent_data_of::<SliverMultiBoxAdaptorParentData>(app)
557            .index
558            .expect("did_adopt_child sets the index");
559        if cfg!(debug_assertions)
560            && let Some(existing) = self
561                .adaptor_data(app)
562                .keep_alive_bucket
563                .get(&new_index)
564                .copied()
565        {
566            self.adaptor_data_mut(app)
567                .debug_dangling_keep_alives
568                .push(existing);
569        }
570        self.adaptor_data_mut(app)
571            .keep_alive_bucket
572            .insert(new_index, child);
573    }
574
575    /// The body of Flutter's `remove` override.
576    fn remove(self: RenderHandle<Self>, app: &mut App, child: AnyRenderBox) {
577        let child_parent_data = child
578            .as_object()
579            .parent_data_of::<SliverMultiBoxAdaptorParentData>(app);
580        let (kept_alive, index) = (child_parent_data.kept_alive(), child_parent_data.index);
581        if !kept_alive {
582            ContainerRenderObjectBase::remove(self, app, child);
583            return;
584        }
585        let index = index.expect("a kept-alive child has an index");
586        debug_assert_eq!(
587            self.adaptor_data(app).keep_alive_bucket.get(&index),
588            Some(&child)
589        );
590        if cfg!(debug_assertions) {
591            self.adaptor_data_mut(app)
592                .debug_dangling_keep_alives
593                .retain(|dangling| *dangling != child);
594        }
595        self.adaptor_data_mut(app)
596            .keep_alive_bucket
597            .shift_remove(&index);
598        self.drop_child(app, child.as_object());
599    }
600
601    /// The body of Flutter's `removeAll` override.
602    fn remove_all(self: RenderHandle<Self>, app: &mut App) {
603        ContainerRenderObjectBase::remove_all(self, app);
604        for child in self.keep_alive_children(app) {
605            self.drop_child(app, child.as_object());
606        }
607        self.adaptor_data_mut(app).keep_alive_bucket.clear();
608    }
609
610    /// The children currently held in the keep-alive bucket, in insertion order.
611    fn keep_alive_children(self: RenderHandle<Self>, app: &App) -> Vec<AnyRenderBox> {
612        self.adaptor_data(app)
613            .keep_alive_bucket
614            .values()
615            .copied()
616            .collect()
617    }
618
619    /// Flutter's `_createOrObtainChild`.
620    fn create_or_obtain_child(
621        self: RenderHandle<Self>,
622        app: &mut App,
623        index: i32,
624        after: Option<AnyRenderBox>,
625    ) {
626        self.as_object().invoke_layout_callback(app, |app| {
627            let cached = self
628                .adaptor_data(app)
629                .keep_alive_bucket
630                .get(&index)
631                .copied();
632            let Some(child) = cached else {
633                self.child_manager(app).create_child(app, index, after);
634                return;
635            };
636            self.adaptor_data_mut(app)
637                .keep_alive_bucket
638                .shift_remove(&index);
639            let child_parent_data = child
640                .as_object()
641                .parent_data_of::<SliverMultiBoxAdaptorParentData>(app);
642            debug_assert!(child_parent_data.kept_alive());
643            let saved = KeptSlot::of(child_parent_data);
644            self.drop_child(app, child.as_object());
645            restore_parent_data(self, app, child, saved);
646            RenderSliverMultiBoxAdaptor::insert(self, app, child, after);
647            child
648                .as_object()
649                .parent_data_of_mut::<SliverMultiBoxAdaptorParentData>(app)
650                .keep_alive
651                .kept_alive = false;
652        });
653    }
654
655    /// Flutter's `_destroyOrCacheChild`.
656    fn destroy_or_cache_child(self: RenderHandle<Self>, app: &mut App, child: AnyRenderBox) {
657        let child_parent_data = child
658            .as_object()
659            .parent_data_of::<SliverMultiBoxAdaptorParentData>(app);
660        if !child_parent_data.keep_alive() {
661            debug_assert_eq!(child.as_object().parent(app), Some(self.as_object()));
662            self.child_manager(app).remove_child(app, child);
663            debug_assert!(child.as_object().parent(app).is_none());
664            return;
665        }
666        debug_assert!(!child_parent_data.kept_alive());
667        let saved = KeptSlot::of(child_parent_data);
668        let index = saved.index.expect("a cached child has an index");
669        RenderSliverMultiBoxAdaptor::remove(self, app, child);
670        self.adaptor_data_mut(app)
671            .keep_alive_bucket
672            .insert(index, child);
673        restore_parent_data(self, app, child, saved);
674        // Dart's `super.adoptChild`: the child manager is not told, because the child keeps its
675        // slot.
676        self.as_object().adopt_child(app, child.as_object());
677    }
678
679    /// The body of Flutter's `attach` override: attaches the kept-alive children too.
680    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
681        ContainerRenderObjectMixin::did_attach(self, app, owner);
682        for child in self.keep_alive_children(app) {
683            child.as_object().attach(app, owner);
684        }
685    }
686
687    /// The body of Flutter's `detach` override: detaches the kept-alive children too.
688    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
689        ContainerRenderObjectMixin::did_detach(self, app);
690        for child in self.keep_alive_children(app) {
691            child.as_object().detach(app);
692        }
693    }
694
695    /// The body of Flutter's `redepthChildren` override.
696    fn redepth_children(self: RenderHandle<Self>, app: &mut App) {
697        ContainerRenderObjectMixin::redepth_children(self, app);
698        for child in self.keep_alive_children(app) {
699            self.as_object().redepth_child(app, child.as_object());
700        }
701    }
702
703    /// The body of Flutter's `visitChildren` override: visits the kept-alive children too.
704    fn visit_children(
705        self: RenderHandle<Self>,
706        app: &App,
707        visitor: &mut dyn FnMut(AnyRenderObject),
708    ) {
709        ContainerRenderObjectMixin::visit_children(self, app, visitor);
710        for child in self.keep_alive_children(app) {
711            visitor(child.as_object());
712        }
713    }
714
715    /// Called during layout to create and add the child with the given index and scroll offset.
716    ///
717    /// Calls [`RenderSliverBoxChildManager::create_child`] to actually create and add the child
718    /// if necessary. The child may instead be obtained from a cache; see
719    /// [`KeepAliveParentData::keep_alive`].
720    ///
721    /// Returns `false` if there was no cached child and `create_child` did not add any child,
722    /// otherwise returns `true`.
723    ///
724    /// Does not lay out the new child.
725    fn add_initial_child(
726        self: RenderHandle<Self>,
727        app: &mut App,
728        index: i32,
729        layout_offset: f64,
730    ) -> bool {
731        debug_assert!(self.debug_assert_child_list_locked(app));
732        debug_assert!(self.first_child(app).is_none());
733        self.create_or_obtain_child(app, index, None);
734        if let Some(first_child) = self.first_child(app) {
735            debug_assert_eq!(Some(first_child), self.last_child(app));
736            debug_assert_eq!(self.index_of(app, first_child), index);
737            first_child
738                .as_object()
739                .parent_data_of_mut::<SliverMultiBoxAdaptorParentData>(app)
740                .set_layout_offset(Some(layout_offset));
741            return true;
742        }
743        self.child_manager(app).set_did_underflow(app, true);
744        false
745    }
746
747    /// Called during layout to create, add, and lay out the child before
748    /// [`ContainerRenderObjectMixin::first_child`].
749    ///
750    /// Returns the new child or `None` if no child was obtained.
751    ///
752    /// The child that was previously the first child, as well as any subsequent children, may be
753    /// removed by this call if they have not yet been laid out during this layout pass.
754    fn insert_and_layout_leading_child(
755        self: RenderHandle<Self>,
756        app: &mut App,
757        child_constraints: BoxConstraints,
758        parent_uses_size: bool,
759    ) -> Option<AnyRenderBox> {
760        debug_assert!(self.debug_assert_child_list_locked(app));
761        let first_child = self.first_child(app).expect("there is a leading child");
762        let index = self.index_of(app, first_child) - 1;
763        self.create_or_obtain_child(app, index, None);
764        let first_child = self.first_child(app).expect("the child list is not empty");
765        if self.index_of(app, first_child) == index {
766            first_child.layout(app, child_constraints, parent_uses_size);
767            return Some(first_child);
768        }
769        self.child_manager(app).set_did_underflow(app, true);
770        None
771    }
772
773    /// Called during layout to create, add, and lay out the child after the given child.
774    ///
775    /// Returns the new child. It is the responsibility of the caller to configure the child's
776    /// scroll offset.
777    ///
778    /// Children after the `after` child may be removed in the process. Only the new child may be
779    /// added.
780    fn insert_and_layout_child(
781        self: RenderHandle<Self>,
782        app: &mut App,
783        child_constraints: BoxConstraints,
784        after: Option<AnyRenderBox>,
785        parent_uses_size: bool,
786    ) -> Option<AnyRenderBox> {
787        debug_assert!(self.debug_assert_child_list_locked(app));
788        let after = after.expect("insert_and_layout_child needs a preceding child");
789        let index = self.index_of(app, after) + 1;
790        self.create_or_obtain_child(app, index, Some(after));
791        let child = self.child_after(app, after);
792        if let Some(child) = child
793            && self.index_of(app, child) == index
794        {
795            child.layout(app, child_constraints, parent_uses_size);
796            return Some(child);
797        }
798        self.child_manager(app).set_did_underflow(app, true);
799        None
800    }
801
802    /// Returns the number of children preceding the `first_index` that need to be garbage
803    /// collected.
804    fn calculate_leading_garbage(self: RenderHandle<Self>, app: &App, first_index: i32) -> usize {
805        let mut walker = self.first_child(app);
806        let mut leading_garbage = 0;
807        while let Some(current) = walker {
808            if self.index_of(app, current) >= first_index {
809                break;
810            }
811            leading_garbage += 1;
812            walker = self.child_after(app, current);
813        }
814        leading_garbage
815    }
816
817    /// Returns the number of children following the `last_index` that need to be garbage
818    /// collected.
819    fn calculate_trailing_garbage(self: RenderHandle<Self>, app: &App, last_index: i32) -> usize {
820        let mut walker = self.last_child(app);
821        let mut trailing_garbage = 0;
822        while let Some(current) = walker {
823            if self.index_of(app, current) <= last_index {
824                break;
825            }
826            trailing_garbage += 1;
827            walker = self.child_before(app, current);
828        }
829        trailing_garbage
830    }
831
832    /// Called after layout with the number of children that can be garbage collected at the head
833    /// and tail of the child list.
834    ///
835    /// Children whose [`KeepAliveParentData::keep_alive`] property is set to true will be
836    /// removed to a cache instead of being dropped.
837    ///
838    /// This method also collects any children that were previously kept alive but are now no
839    /// longer necessary. As such, it should be called every time `perform_layout` is run, even if
840    /// the arguments are both zero.
841    fn collect_garbage(
842        self: RenderHandle<Self>,
843        app: &mut App,
844        leading_garbage: usize,
845        trailing_garbage: usize,
846    ) {
847        debug_assert!(self.debug_assert_child_list_locked(app));
848        debug_assert!(self.child_count(app) >= leading_garbage + trailing_garbage);
849        self.as_object().invoke_layout_callback(app, |app| {
850            for _ in 0..leading_garbage {
851                let first_child = self.first_child(app).expect("counted above");
852                self.destroy_or_cache_child(app, first_child);
853            }
854            for _ in 0..trailing_garbage {
855                let last_child = self.last_child(app).expect("counted above");
856                self.destroy_or_cache_child(app, last_child);
857            }
858            // Ask the child manager to remove the children that are no longer being kept alive.
859            // (This should cause the keep-alive bucket to change, so we have to prepare our list
860            // ahead of time.)
861            let expired: Vec<AnyRenderBox> = self
862                .keep_alive_children(app)
863                .into_iter()
864                .filter(|child| {
865                    !child
866                        .as_object()
867                        .parent_data_of::<SliverMultiBoxAdaptorParentData>(app)
868                        .keep_alive()
869                })
870                .collect();
871            let child_manager = self.child_manager(app);
872            for child in expired {
873                child_manager.remove_child(app, child);
874            }
875            debug_assert!(self.keep_alive_children(app).iter().all(|child| {
876                child
877                    .as_object()
878                    .parent_data_of::<SliverMultiBoxAdaptorParentData>(app)
879                    .keep_alive()
880            }));
881        });
882    }
883
884    /// Returns the index of the given child, as given by the
885    /// [`SliverMultiBoxAdaptorParentData::index`] field of the child's parent data.
886    fn index_of(self: RenderHandle<Self>, app: &App, child: AnyRenderBox) -> i32 {
887        child
888            .as_object()
889            .parent_data_of::<SliverMultiBoxAdaptorParentData>(app)
890            .index
891            .expect("a reified child has an index")
892    }
893
894    /// Dart's `debugFillProperties`: the range of live child indices, or that there are none.
895    fn debug_fill_properties(
896        self: RenderHandle<Self>,
897        app: &App,
898        properties: &mut DiagnosticPropertiesBuilder,
899    ) {
900        let text = match (self.first_child(app), self.last_child(app)) {
901            (Some(first), Some(last)) => format!(
902                "currently live children: {} to {}",
903                self.index_of(app, first),
904                self.index_of(app, last)
905            ),
906            _ => "no children current live".to_owned(),
907        };
908        properties.add(message(text));
909    }
910
911    /// Dart's `debugDescribeChildren`: the live children by index, then the kept-alive children
912    /// by index, offstage.
913    fn debug_describe_children(
914        self: RenderHandle<Self>,
915        app: &App,
916    ) -> Vec<Rc<dyn DiagnosticsNode>> {
917        let mut children: Vec<Rc<dyn DiagnosticsNode>> = Vec::new();
918        if let (Some(mut child), Some(last)) = (self.first_child(app), self.last_child(app)) {
919            loop {
920                let index = self.index_of(app, child);
921                children.push(Rc::new(
922                    child
923                        .as_object()
924                        .to_diagnostics_node(app, format!("child with index {index}")),
925                ));
926                if child == last {
927                    break;
928                }
929                child = self
930                    .child_after(app, child)
931                    .expect("the last child ends the walk");
932            }
933        }
934        let mut indices: Vec<i32> = self
935            .adaptor_data(app)
936            .keep_alive_bucket
937            .keys()
938            .copied()
939            .collect();
940        indices.sort_unstable();
941        for index in indices {
942            let child = self
943                .adaptor_data(app)
944                .keep_alive_bucket
945                .get(&index)
946                .copied()
947                .expect("the index came from the bucket");
948            let name = format!("child with index {index} (kept alive but not laid out)");
949            let node = child.as_object().to_diagnostics_node(app, name.clone());
950            let mut builder =
951                DiagnosticPropertiesBuilder::from_properties(node.properties().to_vec());
952            builder.default_diagnostics_tree_style = DiagnosticsTreeStyle::Offstage;
953            children.push(Rc::new(DiagnosticableTreeNode::from_parts(
954                name,
955                node.description(),
956                builder,
957                node.children().to_vec(),
958            )));
959        }
960        children
961    }
962
963    /// Returns the dimension of the given child in the main axis, as given by the child's size.
964    ///
965    /// This is only valid after layout.
966    fn paint_extent_of(self: RenderHandle<Self>, app: &App, child: AnyRenderBox) -> f64 {
967        debug_assert!(child.has_size(app));
968        match self.constraints(app).axis() {
969            Axis::Horizontal => child.size(app).width(),
970            Axis::Vertical => child.size(app).height(),
971        }
972    }
973
974    /// The body of Flutter's `hitTestChildren` override.
975    fn hit_test_children(
976        self: RenderHandle<Self>,
977        app: &mut App,
978        result: &mut SliverHitTestResult<'_>,
979        main_axis_position: f64,
980        cross_axis_position: f64,
981    ) -> bool {
982        let mut child = self.last_child(app);
983        while let Some(current) = child {
984            let previous = self.child_before(app, current);
985            if self.hit_test_box_child(
986                app,
987                &mut BoxHitTestResult::wrap(result),
988                current,
989                main_axis_position,
990                cross_axis_position,
991            ) {
992                return true;
993            }
994            child = previous;
995        }
996        false
997    }
998
999    /// The body of Flutter's `childMainAxisPosition` override.
1000    fn child_main_axis_position(
1001        self: RenderHandle<Self>,
1002        app: &App,
1003        child: AnyRenderObject,
1004    ) -> f64 {
1005        RenderSliverMultiBoxAdaptor::child_scroll_offset(self, app, child)
1006            .expect("a laid-out child has a scroll offset")
1007            - self.constraints(app).scroll_offset
1008    }
1009
1010    /// The body of Flutter's `childScrollOffset` override.
1011    fn child_scroll_offset(
1012        self: RenderHandle<Self>,
1013        app: &App,
1014        child: AnyRenderObject,
1015    ) -> Option<f64> {
1016        debug_assert_eq!(child.parent(app), Some(self.as_object()));
1017        child
1018            .parent_data_of::<SliverMultiBoxAdaptorParentData>(app)
1019            .layout_offset()
1020    }
1021
1022    /// The body of Flutter's `paintsChild` override: the child is painted when it is reified
1023    /// and not kept alive off-screen.
1024    fn paints_child(self: RenderHandle<Self>, app: &App, child: AnyRenderObject) -> bool {
1025        let index = child
1026            .parent_data_is::<SliverMultiBoxAdaptorParentData>(app)
1027            .then(|| {
1028                child
1029                    .parent_data_of::<SliverMultiBoxAdaptorParentData>(app)
1030                    .index
1031            })
1032            .flatten();
1033        match index {
1034            None => false,
1035            Some(index) => !self
1036                .adaptor_data(app)
1037                .keep_alive_bucket
1038                .contains_key(&index),
1039        }
1040    }
1041
1042    /// The body of Flutter's `applyPaintTransform` override.
1043    fn apply_paint_transform(
1044        self: RenderHandle<Self>,
1045        app: &App,
1046        child: AnyRenderObject,
1047        transform: &mut Matrix4,
1048    ) {
1049        if RenderObject::paints_child(self, app, child) {
1050            let child = child.as_box().expect("the children are boxes");
1051            self.apply_paint_transform_for_box_child(app, child, transform);
1052        } else {
1053            // This can happen if some child asks for the global transform even though they are
1054            // not getting painted. In that case, the transform is set to zero since
1055            // apply_paint_transform_for_box_child would end up throwing due to the child not
1056            // being configured correctly for applying a transform. There's no assert here because
1057            // asking for the paint transform is a valid thing to do even if a child would not be
1058            // painted, but there is no meaningful non-zero matrix to use in this case.
1059            *transform = zero_matrix();
1060        }
1061    }
1062
1063    /// The body of Flutter's `paint` override.
1064    fn paint(
1065        self: RenderHandle<Self>,
1066        app: &mut App,
1067        context: &mut PaintingContext,
1068        offset: Offset,
1069    ) {
1070        if self.first_child(app).is_none() {
1071            return;
1072        }
1073        // offset is to the top-left corner, regardless of our axis direction.
1074        // origin_offset gives us the delta from the real origin to the origin in the axis
1075        // direction.
1076        let constraints = self.constraints(app);
1077        let paint_extent = self.geometry(app).paint_extent;
1078        let (main_axis_unit, cross_axis_unit, origin_offset, add_extent) =
1079            match apply_growth_direction_to_axis_direction(
1080                constraints.axis_direction,
1081                constraints.growth_direction,
1082            ) {
1083                AxisDirection::Up => (
1084                    Offset::new(0.0, -1.0),
1085                    Offset::new(1.0, 0.0),
1086                    offset + Offset::new(0.0, paint_extent),
1087                    true,
1088                ),
1089                AxisDirection::Right => {
1090                    (Offset::new(1.0, 0.0), Offset::new(0.0, 1.0), offset, false)
1091                }
1092                AxisDirection::Down => {
1093                    (Offset::new(0.0, 1.0), Offset::new(1.0, 0.0), offset, false)
1094                }
1095                AxisDirection::Left => (
1096                    Offset::new(-1.0, 0.0),
1097                    Offset::new(0.0, 1.0),
1098                    offset + Offset::new(paint_extent, 0.0),
1099                    true,
1100                ),
1101            };
1102        let mut child = self.first_child(app);
1103        while let Some(current) = child {
1104            let main_axis_delta = RenderSliverMultiBoxAdaptor::child_main_axis_position(
1105                self,
1106                app,
1107                current.as_object(),
1108            );
1109            let cross_axis_delta = self.child_cross_axis_position(app, current.as_object());
1110            let mut child_offset = Offset::new(
1111                origin_offset.dx()
1112                    + main_axis_unit.dx() * main_axis_delta
1113                    + cross_axis_unit.dx() * cross_axis_delta,
1114                origin_offset.dy()
1115                    + main_axis_unit.dy() * main_axis_delta
1116                    + cross_axis_unit.dy() * cross_axis_delta,
1117            );
1118            let child_paint_extent = self.paint_extent_of(app, current);
1119            if add_extent {
1120                child_offset = child_offset + main_axis_unit * child_paint_extent;
1121            }
1122
1123            // If the child's visible interval (main_axis_delta, main_axis_delta +
1124            // paint_extent_of(child)) does not intersect the paint extent interval
1125            // (0, constraints.remaining_paint_extent), it's hidden.
1126            if main_axis_delta < constraints.remaining_paint_extent
1127                && main_axis_delta + child_paint_extent > 0.0
1128            {
1129                context.paint_child(app, current.as_object(), child_offset);
1130            }
1131
1132            child = self.child_after(app, current);
1133        }
1134    }
1135
1136    /// Asserts that the reified child list is not empty and has a contiguous sequence of indices.
1137    ///
1138    /// Always returns true.
1139    fn debug_assert_child_list_is_non_empty_and_contiguous(
1140        self: RenderHandle<Self>,
1141        app: &App,
1142    ) -> bool {
1143        if cfg!(debug_assertions) {
1144            let first_child = self.first_child(app).expect("the child list is not empty");
1145            let mut index = self.index_of(app, first_child);
1146            let mut child = self.child_after(app, first_child);
1147            while let Some(current) = child {
1148                index += 1;
1149                debug_assert_eq!(self.index_of(app, current), index);
1150                child = self.child_after(app, current);
1151            }
1152        }
1153        true
1154    }
1155}
1156
1157#[cfg(test)]
1158pub(crate) mod test_support {
1159    use std::cell::{Cell, RefCell};
1160
1161    use waft_embedder::Size;
1162
1163    use super::*;
1164    use crate::box_::{RenderBox, RenderBoxData};
1165    use crate::object::{RenderObject, RenderObjectData};
1166
1167    /// A box that takes the largest size the constraints allow, and accepts hits.
1168    pub(crate) struct TestChild {
1169        render_object: RenderObjectData,
1170        render_box: RenderBoxData,
1171        preferred_extent: f64,
1172    }
1173
1174    impl RenderObject for TestChild {
1175        crate::render_object_accessors!();
1176
1177        fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
1178            let extent = self.get(app).preferred_extent;
1179            let size = self.constraints(app).constrain(Size::new(extent, extent));
1180            self.set_size(app, size);
1181        }
1182    }
1183
1184    impl RenderBox for TestChild {
1185        crate::render_box_accessors!();
1186
1187        fn hit_test_self(self: RenderHandle<Self>, _app: &App, _position: Offset) -> bool {
1188            let _ = self;
1189            true
1190        }
1191    }
1192
1193    /// A box that fills the constraints it is given, up to `extent` in each dimension, and
1194    /// accepts hits.
1195    pub(crate) fn hit_testable_box(app: &mut App, extent: f64) -> AnyRenderBox {
1196        RenderHandle::new_box(
1197            app,
1198            TestChild {
1199                render_object: RenderObjectData::new(),
1200                render_box: RenderBoxData::new(),
1201                preferred_extent: extent,
1202            },
1203        )
1204        .as_box()
1205    }
1206
1207    /// A [`RenderSliverBoxChildManager`] over a fixed list of child extents, as
1208    /// `SliverMultiBoxAdaptorElement` is over a delegate.
1209    pub(crate) struct TestChildManager<T: RenderSliverMultiBoxAdaptor> {
1210        render_object: Cell<Option<RenderHandle<T>>>,
1211        extents: Vec<f64>,
1212        currently_updating_child_index: Cell<Option<i32>>,
1213        /// The indices `create_child` was asked for, in order.
1214        pub(crate) created: RefCell<Vec<i32>>,
1215        /// The last value passed to `set_did_underflow`.
1216        pub(crate) did_underflow: Cell<bool>,
1217    }
1218
1219    impl<T: RenderSliverMultiBoxAdaptor> TestChildManager<T> {
1220        pub(crate) fn new(extents: Vec<f64>) -> Rc<TestChildManager<T>> {
1221            Rc::new(TestChildManager {
1222                render_object: Cell::new(None),
1223                extents,
1224                currently_updating_child_index: Cell::new(None),
1225                created: RefCell::new(Vec::new()),
1226                did_underflow: Cell::new(false),
1227            })
1228        }
1229
1230        pub(crate) fn attach(&self, render_object: RenderHandle<T>) {
1231            self.render_object.set(Some(render_object));
1232        }
1233
1234        fn adaptor(&self) -> RenderHandle<T> {
1235            self.render_object.get().expect("attached before layout")
1236        }
1237
1238        fn total_extent(&self) -> f64 {
1239            self.extents.iter().sum()
1240        }
1241    }
1242
1243    impl<T: RenderSliverMultiBoxAdaptor> RenderSliverBoxChildManager for TestChildManager<T> {
1244        fn create_child(&self, app: &mut App, index: i32, after: Option<AnyRenderBox>) {
1245            self.created.borrow_mut().push(index);
1246            let Ok(slot) = usize::try_from(index) else {
1247                return;
1248            };
1249            let Some(extent) = self.extents.get(slot).copied() else {
1250                return;
1251            };
1252            let child = RenderHandle::new_box(
1253                app,
1254                TestChild {
1255                    render_object: RenderObjectData::new(),
1256                    render_box: RenderBoxData::new(),
1257                    preferred_extent: extent,
1258                },
1259            )
1260            .as_box();
1261            self.currently_updating_child_index.set(Some(index));
1262            RenderSliverMultiBoxAdaptor::insert(self.adaptor(), app, child, after);
1263            self.currently_updating_child_index.set(None);
1264        }
1265
1266        fn remove_child(&self, app: &mut App, child: AnyRenderBox) {
1267            // Dart's element unmounts the child and disposes its render object later; the test
1268            // leaves the arena slot alone so that assertions can still name the child.
1269            RenderSliverMultiBoxAdaptor::remove(self.adaptor(), app, child);
1270        }
1271
1272        fn estimate_max_scroll_offset(
1273            &self,
1274            _app: &App,
1275            _constraints: SliverConstraints,
1276            _first_index: Option<i32>,
1277            _last_index: Option<i32>,
1278            _leading_scroll_offset: Option<f64>,
1279            _trailing_scroll_offset: Option<f64>,
1280        ) -> f64 {
1281            self.total_extent()
1282        }
1283
1284        fn child_count(&self, _app: &mut App) -> i32 {
1285            self.extents.len() as i32
1286        }
1287
1288        fn estimated_child_count(&self, _app: &App) -> Option<i32> {
1289            Some(self.extents.len() as i32)
1290        }
1291
1292        fn did_adopt_child(&self, app: &mut App, child: AnyRenderBox) {
1293            child
1294                .as_object()
1295                .parent_data_of_mut::<SliverMultiBoxAdaptorParentData>(app)
1296                .index = self.currently_updating_child_index.get();
1297        }
1298
1299        fn set_did_underflow(&self, _app: &mut App, value: bool) {
1300            self.did_underflow.set(value);
1301        }
1302    }
1303}
1304
1305#[cfg(test)]
1306pub(crate) mod viewport_test_support {
1307    use std::rc::Rc;
1308
1309    use waft_embedder::{Size, View, ViewId, ViewMetrics, ViewRef};
1310    use waft_foundation::{Handle, Ref};
1311
1312    use super::*;
1313    use crate::box_::RenderBox;
1314    use crate::pipeline_owner::PipelineOwner;
1315    use crate::sliver::AnyRenderSliver;
1316    use crate::view::{RenderView, ViewConfiguration};
1317    use crate::viewport::RenderViewport;
1318    use crate::viewport_offset::{FixedViewportOffset, ViewportOffset};
1319    use waft_test::TestViewHost;
1320
1321    #[derive(Default)]
1322    struct TestView {
1323        host: TestViewHost,
1324    }
1325
1326    impl View for TestView {
1327        fn id(&self) -> ViewId {
1328            ViewId(0)
1329        }
1330
1331        fn metrics(&self) -> ViewMetrics {
1332            ViewMetrics::default()
1333        }
1334
1335        fn present(
1336            &self,
1337            _scene: std::sync::Arc<waft_embedder::Scene>,
1338            _size: waft_embedder::Size,
1339        ) {
1340        }
1341
1342        fn host(&self) -> &dyn waft_embedder::ViewHost {
1343            &self.host
1344        }
1345    }
1346
1347    /// The scrolling machinery a lazy sliver needs: a viewport inside a [`RenderView`] rooted in
1348    /// a [`PipelineOwner`], laid out once.
1349    pub(crate) struct ScrollHarness {
1350        pub(crate) owner: Ref<PipelineOwner>,
1351        pub(crate) viewport: RenderHandle<RenderViewport>,
1352        pub(crate) offset: Handle<FixedViewportOffset>,
1353    }
1354
1355    impl ScrollHarness {
1356        /// Lays `sliver` out in a downward-scrolling viewport of `size`.
1357        pub(crate) fn new(app: &mut App, sliver: AnyRenderSliver, size: Size) -> ScrollHarness {
1358            let offset = FixedViewportOffset::zero(app);
1359            let viewport = RenderViewport::new(
1360                app,
1361                AxisDirection::Right,
1362                offset.erase(),
1363                Some(vec![sliver]),
1364                None,
1365            );
1366            let constraints = BoxConstraints::tight(size);
1367            let configuration = ViewConfiguration::new(constraints, constraints, 1.0);
1368            let view = RenderView::new(
1369                app,
1370                Some(viewport.as_box()),
1371                Some(configuration),
1372                Rc::new(TestView::default()) as ViewRef,
1373            );
1374            let owner = PipelineOwner::new(app, None, None);
1375            owner.set_root_node(app, Some(view.as_object()));
1376            view.prepare_initial_frame(app);
1377            owner.flush_layout(app);
1378            ScrollHarness {
1379                owner,
1380                viewport,
1381                offset: offset.handle(),
1382            }
1383        }
1384
1385        /// Scrolls to `pixels` and lays out again.
1386        pub(crate) fn scroll_to(&self, app: &mut App, pixels: f64) {
1387            let current = self.offset.pixels(app);
1388            self.offset.correct_by(app, pixels - current);
1389            self.viewport.mark_needs_layout(app);
1390            self.owner.flush_layout(app);
1391        }
1392    }
1393}