Skip to main content

waft_rendering/
sliver_grid.rs

1//! Flutter counterpart: `rendering/sliver_grid.dart`.
2
3use std::any::{Any, TypeId};
4use std::fmt::{self, Debug, Display};
5use std::rc::Rc;
6
7use waft_embedder::{Matrix4, Offset};
8use waft_foundation::{App, Handle, PRECISION_ERROR_TOLERANCE};
9use waft_painting::axis_direction_is_reversed;
10
11use crate::box_::{AnyRenderBox, BoxConstraints};
12use crate::object::{
13    AnyRenderObject, ContainerParentData, ContainerParentDataMixin, ContainerRenderObjectData,
14    ContainerRenderObjectMixin, ParentData, RenderHandle, RenderObject, RenderObjectData,
15};
16use crate::painting_context::PaintingContext;
17use crate::pipeline_owner::PipelineOwner;
18use crate::sliver::{
19    RenderSliver, RenderSliverData, RenderSliverHelpers, SliverConstraints, SliverGeometry,
20    SliverHitTestResult, calculate_cache_offset, calculate_paint_offset,
21};
22use crate::sliver_multi_box_adaptor::{
23    RenderSliverBoxChildManager, RenderSliverMultiBoxAdaptor, RenderSliverMultiBoxAdaptorData,
24    RenderSliverWithKeepAliveMixin, SliverMultiBoxAdaptorParentData,
25};
26
27/// Describes the placement of a child in a [`RenderSliverGrid`].
28///
29/// This class is similar to [`Rect`](waft_embedder::Rect), in that it gives a two-dimensional
30/// position and a two-dimensional dimension, but is direction-agnostic.
31///
32/// See also:
33///
34///  * [`SliverGridLayout`], which represents the geometry of all the tiles in a grid.
35///  * [`SliverGridLayout::get_geometry_for_child_index`], which returns this object to describe
36///    the child's placement.
37///  * [`RenderSliverGrid`], which uses this class during its
38///    [`perform_layout`](RenderObject::perform_layout) method.
39#[derive(Clone, Copy)]
40pub struct SliverGridGeometry {
41    /// The scroll offset of the leading edge of the child relative to the leading edge of the
42    /// parent.
43    pub scroll_offset: f64,
44    /// The offset of the child in the non-scrolling axis.
45    ///
46    /// If the scroll axis is vertical, this offset is from the left-most edge of the parent to
47    /// the left-most edge of the child. If the scroll axis is horizontal, this offset is from the
48    /// top-most edge of the parent to the top-most edge of the child.
49    pub cross_axis_offset: f64,
50    /// The extent of the child in the scrolling axis.
51    ///
52    /// If the scroll axis is vertical, this extent is the child's height. If the scroll axis is
53    /// horizontal, this extent is the child's width.
54    pub main_axis_extent: f64,
55    /// The extent of the child in the non-scrolling axis.
56    ///
57    /// If the scroll axis is vertical, this extent is the child's width. If the scroll axis is
58    /// horizontal, this extent is the child's height.
59    pub cross_axis_extent: f64,
60}
61
62impl SliverGridGeometry {
63    /// Creates an object that describes the placement of a child in a [`RenderSliverGrid`].
64    pub const fn new(
65        scroll_offset: f64,
66        cross_axis_offset: f64,
67        main_axis_extent: f64,
68        cross_axis_extent: f64,
69    ) -> SliverGridGeometry {
70        SliverGridGeometry {
71            scroll_offset,
72            cross_axis_offset,
73            main_axis_extent,
74            cross_axis_extent,
75        }
76    }
77
78    /// The scroll offset of the trailing edge of the child relative to the leading edge of the
79    /// parent.
80    pub fn trailing_scroll_offset(&self) -> f64 {
81        self.scroll_offset + self.main_axis_extent
82    }
83
84    /// Returns a tight [`BoxConstraints`] that forces the child to have the required size, given
85    /// a [`SliverConstraints`].
86    pub fn get_box_constraints(&self, constraints: SliverConstraints) -> BoxConstraints {
87        constraints.as_box_constraints(
88            self.main_axis_extent,
89            self.main_axis_extent,
90            Some(self.cross_axis_extent),
91        )
92    }
93}
94
95impl Debug for SliverGridGeometry {
96    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97        write!(
98            f,
99            "SliverGridGeometry(scrollOffset: {}, crossAxisOffset: {}, mainAxisExtent: {}, crossAxisExtent: {})",
100            self.scroll_offset,
101            self.cross_axis_offset,
102            self.main_axis_extent,
103            self.cross_axis_extent
104        )
105    }
106}
107
108/// The size and position of all the tiles in a [`RenderSliverGrid`].
109///
110/// Rather that providing a grid with a [`SliverGridLayout`] directly, the grid is provided a
111/// [`SliverGridDelegate`], which computes a [`SliverGridLayout`] given a set of
112/// [`SliverConstraints`]. This allows the algorithm to dynamically respond to changes in the
113/// environment (e.g. the user rotating the device).
114///
115/// The tiles can be placed arbitrarily, but it is more efficient to place tiles roughly in order
116/// by scroll offset because grids reify a contiguous sequence of children.
117///
118/// See also:
119///
120///  * [`SliverGridRegularTileLayout`], which represents a layout that uses equally sized and
121///    spaced tiles.
122///  * [`SliverGridGeometry`], which represents the size and position of a single tile in a grid.
123///  * [`SliverGridDelegate::get_layout`], which returns this object to describe the delegate's
124///    layout.
125///  * [`RenderSliverGrid`], which uses this class during its
126///    [`perform_layout`](RenderObject::perform_layout) method.
127pub trait SliverGridLayout: Debug {
128    /// The minimum child index that intersects with (or is after) this scroll offset.
129    fn get_min_child_index_for_scroll_offset(&self, scroll_offset: f64) -> i32;
130
131    /// The maximum child index that intersects with (or is before) this scroll offset.
132    fn get_max_child_index_for_scroll_offset(&self, scroll_offset: f64) -> i32;
133
134    /// The size and position of the child with the given index.
135    fn get_geometry_for_child_index(&self, index: i32) -> SliverGridGeometry;
136
137    /// The scroll extent needed to fully display all the tiles if there are `child_count`
138    /// children in total.
139    fn compute_max_scroll_offset(&self, child_count: i32) -> f64;
140}
141
142/// A [`SliverGridLayout`] that uses equally sized and spaced tiles.
143///
144/// Rather that providing a grid with a [`SliverGridLayout`] directly, you instead provide the
145/// grid a [`SliverGridDelegate`], which can compute a [`SliverGridLayout`] given the current
146/// [`SliverConstraints`].
147///
148/// This layout is used by [`SliverGridDelegateWithFixedCrossAxisCount`] and
149/// [`SliverGridDelegateWithMaxCrossAxisExtent`].
150#[derive(Clone, Copy, Debug)]
151pub struct SliverGridRegularTileLayout {
152    /// The number of children in the cross axis.
153    pub cross_axis_count: i32,
154    /// The number of pixels from the leading edge of one tile to the leading edge of the next
155    /// tile in the main axis.
156    pub main_axis_stride: f64,
157    /// The number of pixels from the leading edge of one tile to the leading edge of the next
158    /// tile in the cross axis.
159    pub cross_axis_stride: f64,
160    /// The number of pixels from the leading edge of one tile to the trailing edge of the same
161    /// tile in the main axis.
162    pub child_main_axis_extent: f64,
163    /// The number of pixels from the leading edge of one tile to the trailing edge of the same
164    /// tile in the cross axis.
165    pub child_cross_axis_extent: f64,
166    /// Whether the children should be placed in the opposite order of increasing coordinates in
167    /// the cross axis.
168    ///
169    /// For example, if the cross axis is horizontal, the children are placed from left to right
170    /// when [`reverse_cross_axis`](Self::reverse_cross_axis) is false and from right to left when
171    /// it is true.
172    ///
173    /// Typically set to the return value of [`axis_direction_is_reversed`] applied to the
174    /// [`SliverConstraints::cross_axis_direction`].
175    pub reverse_cross_axis: bool,
176}
177
178impl SliverGridRegularTileLayout {
179    /// Creates a layout that uses equally sized and spaced tiles.
180    ///
181    /// All of the arguments must not be negative. The `cross_axis_count` argument must be greater
182    /// than zero.
183    pub fn new(
184        cross_axis_count: i32,
185        main_axis_stride: f64,
186        cross_axis_stride: f64,
187        child_main_axis_extent: f64,
188        child_cross_axis_extent: f64,
189        reverse_cross_axis: bool,
190    ) -> SliverGridRegularTileLayout {
191        debug_assert!(cross_axis_count > 0);
192        debug_assert!(main_axis_stride >= 0.0);
193        debug_assert!(cross_axis_stride >= 0.0);
194        debug_assert!(child_main_axis_extent >= 0.0);
195        debug_assert!(child_cross_axis_extent >= 0.0);
196        SliverGridRegularTileLayout {
197            cross_axis_count,
198            main_axis_stride,
199            cross_axis_stride,
200            child_main_axis_extent,
201            child_cross_axis_extent,
202            reverse_cross_axis,
203        }
204    }
205
206    fn get_offset_from_start_in_cross_axis(&self, cross_axis_start: f64) -> f64 {
207        if self.reverse_cross_axis {
208            return f64::from(self.cross_axis_count) * self.cross_axis_stride
209                - cross_axis_start
210                - self.child_cross_axis_extent
211                - (self.cross_axis_stride - self.child_cross_axis_extent);
212        }
213        cross_axis_start
214    }
215}
216
217impl SliverGridLayout for SliverGridRegularTileLayout {
218    fn get_min_child_index_for_scroll_offset(&self, scroll_offset: f64) -> i32 {
219        if self.main_axis_stride > PRECISION_ERROR_TOLERANCE {
220            self.cross_axis_count * (scroll_offset / self.main_axis_stride).trunc() as i32
221        } else {
222            0
223        }
224    }
225
226    fn get_max_child_index_for_scroll_offset(&self, scroll_offset: f64) -> i32 {
227        if self.main_axis_stride > 0.0 {
228            let main_axis_count = (scroll_offset / self.main_axis_stride).ceil() as i32;
229            return (self.cross_axis_count * main_axis_count - 1).max(0);
230        }
231        0
232    }
233
234    fn get_geometry_for_child_index(&self, index: i32) -> SliverGridGeometry {
235        let cross_axis_start = f64::from(index % self.cross_axis_count) * self.cross_axis_stride;
236        SliverGridGeometry::new(
237            f64::from(index / self.cross_axis_count) * self.main_axis_stride,
238            self.get_offset_from_start_in_cross_axis(cross_axis_start),
239            self.child_main_axis_extent,
240            self.child_cross_axis_extent,
241        )
242    }
243
244    fn compute_max_scroll_offset(&self, child_count: i32) -> f64 {
245        if child_count == 0 {
246            // There are no children in the grid. The max scroll offset should be zero.
247            return 0.0;
248        }
249        let main_axis_count = ((child_count - 1) / self.cross_axis_count) + 1;
250        let main_axis_spacing = self.main_axis_stride - self.child_main_axis_extent;
251        self.main_axis_stride * f64::from(main_axis_count) - main_axis_spacing
252    }
253}
254
255/// Controls the layout of tiles in a grid.
256///
257/// Given the current constraints on the grid, a [`SliverGridDelegate`] computes the layout for
258/// the tiles in the grid. The tiles can be placed arbitrarily, but it is more efficient to place
259/// tiles roughly in order by scroll offset because grids reify a contiguous sequence of children.
260///
261/// See also:
262///
263///  * [`SliverGridDelegateWithFixedCrossAxisCount`], which creates a layout with a fixed number
264///    of tiles in the cross axis.
265///  * [`SliverGridDelegateWithMaxCrossAxisExtent`], which creates a layout with tiles that have a
266///    maximum cross-axis extent.
267///  * `GridView`, which uses this delegate to control the layout of its tiles.
268///  * `SliverGrid`, which uses this delegate to control the layout of its tiles.
269///  * [`RenderSliverGrid`], which uses this delegate to control the layout of its tiles.
270pub trait SliverGridDelegate: Debug {
271    /// Returns information about the size and position of the tiles in the grid.
272    fn get_layout(&self, constraints: SliverConstraints) -> Box<dyn SliverGridLayout>;
273
274    /// Override this method to return true when the children need to be laid out.
275    ///
276    /// This should compare the fields of the current delegate and the given `old_delegate` and
277    /// return true if the fields are such that the layout would be different. The grid asks only
278    /// for an `old_delegate` of this delegate's own type.
279    fn should_relayout(&self, old_delegate: &dyn SliverGridDelegate) -> bool;
280
281    /// Downcast support for Dart's `runtimeType` comparison and `covariant` parameters.
282    fn as_any(&self) -> &dyn Any;
283}
284
285/// Creates grid layouts with a fixed number of tiles in the cross axis.
286///
287/// For example, if the grid is vertical, this delegate will create a layout with a fixed number
288/// of columns. If the grid is horizontal, this delegate will create a layout with a fixed number
289/// of rows.
290///
291/// This delegate creates grids with equally sized and spaced tiles.
292///
293/// Dart's named constructor arguments are the fluent setters.
294///
295/// See also:
296///
297///  * [`SliverGridDelegateWithMaxCrossAxisExtent`], which creates a layout with tiles that have a
298///    maximum cross-axis extent.
299///  * [`SliverGridDelegate`], which creates arbitrary layouts.
300///  * [`RenderSliverGrid`], which can use this delegate to control the layout of its tiles.
301#[derive(Clone, Debug)]
302pub struct SliverGridDelegateWithFixedCrossAxisCount {
303    /// The number of children in the cross axis.
304    pub cross_axis_count: i32,
305    /// The number of logical pixels between each child along the main axis.
306    pub main_axis_spacing: f64,
307    /// The number of logical pixels between each child along the cross axis.
308    pub cross_axis_spacing: f64,
309    /// The ratio of the cross-axis to the main-axis extent of each child.
310    pub child_aspect_ratio: f64,
311    /// The extent of each tile in the main axis. If provided it would define the logical pixels
312    /// taken by each tile in the main-axis.
313    ///
314    /// If `None`, [`child_aspect_ratio`](Self::child_aspect_ratio) is used instead.
315    pub main_axis_extent: Option<f64>,
316}
317
318impl SliverGridDelegateWithFixedCrossAxisCount {
319    /// Creates a delegate that makes grid layouts with a fixed number of tiles in the cross axis.
320    ///
321    /// The `cross_axis_count` must be greater than zero.
322    pub fn new(cross_axis_count: i32) -> SliverGridDelegateWithFixedCrossAxisCount {
323        debug_assert!(cross_axis_count > 0);
324        SliverGridDelegateWithFixedCrossAxisCount {
325            cross_axis_count,
326            main_axis_spacing: 0.0,
327            cross_axis_spacing: 0.0,
328            child_aspect_ratio: 1.0,
329            main_axis_extent: None,
330        }
331    }
332
333    /// Dart `SliverGridDelegateWithFixedCrossAxisCount(mainAxisSpacing:)`. Must not be negative.
334    pub fn main_axis_spacing(mut self, value: f64) -> Self {
335        debug_assert!(value >= 0.0);
336        self.main_axis_spacing = value;
337        self
338    }
339
340    /// Dart `SliverGridDelegateWithFixedCrossAxisCount(crossAxisSpacing:)`. Must not be negative.
341    pub fn cross_axis_spacing(mut self, value: f64) -> Self {
342        debug_assert!(value >= 0.0);
343        self.cross_axis_spacing = value;
344        self
345    }
346
347    /// Dart `SliverGridDelegateWithFixedCrossAxisCount(childAspectRatio:)`. Must be greater than
348    /// zero.
349    pub fn child_aspect_ratio(mut self, value: f64) -> Self {
350        debug_assert!(value > 0.0);
351        self.child_aspect_ratio = value;
352        self
353    }
354
355    /// Dart `SliverGridDelegateWithFixedCrossAxisCount(mainAxisExtent:)`. Must not be negative.
356    pub fn main_axis_extent(mut self, value: f64) -> Self {
357        debug_assert!(value >= 0.0);
358        self.main_axis_extent = Some(value);
359        self
360    }
361
362    fn debug_assert_is_valid(&self) -> bool {
363        debug_assert!(self.cross_axis_count > 0);
364        debug_assert!(self.main_axis_spacing >= 0.0);
365        debug_assert!(self.cross_axis_spacing >= 0.0);
366        debug_assert!(self.child_aspect_ratio > 0.0);
367        true
368    }
369}
370
371impl SliverGridDelegate for SliverGridDelegateWithFixedCrossAxisCount {
372    fn get_layout(&self, constraints: SliverConstraints) -> Box<dyn SliverGridLayout> {
373        debug_assert!(self.debug_assert_is_valid());
374        let usable_cross_axis_extent = (constraints.cross_axis_extent
375            - self.cross_axis_spacing * f64::from(self.cross_axis_count - 1))
376        .max(0.0);
377        let child_cross_axis_extent = usable_cross_axis_extent / f64::from(self.cross_axis_count);
378        let child_main_axis_extent = self
379            .main_axis_extent
380            .unwrap_or(child_cross_axis_extent / self.child_aspect_ratio);
381        Box::new(SliverGridRegularTileLayout::new(
382            self.cross_axis_count,
383            child_main_axis_extent + self.main_axis_spacing,
384            child_cross_axis_extent + self.cross_axis_spacing,
385            child_main_axis_extent,
386            child_cross_axis_extent,
387            axis_direction_is_reversed(constraints.cross_axis_direction),
388        ))
389    }
390
391    fn should_relayout(&self, old_delegate: &dyn SliverGridDelegate) -> bool {
392        let Some(old) = old_delegate.as_any().downcast_ref::<Self>() else {
393            return true;
394        };
395        old.cross_axis_count != self.cross_axis_count
396            || old.main_axis_spacing != self.main_axis_spacing
397            || old.cross_axis_spacing != self.cross_axis_spacing
398            || old.child_aspect_ratio != self.child_aspect_ratio
399            || old.main_axis_extent != self.main_axis_extent
400    }
401
402    fn as_any(&self) -> &dyn Any {
403        self
404    }
405}
406
407/// Creates grid layouts with tiles that each have a maximum cross-axis extent.
408///
409/// This delegate will select a cross-axis extent for the tiles that is as large as possible
410/// subject to the following conditions:
411///
412///  - The extent evenly divides the cross-axis extent of the grid.
413///  - The extent is at most [`max_cross_axis_extent`](Self::max_cross_axis_extent).
414///
415/// For example, if the grid is vertical, the grid is 500.0 pixels wide, and
416/// `max_cross_axis_extent` is 150.0, this delegate will create a grid with 4 columns that are
417/// 125.0 pixels wide.
418///
419/// This delegate creates grids with equally sized and spaced tiles.
420///
421/// Dart's named constructor arguments are the fluent setters.
422///
423/// See also:
424///
425///  * [`SliverGridDelegateWithFixedCrossAxisCount`], which creates a layout with a fixed number
426///    of tiles in the cross axis.
427///  * [`SliverGridDelegate`], which creates arbitrary layouts.
428///  * [`RenderSliverGrid`], which can use this delegate to control the layout of its tiles.
429#[derive(Clone, Debug)]
430pub struct SliverGridDelegateWithMaxCrossAxisExtent {
431    /// The maximum extent of tiles in the cross axis.
432    pub max_cross_axis_extent: f64,
433    /// The number of logical pixels between each child along the main axis.
434    pub main_axis_spacing: f64,
435    /// The number of logical pixels between each child along the cross axis.
436    pub cross_axis_spacing: f64,
437    /// The ratio of the cross-axis to the main-axis extent of each child.
438    pub child_aspect_ratio: f64,
439    /// The extent of each tile in the main axis. If provided it would define the logical pixels
440    /// taken by each tile in the main-axis.
441    ///
442    /// If `None`, [`child_aspect_ratio`](Self::child_aspect_ratio) is used instead.
443    pub main_axis_extent: Option<f64>,
444}
445
446impl SliverGridDelegateWithMaxCrossAxisExtent {
447    /// Creates a delegate that makes grid layouts with tiles that have a maximum cross-axis
448    /// extent.
449    ///
450    /// The `max_cross_axis_extent` must be greater than zero.
451    pub fn new(max_cross_axis_extent: f64) -> SliverGridDelegateWithMaxCrossAxisExtent {
452        debug_assert!(max_cross_axis_extent > 0.0);
453        SliverGridDelegateWithMaxCrossAxisExtent {
454            max_cross_axis_extent,
455            main_axis_spacing: 0.0,
456            cross_axis_spacing: 0.0,
457            child_aspect_ratio: 1.0,
458            main_axis_extent: None,
459        }
460    }
461
462    /// Dart `SliverGridDelegateWithMaxCrossAxisExtent(mainAxisSpacing:)`. Must not be negative.
463    pub fn main_axis_spacing(mut self, value: f64) -> Self {
464        debug_assert!(value >= 0.0);
465        self.main_axis_spacing = value;
466        self
467    }
468
469    /// Dart `SliverGridDelegateWithMaxCrossAxisExtent(crossAxisSpacing:)`. Must not be negative.
470    pub fn cross_axis_spacing(mut self, value: f64) -> Self {
471        debug_assert!(value >= 0.0);
472        self.cross_axis_spacing = value;
473        self
474    }
475
476    /// Dart `SliverGridDelegateWithMaxCrossAxisExtent(childAspectRatio:)`. Must be greater than
477    /// zero.
478    pub fn child_aspect_ratio(mut self, value: f64) -> Self {
479        debug_assert!(value > 0.0);
480        self.child_aspect_ratio = value;
481        self
482    }
483
484    /// Dart `SliverGridDelegateWithMaxCrossAxisExtent(mainAxisExtent:)`. Must not be negative.
485    pub fn main_axis_extent(mut self, value: f64) -> Self {
486        debug_assert!(value >= 0.0);
487        self.main_axis_extent = Some(value);
488        self
489    }
490
491    fn debug_assert_is_valid(&self, cross_axis_extent: f64) -> bool {
492        debug_assert!(cross_axis_extent > 0.0);
493        debug_assert!(self.max_cross_axis_extent > 0.0);
494        debug_assert!(self.main_axis_spacing >= 0.0);
495        debug_assert!(self.cross_axis_spacing >= 0.0);
496        debug_assert!(self.child_aspect_ratio > 0.0);
497        true
498    }
499}
500
501impl SliverGridDelegate for SliverGridDelegateWithMaxCrossAxisExtent {
502    fn get_layout(&self, constraints: SliverConstraints) -> Box<dyn SliverGridLayout> {
503        debug_assert!(self.debug_assert_is_valid(constraints.cross_axis_extent));
504        let cross_axis_count = (constraints.cross_axis_extent
505            / (self.max_cross_axis_extent + self.cross_axis_spacing))
506            .ceil() as i32;
507        // Ensure a minimum count of 1, can be zero and result in an infinite extent
508        // below when the window size is 0.
509        let cross_axis_count = cross_axis_count.max(1);
510        let usable_cross_axis_extent = (constraints.cross_axis_extent
511            - self.cross_axis_spacing * f64::from(cross_axis_count - 1))
512        .max(0.0);
513        let child_cross_axis_extent = usable_cross_axis_extent / f64::from(cross_axis_count);
514        let child_main_axis_extent = self
515            .main_axis_extent
516            .unwrap_or(child_cross_axis_extent / self.child_aspect_ratio);
517        Box::new(SliverGridRegularTileLayout::new(
518            cross_axis_count,
519            child_main_axis_extent + self.main_axis_spacing,
520            child_cross_axis_extent + self.cross_axis_spacing,
521            child_main_axis_extent,
522            child_cross_axis_extent,
523            axis_direction_is_reversed(constraints.cross_axis_direction),
524        ))
525    }
526
527    fn should_relayout(&self, old_delegate: &dyn SliverGridDelegate) -> bool {
528        let Some(old) = old_delegate.as_any().downcast_ref::<Self>() else {
529            return true;
530        };
531        old.max_cross_axis_extent != self.max_cross_axis_extent
532            || old.main_axis_spacing != self.main_axis_spacing
533            || old.cross_axis_spacing != self.cross_axis_spacing
534            || old.child_aspect_ratio != self.child_aspect_ratio
535            || old.main_axis_extent != self.main_axis_extent
536    }
537
538    fn as_any(&self) -> &dyn Any {
539        self
540    }
541}
542
543/// Parent data structure used by [`RenderSliverGrid`].
544#[derive(Debug, Default)]
545pub struct SliverGridParentData {
546    adaptor: SliverMultiBoxAdaptorParentData,
547    /// The offset of the child in the non-scrolling axis.
548    ///
549    /// If the scroll axis is vertical, this offset is from the left-most edge of the parent to
550    /// the left-most edge of the child. If the scroll axis is horizontal, this offset is from the
551    /// top-most edge of the parent to the top-most edge of the child.
552    pub cross_axis_offset: Option<f64>,
553}
554
555impl SliverGridParentData {
556    /// Creates parent data with no index, layout offset or cross-axis offset.
557    pub const fn new() -> SliverGridParentData {
558        SliverGridParentData {
559            adaptor: SliverMultiBoxAdaptorParentData::new(),
560            cross_axis_offset: None,
561        }
562    }
563}
564
565impl ParentData for SliverGridParentData {
566    fn detach(&mut self) {
567        ParentData::detach(&mut self.adaptor);
568    }
569
570    fn provide(&self, id: TypeId) -> Option<&dyn Any> {
571        if id == TypeId::of::<SliverGridParentData>() {
572            return Some(self);
573        }
574        self.adaptor.provide(id)
575    }
576
577    fn provide_mut(&mut self, id: TypeId) -> Option<&mut dyn Any> {
578        if id == TypeId::of::<SliverGridParentData>() {
579            return Some(self);
580        }
581        self.adaptor.provide_mut(id)
582    }
583}
584
585impl ContainerParentDataMixin for SliverGridParentData {
586    type ChildType = AnyRenderBox;
587
588    fn container_parent_data(&self) -> &ContainerParentData<AnyRenderBox> {
589        self.adaptor.container_parent_data()
590    }
591
592    fn container_parent_data_mut(&mut self) -> &mut ContainerParentData<AnyRenderBox> {
593        self.adaptor.container_parent_data_mut()
594    }
595}
596
597impl Display for SliverGridParentData {
598    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
599        write!(
600            f,
601            "crossAxisOffset={:?}; {}",
602            self.cross_axis_offset, self.adaptor
603        )
604    }
605}
606
607/// A sliver that places multiple box children in a two dimensional arrangement.
608///
609/// [`RenderSliverGrid`] places its children in arbitrary positions determined by
610/// [`grid_delegate`](Self::grid_delegate). Each child is forced to have the size specified by
611/// the `grid_delegate`.
612///
613/// See also:
614///
615///  * [`RenderSliverList`](crate::RenderSliverList), which places its children in a linear array.
616///  * [`RenderSliverFixedExtentList`](crate::RenderSliverFixedExtentList), which places its
617///    children in a linear array with a fixed extent in the main axis.
618pub struct RenderSliverGrid {
619    render_object: RenderObjectData,
620    render_sliver: RenderSliverData,
621    container: ContainerRenderObjectData<AnyRenderBox>,
622    adaptor: RenderSliverMultiBoxAdaptorData,
623    grid_delegate: Rc<dyn SliverGridDelegate>,
624}
625
626impl RenderSliverGrid {
627    /// Creates a sliver that contains multiple box children whose size and position are
628    /// determined by a delegate.
629    pub fn new(
630        app: &mut App,
631        child_manager: Rc<dyn RenderSliverBoxChildManager>,
632        grid_delegate: Rc<dyn SliverGridDelegate>,
633    ) -> RenderHandle<RenderSliverGrid> {
634        RenderHandle::new_sliver(
635            app,
636            RenderSliverGrid {
637                render_object: RenderObjectData::new(),
638                render_sliver: RenderSliverData::new(),
639                container: ContainerRenderObjectData::new(),
640                adaptor: RenderSliverMultiBoxAdaptorData::new(child_manager),
641                grid_delegate,
642            },
643        )
644    }
645
646    /// The delegate that controls the size and position of the children.
647    pub fn grid_delegate(self: RenderHandle<Self>, app: &App) -> Rc<dyn SliverGridDelegate> {
648        Rc::clone(&self.get(app).grid_delegate)
649    }
650
651    /// Sets [`grid_delegate`](Self::grid_delegate).
652    pub fn set_grid_delegate(
653        self: RenderHandle<Self>,
654        app: &mut App,
655        value: Rc<dyn SliverGridDelegate>,
656    ) {
657        let old = self.grid_delegate(app);
658        if Rc::ptr_eq(&old, &value) {
659            return;
660        }
661        if value.as_any().type_id() != old.as_any().type_id() || value.should_relayout(&*old) {
662            self.mark_needs_layout(app);
663        }
664        self.get_mut(app).grid_delegate = value;
665    }
666
667    /// Stores where `child` was laid out, from `geometry`.
668    fn place(app: &mut App, child: AnyRenderBox, geometry: SliverGridGeometry) {
669        let child_parent_data = child
670            .as_object()
671            .parent_data_of_mut::<SliverGridParentData>(app);
672        child_parent_data
673            .adaptor
674            .set_layout_offset(Some(geometry.scroll_offset));
675        child_parent_data.cross_axis_offset = Some(geometry.cross_axis_offset);
676    }
677}
678
679impl ContainerRenderObjectMixin for RenderSliverGrid {
680    type ChildType = AnyRenderBox;
681    type ParentDataType = SliverMultiBoxAdaptorParentData;
682
683    fn container_data(
684        self: RenderHandle<Self>,
685        app: &App,
686    ) -> &ContainerRenderObjectData<AnyRenderBox> {
687        &self.get(app).container
688    }
689
690    fn container_data_mut(
691        self: RenderHandle<Self>,
692        app: &mut App,
693    ) -> &mut ContainerRenderObjectData<AnyRenderBox> {
694        &mut self.get_mut(app).container
695    }
696
697    fn insert(
698        self: RenderHandle<Self>,
699        app: &mut App,
700        child: AnyRenderBox,
701        after: Option<AnyRenderBox>,
702    ) {
703        RenderSliverMultiBoxAdaptor::insert(self, app, child, after)
704    }
705
706    fn move_child(
707        self: RenderHandle<Self>,
708        app: &mut App,
709        child: AnyRenderBox,
710        after: Option<AnyRenderBox>,
711    ) {
712        RenderSliverMultiBoxAdaptor::move_child(self, app, child, after)
713    }
714
715    fn remove(self: RenderHandle<Self>, app: &mut App, child: AnyRenderBox) {
716        RenderSliverMultiBoxAdaptor::remove(self, app, child)
717    }
718
719    fn remove_all(self: RenderHandle<Self>, app: &mut App) {
720        RenderSliverMultiBoxAdaptor::remove_all(self, app)
721    }
722}
723
724impl RenderSliverHelpers for RenderSliverGrid {}
725
726impl RenderSliverWithKeepAliveMixin for RenderSliverGrid {}
727
728impl RenderSliverMultiBoxAdaptor for RenderSliverGrid {
729    crate::render_sliver_multi_box_adaptor_accessors!();
730}
731
732impl RenderObject for RenderSliverGrid {
733    crate::render_object_accessors!();
734
735    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
736        if !child.parent_data_is::<SliverGridParentData>(app) {
737            child.set_parent_data(app, SliverGridParentData::new());
738        }
739    }
740
741    fn visit_children(
742        self: RenderHandle<Self>,
743        app: &App,
744        visitor: &mut dyn FnMut(AnyRenderObject),
745    ) {
746        RenderSliverMultiBoxAdaptor::visit_children(self, app, visitor)
747    }
748
749    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
750        RenderSliverMultiBoxAdaptor::did_attach(self, app, owner)
751    }
752
753    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
754        RenderSliverMultiBoxAdaptor::did_detach(self, app)
755    }
756
757    fn redepth_children(self: RenderHandle<Self>, app: &mut App) {
758        RenderSliverMultiBoxAdaptor::redepth_children(self, app)
759    }
760
761    fn apply_paint_transform(
762        self: RenderHandle<Self>,
763        app: &App,
764        child: AnyRenderObject,
765        transform: &mut Matrix4,
766    ) {
767        RenderSliverMultiBoxAdaptor::apply_paint_transform(self, app, child, transform)
768    }
769
770    fn paints_child(self: RenderHandle<Self>, app: &App, child: AnyRenderObject) -> bool {
771        RenderSliverMultiBoxAdaptor::paints_child(self, app, child)
772    }
773
774    fn paint(
775        self: RenderHandle<Self>,
776        app: &mut App,
777        context: &mut PaintingContext,
778        offset: Offset,
779    ) {
780        RenderSliverMultiBoxAdaptor::paint(self, app, context, offset)
781    }
782
783    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
784        let constraints = self.constraints(app);
785        let child_manager = self.child_manager(app);
786        child_manager.did_start_layout(app);
787        child_manager.set_did_underflow(app, false);
788
789        let scroll_offset = constraints.scroll_offset + constraints.cache_origin;
790        debug_assert!(scroll_offset >= 0.0);
791        let remaining_extent = constraints.remaining_cache_extent;
792        debug_assert!(remaining_extent >= 0.0);
793        let target_end_scroll_offset = scroll_offset + remaining_extent;
794
795        let layout = self.grid_delegate(app).get_layout(constraints);
796
797        let first_index = layout.get_min_child_index_for_scroll_offset(scroll_offset);
798        let target_last_index = target_end_scroll_offset
799            .is_finite()
800            .then(|| layout.get_max_child_index_for_scroll_offset(target_end_scroll_offset));
801
802        if self.first_child(app).is_some() {
803            let leading_garbage = self.calculate_leading_garbage(app, first_index);
804            let trailing_garbage = match target_last_index {
805                Some(last_index) => self.calculate_trailing_garbage(app, last_index),
806                None => 0,
807            };
808            self.collect_garbage(app, leading_garbage, trailing_garbage);
809        } else {
810            self.collect_garbage(app, 0, 0);
811        }
812
813        let first_child_grid_geometry = layout.get_geometry_for_child_index(first_index);
814
815        if self.first_child(app).is_none()
816            && !self.add_initial_child(app, first_index, first_child_grid_geometry.scroll_offset)
817        {
818            // There are either no children, or we are past the end of all our children.
819            let max = layout.compute_max_scroll_offset(child_manager.child_count(app));
820            self.set_geometry(
821                app,
822                SliverGeometry::builder()
823                    .scroll_extent(max)
824                    .max_paint_extent(max)
825                    .build(),
826            );
827            child_manager.did_finish_layout(app);
828            return;
829        }
830
831        let leading_scroll_offset = first_child_grid_geometry.scroll_offset;
832        let mut trailing_scroll_offset = first_child_grid_geometry.trailing_scroll_offset();
833        let mut trailing_child_with_layout: Option<AnyRenderBox> = None;
834        let mut reached_end = false;
835
836        let first_child = self.first_child(app).expect("added above");
837        let mut index = self.index_of(app, first_child) - 1;
838        while index >= first_index {
839            let grid_geometry = layout.get_geometry_for_child_index(index);
840            let child = self
841                .insert_and_layout_leading_child(
842                    app,
843                    grid_geometry.get_box_constraints(constraints),
844                    false,
845                )
846                .expect("the children before the first one are there");
847            Self::place(app, child, grid_geometry);
848            debug_assert_eq!(
849                child
850                    .as_object()
851                    .parent_data_of::<SliverMultiBoxAdaptorParentData>(app)
852                    .index,
853                Some(index)
854            );
855            trailing_child_with_layout.get_or_insert(child);
856            trailing_scroll_offset =
857                trailing_scroll_offset.max(grid_geometry.trailing_scroll_offset());
858            index -= 1;
859        }
860
861        if trailing_child_with_layout.is_none() {
862            let first_child = self.first_child(app).expect("the child list is not empty");
863            first_child.layout(
864                app,
865                first_child_grid_geometry.get_box_constraints(constraints),
866                false,
867            );
868            Self::place(app, first_child, first_child_grid_geometry);
869            trailing_child_with_layout = Some(first_child);
870        }
871
872        let mut index = self.index_of(app, trailing_child_with_layout.expect("set above")) + 1;
873        while target_last_index.is_none_or(|last_index| index <= last_index) {
874            let grid_geometry = layout.get_geometry_for_child_index(index);
875            let child_constraints = grid_geometry.get_box_constraints(constraints);
876            let after = trailing_child_with_layout.expect("set above");
877            let mut child = self.child_after(app, after);
878            if child.is_none_or(|current| self.index_of(app, current) != index) {
879                child = self.insert_and_layout_child(app, child_constraints, Some(after), false);
880                if child.is_none() {
881                    reached_end = true;
882                    // We have run out of children.
883                    break;
884                }
885            } else {
886                child
887                    .expect("checked")
888                    .layout(app, child_constraints, false);
889            }
890            let child = child.expect("set above");
891            trailing_child_with_layout = Some(child);
892            Self::place(app, child, grid_geometry);
893            debug_assert_eq!(
894                child
895                    .as_object()
896                    .parent_data_of::<SliverMultiBoxAdaptorParentData>(app)
897                    .index,
898                Some(index)
899            );
900            trailing_scroll_offset =
901                trailing_scroll_offset.max(grid_geometry.trailing_scroll_offset());
902            index += 1;
903        }
904
905        let last_index = self.index_of(app, self.last_child(app).expect("not empty"));
906
907        debug_assert!(self.debug_assert_child_list_is_non_empty_and_contiguous(app));
908        debug_assert_eq!(
909            self.index_of(app, self.first_child(app).expect("not empty")),
910            first_index
911        );
912        debug_assert!(target_last_index.is_none_or(|target| last_index <= target));
913
914        let estimated_total_extent = if reached_end {
915            trailing_scroll_offset
916        } else {
917            child_manager.estimate_max_scroll_offset(
918                app,
919                constraints,
920                Some(first_index),
921                Some(last_index),
922                Some(leading_scroll_offset),
923                Some(trailing_scroll_offset),
924            )
925        };
926        let paint_extent = calculate_paint_offset(
927            constraints,
928            constraints.scroll_offset.min(leading_scroll_offset),
929            trailing_scroll_offset,
930        );
931        let cache_extent =
932            calculate_cache_offset(constraints, leading_scroll_offset, trailing_scroll_offset);
933
934        self.set_geometry(
935            app,
936            SliverGeometry::builder()
937                .scroll_extent(estimated_total_extent)
938                .paint_extent(paint_extent)
939                .max_paint_extent(estimated_total_extent)
940                .cache_extent(cache_extent)
941                .has_visual_overflow(
942                    estimated_total_extent > paint_extent
943                        || constraints.scroll_offset > 0.0
944                        || constraints.overlap != 0.0,
945                )
946                .build(),
947        );
948
949        // We may have started the layout while scrolled to the end, which
950        // would not expose a new child.
951        if estimated_total_extent == trailing_scroll_offset {
952            child_manager.set_did_underflow(app, true);
953        }
954        child_manager.did_finish_layout(app);
955    }
956}
957
958impl RenderSliver for RenderSliverGrid {
959    crate::render_sliver_accessors!();
960
961    fn hit_test_children(
962        self: RenderHandle<Self>,
963        app: &mut App,
964        result: &mut SliverHitTestResult<'_>,
965        main_axis_position: f64,
966        cross_axis_position: f64,
967    ) -> bool {
968        RenderSliverMultiBoxAdaptor::hit_test_children(
969            self,
970            app,
971            result,
972            main_axis_position,
973            cross_axis_position,
974        )
975    }
976
977    fn child_main_axis_position(
978        self: RenderHandle<Self>,
979        app: &App,
980        child: AnyRenderObject,
981    ) -> f64 {
982        RenderSliverMultiBoxAdaptor::child_main_axis_position(self, app, child)
983    }
984
985    fn child_cross_axis_position(
986        self: RenderHandle<Self>,
987        app: &App,
988        child: AnyRenderObject,
989    ) -> f64 {
990        child
991            .parent_data_of::<SliverGridParentData>(app)
992            .cross_axis_offset
993            .expect("laid out")
994    }
995
996    fn child_scroll_offset(
997        self: RenderHandle<Self>,
998        app: &App,
999        child: AnyRenderObject,
1000    ) -> Option<f64> {
1001        RenderSliverMultiBoxAdaptor::child_scroll_offset(self, app, child)
1002    }
1003}
1004
1005#[cfg(test)]
1006mod tests {
1007    use waft_embedder::Size;
1008    use waft_foundation::AppCell;
1009    use waft_gestures::HitTestResult;
1010    use waft_painting::AxisDirection;
1011
1012    use super::*;
1013    use crate::sliver::GrowthDirection;
1014    use crate::sliver_multi_box_adaptor::test_support::TestChildManager;
1015    use crate::sliver_multi_box_adaptor::viewport_test_support::ScrollHarness;
1016    use crate::viewport_offset::ScrollDirection;
1017
1018    const VIEWPORT: Size = Size::new(500.0, 200.0);
1019
1020    fn sliver_grid(
1021        app: &mut App,
1022        count: usize,
1023        delegate: Rc<dyn SliverGridDelegate>,
1024    ) -> (
1025        RenderHandle<RenderSliverGrid>,
1026        Rc<TestChildManager<RenderSliverGrid>>,
1027        ScrollHarness,
1028    ) {
1029        let manager = TestChildManager::new(vec![1000.0; count]);
1030        let grid = RenderSliverGrid::new(app, manager.clone(), delegate);
1031        manager.attach(grid);
1032        let harness = ScrollHarness::new(app, grid.as_sliver(), VIEWPORT);
1033        (grid, manager, harness)
1034    }
1035
1036    /// Vertical constraints `cross_axis_extent` wide, at the top of a 600 high viewport.
1037    fn constraints(cross_axis_extent: f64) -> SliverConstraints {
1038        SliverConstraints::new(
1039            AxisDirection::Down,
1040            GrowthDirection::Forward,
1041            ScrollDirection::Idle,
1042            0.0,
1043            0.0,
1044            0.0,
1045            600.0,
1046            cross_axis_extent,
1047            AxisDirection::Right,
1048            600.0,
1049            1100.0,
1050            0.0,
1051        )
1052    }
1053
1054    /// Where each child is laid out: its index, scroll offset, cross-axis offset and size.
1055    fn placed(app: &App, grid: RenderHandle<RenderSliverGrid>) -> Vec<(i32, f64, f64, Size)> {
1056        let mut placed = Vec::new();
1057        let mut child = grid.first_child(app);
1058        while let Some(current) = child {
1059            let data = current
1060                .as_object()
1061                .parent_data_of::<SliverGridParentData>(app);
1062            placed.push((
1063                data.adaptor.index.expect("indexed"),
1064                data.adaptor.layout_offset().expect("laid out"),
1065                data.cross_axis_offset.expect("laid out"),
1066                current.size(app),
1067            ));
1068            child = grid.child_after(app, current);
1069        }
1070        placed
1071    }
1072
1073    /// `sliver_grid_test.dart`: the max-extent delegate fits as many columns as it can, each as
1074    /// wide as an even split allows.
1075    #[test]
1076    fn a_max_extent_grid_fits_as_many_columns_as_it_can() {
1077        let delegate = SliverGridDelegateWithMaxCrossAxisExtent::new(150.0);
1078        let layout = delegate.get_layout(constraints(500.0));
1079        let geometry = layout.get_geometry_for_child_index(5);
1080        assert_eq!(geometry.cross_axis_extent, 125.0, "4 columns of 125 in 500");
1081        assert_eq!(geometry.cross_axis_offset, 125.0);
1082        assert_eq!(geometry.scroll_offset, 125.0, "the second row");
1083        assert_eq!(layout.compute_max_scroll_offset(9), 375.0, "3 rows");
1084        assert_eq!(layout.compute_max_scroll_offset(0), 0.0);
1085    }
1086
1087    /// A grid whose cross axis runs right to left places its first column on the right.
1088    #[test]
1089    fn a_reversed_cross_axis_places_the_first_column_last() {
1090        let mut leftward = constraints(400.0);
1091        leftward.cross_axis_direction = AxisDirection::Left;
1092        let layout = SliverGridDelegateWithFixedCrossAxisCount::new(4)
1093            .cross_axis_spacing(20.0)
1094            .get_layout(leftward);
1095        // Columns are 85 wide with 20 between them: the first sits at 400 - 85.
1096        assert_eq!(
1097            layout.get_geometry_for_child_index(0).cross_axis_offset,
1098            315.0
1099        );
1100        assert_eq!(
1101            layout.get_geometry_for_child_index(3).cross_axis_offset,
1102            0.0
1103        );
1104    }
1105
1106    #[test]
1107    fn a_grid_lays_out_only_the_rows_it_shows_with_their_spacing() {
1108        let cell = AppCell::new();
1109        let mut app = cell.borrow_mut();
1110        let delegate = SliverGridDelegateWithFixedCrossAxisCount::new(2)
1111            .main_axis_spacing(10.0)
1112            .cross_axis_spacing(20.0)
1113            .child_aspect_ratio(2.0);
1114        let (grid, manager, _harness) = sliver_grid(&mut app, 100, Rc::new(delegate));
1115        // Each tile is (500 - 20) / 2 = 240 wide and 120 tall, so rows are 130 apart: the 200
1116        // high viewport and its 250 of cache reach into the fourth row.
1117        let placed = placed(&app, grid);
1118        assert_eq!(
1119            placed[..3],
1120            [
1121                (0, 0.0, 0.0, Size::new(240.0, 120.0)),
1122                (1, 0.0, 260.0, Size::new(240.0, 120.0)),
1123                (2, 130.0, 0.0, Size::new(240.0, 120.0)),
1124            ]
1125        );
1126        assert_eq!(placed.len(), 8, "four rows of two");
1127        assert!(manager.created.borrow().iter().all(|index| *index < 8));
1128    }
1129
1130    #[test]
1131    fn scrolling_a_grid_replaces_its_rows() {
1132        let cell = AppCell::new();
1133        let mut app = cell.borrow_mut();
1134        let delegate = SliverGridDelegateWithFixedCrossAxisCount::new(4).main_axis_extent(100.0);
1135        let (grid, _, harness) = sliver_grid(&mut app, 100, Rc::new(delegate));
1136        harness.scroll_to(&mut app, 1000.0);
1137        let placed = placed(&app, grid);
1138        // The cache reaches 250 before the scroll offset, to 750: row 7, which starts at 700.
1139        assert_eq!((placed[0].0, placed[0].1), (28, 700.0));
1140        assert!(placed.iter().all(|(index, ..)| *index >= 28));
1141        assert!(grid.geometry(&app).has_visual_overflow);
1142    }
1143
1144    #[test]
1145    fn a_short_grid_reports_its_exact_extent() {
1146        let cell = AppCell::new();
1147        let mut app = cell.borrow_mut();
1148        let delegate = SliverGridDelegateWithFixedCrossAxisCount::new(4).main_axis_extent(50.0);
1149        let (grid, manager, _harness) = sliver_grid(&mut app, 6, Rc::new(delegate));
1150        let geometry = grid.geometry(&app);
1151        assert_eq!(geometry.scroll_extent, 100.0, "two rows of 50");
1152        assert_eq!(geometry.paint_extent, 100.0);
1153        assert!(!geometry.has_visual_overflow);
1154        assert!(manager.did_underflow.get());
1155    }
1156
1157    /// A hit lands on the tile under it, which only its cross-axis offset tells apart from the
1158    /// others in its row.
1159    #[test]
1160    fn a_grid_hit_tests_the_tile_under_the_point() {
1161        let cell = AppCell::new();
1162        let mut app = cell.borrow_mut();
1163        let delegate = SliverGridDelegateWithFixedCrossAxisCount::new(5).main_axis_extent(100.0);
1164        let (grid, _, _harness) = sliver_grid(&mut app, 20, Rc::new(delegate));
1165        let tile = placed(&app, grid)
1166            .iter()
1167            .position(|(index, ..)| *index == 8)
1168            .expect("tile 8 is laid out");
1169        let mut child = grid.first_child(&app).expect("tiles");
1170        for _ in 0..tile {
1171            child = grid.child_after(&app, child).expect("tile");
1172        }
1173        assert_eq!(
1174            RenderSliver::child_cross_axis_position(grid, &app, child.as_object()),
1175            300.0
1176        );
1177
1178        let mut result = HitTestResult::new();
1179        let hit = grid.hit_test(
1180            &mut app,
1181            &mut SliverHitTestResult::wrap(&mut result),
1182            150.0,
1183            350.0,
1184        );
1185        assert!(hit);
1186        assert_eq!(result.path().len(), 2, "tile 8 and the grid");
1187    }
1188
1189    #[test]
1190    fn a_new_delegate_relays_out_only_when_it_changes_the_tiles() {
1191        let cell = AppCell::new();
1192        let mut app = cell.borrow_mut();
1193        let delegate = SliverGridDelegateWithFixedCrossAxisCount::new(2);
1194        let (grid, _, harness) = sliver_grid(&mut app, 10, Rc::new(delegate.clone()));
1195        grid.set_grid_delegate(&mut app, Rc::new(delegate.clone()));
1196        assert!(!grid.as_object().debug_needs_layout(&app), "the same tiles");
1197        grid.set_grid_delegate(&mut app, Rc::new(delegate.main_axis_spacing(4.0)));
1198        assert!(grid.as_object().debug_needs_layout(&app));
1199        harness.owner.flush_layout(&mut app);
1200        grid.set_grid_delegate(
1201            &mut app,
1202            Rc::new(SliverGridDelegateWithMaxCrossAxisExtent::new(250.0)),
1203        );
1204        assert!(
1205            grid.as_object().debug_needs_layout(&app),
1206            "another kind of delegate"
1207        );
1208    }
1209}