1use std::any::{Any, TypeId};
4use std::fmt::{self, Debug, Display};
5use std::rc::Rc;
6
7use waft_embedder::{Matrix4, Offset};
8use waft_foundation::{
9 App, DiagnosticPropertiesBuilder, DiagnosticsNode, Handle, PRECISION_ERROR_TOLERANCE,
10 display_or_null,
11};
12use waft_painting::axis_direction_is_reversed;
13
14use crate::box_::{AnyRenderBox, BoxConstraints};
15use crate::object::{
16 AnyRenderObject, ContainerParentData, ContainerParentDataMixin, ContainerRenderObjectData,
17 ContainerRenderObjectMixin, ParentData, RenderHandle, RenderObject, RenderObjectData,
18};
19use crate::painting_context::PaintingContext;
20use crate::pipeline_owner::PipelineOwner;
21use crate::sliver::{
22 RenderSliver, RenderSliverData, RenderSliverHelpers, SliverConstraints, SliverGeometry,
23 SliverHitTestResult, calculate_cache_offset, calculate_paint_offset,
24};
25use crate::sliver_multi_box_adaptor::{
26 RenderSliverBoxChildManager, RenderSliverMultiBoxAdaptor, RenderSliverMultiBoxAdaptorData,
27 RenderSliverWithKeepAliveMixin, SliverMultiBoxAdaptorParentData,
28};
29
30#[derive(Clone, Copy)]
43pub struct SliverGridGeometry {
44 pub scroll_offset: f64,
47 pub cross_axis_offset: f64,
53 pub main_axis_extent: f64,
58 pub cross_axis_extent: f64,
63}
64
65impl SliverGridGeometry {
66 pub const fn new(
68 scroll_offset: f64,
69 cross_axis_offset: f64,
70 main_axis_extent: f64,
71 cross_axis_extent: f64,
72 ) -> SliverGridGeometry {
73 SliverGridGeometry {
74 scroll_offset,
75 cross_axis_offset,
76 main_axis_extent,
77 cross_axis_extent,
78 }
79 }
80
81 pub fn trailing_scroll_offset(&self) -> f64 {
84 self.scroll_offset + self.main_axis_extent
85 }
86
87 pub fn get_box_constraints(&self, constraints: SliverConstraints) -> BoxConstraints {
90 constraints.as_box_constraints(
91 self.main_axis_extent,
92 self.main_axis_extent,
93 Some(self.cross_axis_extent),
94 )
95 }
96}
97
98impl Debug for SliverGridGeometry {
99 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100 write!(
101 f,
102 "SliverGridGeometry(scrollOffset: {}, crossAxisOffset: {}, mainAxisExtent: {}, crossAxisExtent: {})",
103 self.scroll_offset,
104 self.cross_axis_offset,
105 self.main_axis_extent,
106 self.cross_axis_extent
107 )
108 }
109}
110
111pub trait SliverGridLayout: Debug {
131 fn get_min_child_index_for_scroll_offset(&self, scroll_offset: f64) -> i32;
133
134 fn get_max_child_index_for_scroll_offset(&self, scroll_offset: f64) -> i32;
136
137 fn get_geometry_for_child_index(&self, index: i32) -> SliverGridGeometry;
139
140 fn compute_max_scroll_offset(&self, child_count: i32) -> f64;
143}
144
145#[derive(Clone, Copy, Debug)]
154pub struct SliverGridRegularTileLayout {
155 pub cross_axis_count: i32,
157 pub main_axis_stride: f64,
160 pub cross_axis_stride: f64,
163 pub child_main_axis_extent: f64,
166 pub child_cross_axis_extent: f64,
169 pub reverse_cross_axis: bool,
179}
180
181impl SliverGridRegularTileLayout {
182 pub fn new(
187 cross_axis_count: i32,
188 main_axis_stride: f64,
189 cross_axis_stride: f64,
190 child_main_axis_extent: f64,
191 child_cross_axis_extent: f64,
192 reverse_cross_axis: bool,
193 ) -> SliverGridRegularTileLayout {
194 debug_assert!(cross_axis_count > 0);
195 debug_assert!(main_axis_stride >= 0.0);
196 debug_assert!(cross_axis_stride >= 0.0);
197 debug_assert!(child_main_axis_extent >= 0.0);
198 debug_assert!(child_cross_axis_extent >= 0.0);
199 SliverGridRegularTileLayout {
200 cross_axis_count,
201 main_axis_stride,
202 cross_axis_stride,
203 child_main_axis_extent,
204 child_cross_axis_extent,
205 reverse_cross_axis,
206 }
207 }
208
209 fn get_offset_from_start_in_cross_axis(&self, cross_axis_start: f64) -> f64 {
210 if self.reverse_cross_axis {
211 return f64::from(self.cross_axis_count) * self.cross_axis_stride
212 - cross_axis_start
213 - self.child_cross_axis_extent
214 - (self.cross_axis_stride - self.child_cross_axis_extent);
215 }
216 cross_axis_start
217 }
218}
219
220impl SliverGridLayout for SliverGridRegularTileLayout {
221 fn get_min_child_index_for_scroll_offset(&self, scroll_offset: f64) -> i32 {
222 if self.main_axis_stride > PRECISION_ERROR_TOLERANCE {
223 self.cross_axis_count * (scroll_offset / self.main_axis_stride).trunc() as i32
224 } else {
225 0
226 }
227 }
228
229 fn get_max_child_index_for_scroll_offset(&self, scroll_offset: f64) -> i32 {
230 if self.main_axis_stride > 0.0 {
231 let main_axis_count = (scroll_offset / self.main_axis_stride).ceil() as i32;
232 return (self.cross_axis_count * main_axis_count - 1).max(0);
233 }
234 0
235 }
236
237 fn get_geometry_for_child_index(&self, index: i32) -> SliverGridGeometry {
238 let cross_axis_start = f64::from(index % self.cross_axis_count) * self.cross_axis_stride;
239 SliverGridGeometry::new(
240 f64::from(index / self.cross_axis_count) * self.main_axis_stride,
241 self.get_offset_from_start_in_cross_axis(cross_axis_start),
242 self.child_main_axis_extent,
243 self.child_cross_axis_extent,
244 )
245 }
246
247 fn compute_max_scroll_offset(&self, child_count: i32) -> f64 {
248 if child_count == 0 {
249 return 0.0;
251 }
252 let main_axis_count = ((child_count - 1) / self.cross_axis_count) + 1;
253 let main_axis_spacing = self.main_axis_stride - self.child_main_axis_extent;
254 self.main_axis_stride * f64::from(main_axis_count) - main_axis_spacing
255 }
256}
257
258pub trait SliverGridDelegate: Debug {
274 fn get_layout(&self, constraints: SliverConstraints) -> Box<dyn SliverGridLayout>;
276
277 fn should_relayout(&self, old_delegate: &dyn SliverGridDelegate) -> bool;
283
284 fn as_any(&self) -> &dyn Any;
286}
287
288#[derive(Clone, Debug)]
305pub struct SliverGridDelegateWithFixedCrossAxisCount {
306 pub cross_axis_count: i32,
308 pub main_axis_spacing: f64,
310 pub cross_axis_spacing: f64,
312 pub child_aspect_ratio: f64,
314 pub main_axis_extent: Option<f64>,
319}
320
321impl SliverGridDelegateWithFixedCrossAxisCount {
322 pub fn new(cross_axis_count: i32) -> SliverGridDelegateWithFixedCrossAxisCount {
326 debug_assert!(cross_axis_count > 0);
327 SliverGridDelegateWithFixedCrossAxisCount {
328 cross_axis_count,
329 main_axis_spacing: 0.0,
330 cross_axis_spacing: 0.0,
331 child_aspect_ratio: 1.0,
332 main_axis_extent: None,
333 }
334 }
335
336 pub fn main_axis_spacing(mut self, value: f64) -> Self {
338 debug_assert!(value >= 0.0);
339 self.main_axis_spacing = value;
340 self
341 }
342
343 pub fn cross_axis_spacing(mut self, value: f64) -> Self {
345 debug_assert!(value >= 0.0);
346 self.cross_axis_spacing = value;
347 self
348 }
349
350 pub fn child_aspect_ratio(mut self, value: f64) -> Self {
353 debug_assert!(value > 0.0);
354 self.child_aspect_ratio = value;
355 self
356 }
357
358 pub fn main_axis_extent(mut self, value: f64) -> Self {
360 debug_assert!(value >= 0.0);
361 self.main_axis_extent = Some(value);
362 self
363 }
364
365 fn debug_assert_is_valid(&self) -> bool {
366 debug_assert!(self.cross_axis_count > 0);
367 debug_assert!(self.main_axis_spacing >= 0.0);
368 debug_assert!(self.cross_axis_spacing >= 0.0);
369 debug_assert!(self.child_aspect_ratio > 0.0);
370 true
371 }
372}
373
374impl SliverGridDelegate for SliverGridDelegateWithFixedCrossAxisCount {
375 fn get_layout(&self, constraints: SliverConstraints) -> Box<dyn SliverGridLayout> {
376 debug_assert!(self.debug_assert_is_valid());
377 let usable_cross_axis_extent = (constraints.cross_axis_extent
378 - self.cross_axis_spacing * f64::from(self.cross_axis_count - 1))
379 .max(0.0);
380 let child_cross_axis_extent = usable_cross_axis_extent / f64::from(self.cross_axis_count);
381 let child_main_axis_extent = self
382 .main_axis_extent
383 .unwrap_or(child_cross_axis_extent / self.child_aspect_ratio);
384 Box::new(SliverGridRegularTileLayout::new(
385 self.cross_axis_count,
386 child_main_axis_extent + self.main_axis_spacing,
387 child_cross_axis_extent + self.cross_axis_spacing,
388 child_main_axis_extent,
389 child_cross_axis_extent,
390 axis_direction_is_reversed(constraints.cross_axis_direction),
391 ))
392 }
393
394 fn should_relayout(&self, old_delegate: &dyn SliverGridDelegate) -> bool {
395 let Some(old) = old_delegate.as_any().downcast_ref::<Self>() else {
396 return true;
397 };
398 old.cross_axis_count != self.cross_axis_count
399 || old.main_axis_spacing != self.main_axis_spacing
400 || old.cross_axis_spacing != self.cross_axis_spacing
401 || old.child_aspect_ratio != self.child_aspect_ratio
402 || old.main_axis_extent != self.main_axis_extent
403 }
404
405 fn as_any(&self) -> &dyn Any {
406 self
407 }
408}
409
410#[derive(Clone, Debug)]
433pub struct SliverGridDelegateWithMaxCrossAxisExtent {
434 pub max_cross_axis_extent: f64,
436 pub main_axis_spacing: f64,
438 pub cross_axis_spacing: f64,
440 pub child_aspect_ratio: f64,
442 pub main_axis_extent: Option<f64>,
447}
448
449impl SliverGridDelegateWithMaxCrossAxisExtent {
450 pub fn new(max_cross_axis_extent: f64) -> SliverGridDelegateWithMaxCrossAxisExtent {
455 debug_assert!(max_cross_axis_extent > 0.0);
456 SliverGridDelegateWithMaxCrossAxisExtent {
457 max_cross_axis_extent,
458 main_axis_spacing: 0.0,
459 cross_axis_spacing: 0.0,
460 child_aspect_ratio: 1.0,
461 main_axis_extent: None,
462 }
463 }
464
465 pub fn main_axis_spacing(mut self, value: f64) -> Self {
467 debug_assert!(value >= 0.0);
468 self.main_axis_spacing = value;
469 self
470 }
471
472 pub fn cross_axis_spacing(mut self, value: f64) -> Self {
474 debug_assert!(value >= 0.0);
475 self.cross_axis_spacing = value;
476 self
477 }
478
479 pub fn child_aspect_ratio(mut self, value: f64) -> Self {
482 debug_assert!(value > 0.0);
483 self.child_aspect_ratio = value;
484 self
485 }
486
487 pub fn main_axis_extent(mut self, value: f64) -> Self {
489 debug_assert!(value >= 0.0);
490 self.main_axis_extent = Some(value);
491 self
492 }
493
494 fn debug_assert_is_valid(&self, cross_axis_extent: f64) -> bool {
495 debug_assert!(cross_axis_extent > 0.0);
496 debug_assert!(self.max_cross_axis_extent > 0.0);
497 debug_assert!(self.main_axis_spacing >= 0.0);
498 debug_assert!(self.cross_axis_spacing >= 0.0);
499 debug_assert!(self.child_aspect_ratio > 0.0);
500 true
501 }
502}
503
504impl SliverGridDelegate for SliverGridDelegateWithMaxCrossAxisExtent {
505 fn get_layout(&self, constraints: SliverConstraints) -> Box<dyn SliverGridLayout> {
506 debug_assert!(self.debug_assert_is_valid(constraints.cross_axis_extent));
507 let cross_axis_count = (constraints.cross_axis_extent
508 / (self.max_cross_axis_extent + self.cross_axis_spacing))
509 .ceil() as i32;
510 let cross_axis_count = cross_axis_count.max(1);
513 let usable_cross_axis_extent = (constraints.cross_axis_extent
514 - self.cross_axis_spacing * f64::from(cross_axis_count - 1))
515 .max(0.0);
516 let child_cross_axis_extent = usable_cross_axis_extent / f64::from(cross_axis_count);
517 let child_main_axis_extent = self
518 .main_axis_extent
519 .unwrap_or(child_cross_axis_extent / self.child_aspect_ratio);
520 Box::new(SliverGridRegularTileLayout::new(
521 cross_axis_count,
522 child_main_axis_extent + self.main_axis_spacing,
523 child_cross_axis_extent + self.cross_axis_spacing,
524 child_main_axis_extent,
525 child_cross_axis_extent,
526 axis_direction_is_reversed(constraints.cross_axis_direction),
527 ))
528 }
529
530 fn should_relayout(&self, old_delegate: &dyn SliverGridDelegate) -> bool {
531 let Some(old) = old_delegate.as_any().downcast_ref::<Self>() else {
532 return true;
533 };
534 old.max_cross_axis_extent != self.max_cross_axis_extent
535 || old.main_axis_spacing != self.main_axis_spacing
536 || old.cross_axis_spacing != self.cross_axis_spacing
537 || old.child_aspect_ratio != self.child_aspect_ratio
538 || old.main_axis_extent != self.main_axis_extent
539 }
540
541 fn as_any(&self) -> &dyn Any {
542 self
543 }
544}
545
546#[derive(Debug, Default)]
548pub struct SliverGridParentData {
549 adaptor: SliverMultiBoxAdaptorParentData,
550 pub cross_axis_offset: Option<f64>,
556}
557
558impl SliverGridParentData {
559 pub const fn new() -> SliverGridParentData {
561 SliverGridParentData {
562 adaptor: SliverMultiBoxAdaptorParentData::new(),
563 cross_axis_offset: None,
564 }
565 }
566}
567
568impl ParentData for SliverGridParentData {
569 fn detach(&mut self) {
570 ParentData::detach(&mut self.adaptor);
571 }
572
573 fn provide(&self, id: TypeId) -> Option<&dyn Any> {
574 if id == TypeId::of::<SliverGridParentData>() {
575 return Some(self);
576 }
577 self.adaptor.provide(id)
578 }
579
580 fn provide_mut(&mut self, id: TypeId) -> Option<&mut dyn Any> {
581 if id == TypeId::of::<SliverGridParentData>() {
582 return Some(self);
583 }
584 self.adaptor.provide_mut(id)
585 }
586}
587
588impl ContainerParentDataMixin for SliverGridParentData {
589 type ChildType = AnyRenderBox;
590
591 fn container_parent_data(&self) -> &ContainerParentData<AnyRenderBox> {
592 self.adaptor.container_parent_data()
593 }
594
595 fn container_parent_data_mut(&mut self) -> &mut ContainerParentData<AnyRenderBox> {
596 self.adaptor.container_parent_data_mut()
597 }
598}
599
600impl Display for SliverGridParentData {
601 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
602 write!(
603 f,
604 "crossAxisOffset={}; {}",
605 display_or_null(&self.cross_axis_offset.map(|offset| format!("{offset:?}"))),
606 self.adaptor
607 )
608 }
609}
610
611pub struct RenderSliverGrid {
623 render_object: RenderObjectData,
624 render_sliver: RenderSliverData,
625 container: ContainerRenderObjectData<AnyRenderBox>,
626 adaptor: RenderSliverMultiBoxAdaptorData,
627 grid_delegate: Rc<dyn SliverGridDelegate>,
628}
629
630impl RenderSliverGrid {
631 pub fn new(
634 app: &mut App,
635 child_manager: Rc<dyn RenderSliverBoxChildManager>,
636 grid_delegate: Rc<dyn SliverGridDelegate>,
637 ) -> RenderHandle<RenderSliverGrid> {
638 RenderHandle::new_sliver(
639 app,
640 RenderSliverGrid {
641 render_object: RenderObjectData::new(),
642 render_sliver: RenderSliverData::new(),
643 container: ContainerRenderObjectData::new(),
644 adaptor: RenderSliverMultiBoxAdaptorData::new(child_manager),
645 grid_delegate,
646 },
647 )
648 }
649
650 pub fn grid_delegate(self: RenderHandle<Self>, app: &App) -> Rc<dyn SliverGridDelegate> {
652 Rc::clone(&self.get(app).grid_delegate)
653 }
654
655 pub fn set_grid_delegate(
657 self: RenderHandle<Self>,
658 app: &mut App,
659 value: Rc<dyn SliverGridDelegate>,
660 ) {
661 let old = self.grid_delegate(app);
662 if Rc::ptr_eq(&old, &value) {
663 return;
664 }
665 if value.as_any().type_id() != old.as_any().type_id() || value.should_relayout(&*old) {
666 self.mark_needs_layout(app);
667 }
668 self.get_mut(app).grid_delegate = value;
669 }
670
671 fn place(app: &mut App, child: AnyRenderBox, geometry: SliverGridGeometry) {
673 let child_parent_data = child
674 .as_object()
675 .parent_data_of_mut::<SliverGridParentData>(app);
676 child_parent_data
677 .adaptor
678 .set_layout_offset(Some(geometry.scroll_offset));
679 child_parent_data.cross_axis_offset = Some(geometry.cross_axis_offset);
680 }
681}
682
683impl ContainerRenderObjectMixin for RenderSliverGrid {
684 type ChildType = AnyRenderBox;
685 type ParentDataType = SliverMultiBoxAdaptorParentData;
686
687 fn container_data(
688 self: RenderHandle<Self>,
689 app: &App,
690 ) -> &ContainerRenderObjectData<AnyRenderBox> {
691 &self.get(app).container
692 }
693
694 fn container_data_mut(
695 self: RenderHandle<Self>,
696 app: &mut App,
697 ) -> &mut ContainerRenderObjectData<AnyRenderBox> {
698 &mut self.get_mut(app).container
699 }
700
701 fn insert(
702 self: RenderHandle<Self>,
703 app: &mut App,
704 child: AnyRenderBox,
705 after: Option<AnyRenderBox>,
706 ) {
707 RenderSliverMultiBoxAdaptor::insert(self, app, child, after)
708 }
709
710 fn move_child(
711 self: RenderHandle<Self>,
712 app: &mut App,
713 child: AnyRenderBox,
714 after: Option<AnyRenderBox>,
715 ) {
716 RenderSliverMultiBoxAdaptor::move_child(self, app, child, after)
717 }
718
719 fn remove(self: RenderHandle<Self>, app: &mut App, child: AnyRenderBox) {
720 RenderSliverMultiBoxAdaptor::remove(self, app, child)
721 }
722
723 fn remove_all(self: RenderHandle<Self>, app: &mut App) {
724 RenderSliverMultiBoxAdaptor::remove_all(self, app)
725 }
726}
727
728impl RenderSliverHelpers for RenderSliverGrid {}
729
730impl RenderSliverWithKeepAliveMixin for RenderSliverGrid {}
731
732impl RenderSliverMultiBoxAdaptor for RenderSliverGrid {
733 crate::render_sliver_multi_box_adaptor_accessors!();
734}
735
736impl RenderObject for RenderSliverGrid {
737 crate::render_object_accessors!();
738
739 fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
740 if !child.parent_data_is::<SliverGridParentData>(app) {
741 child.set_parent_data(app, SliverGridParentData::new());
742 }
743 }
744
745 fn visit_children(
746 self: RenderHandle<Self>,
747 app: &App,
748 visitor: &mut dyn FnMut(AnyRenderObject),
749 ) {
750 RenderSliverMultiBoxAdaptor::visit_children(self, app, visitor)
751 }
752
753 fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
754 RenderSliverMultiBoxAdaptor::did_attach(self, app, owner)
755 }
756
757 fn did_detach(self: RenderHandle<Self>, app: &mut App) {
758 RenderSliverMultiBoxAdaptor::did_detach(self, app)
759 }
760
761 fn redepth_children(self: RenderHandle<Self>, app: &mut App) {
762 RenderSliverMultiBoxAdaptor::redepth_children(self, app)
763 }
764
765 fn apply_paint_transform(
766 self: RenderHandle<Self>,
767 app: &App,
768 child: AnyRenderObject,
769 transform: &mut Matrix4,
770 ) {
771 RenderSliverMultiBoxAdaptor::apply_paint_transform(self, app, child, transform)
772 }
773
774 fn paints_child(self: RenderHandle<Self>, app: &App, child: AnyRenderObject) -> bool {
775 RenderSliverMultiBoxAdaptor::paints_child(self, app, child)
776 }
777
778 fn debug_fill_properties(
779 self: RenderHandle<Self>,
780 app: &App,
781 properties: &mut DiagnosticPropertiesBuilder,
782 ) {
783 RenderSliverMultiBoxAdaptor::debug_fill_properties(self, app, properties)
784 }
785
786 fn debug_describe_children(
787 self: RenderHandle<Self>,
788 app: &App,
789 ) -> Vec<Rc<dyn DiagnosticsNode>> {
790 RenderSliverMultiBoxAdaptor::debug_describe_children(self, app)
791 }
792
793 fn paint(
794 self: RenderHandle<Self>,
795 app: &mut App,
796 context: &mut PaintingContext,
797 offset: Offset,
798 ) {
799 RenderSliverMultiBoxAdaptor::paint(self, app, context, offset)
800 }
801
802 fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
803 let constraints = self.constraints(app);
804 let child_manager = self.child_manager(app);
805 child_manager.did_start_layout(app);
806 child_manager.set_did_underflow(app, false);
807
808 let scroll_offset = constraints.scroll_offset + constraints.cache_origin;
809 debug_assert!(scroll_offset >= 0.0);
810 let remaining_extent = constraints.remaining_cache_extent;
811 debug_assert!(remaining_extent >= 0.0);
812 let target_end_scroll_offset = scroll_offset + remaining_extent;
813
814 let layout = self.grid_delegate(app).get_layout(constraints);
815
816 let first_index = layout.get_min_child_index_for_scroll_offset(scroll_offset);
817 let target_last_index = target_end_scroll_offset
818 .is_finite()
819 .then(|| layout.get_max_child_index_for_scroll_offset(target_end_scroll_offset));
820
821 if self.first_child(app).is_some() {
822 let leading_garbage = self.calculate_leading_garbage(app, first_index);
823 let trailing_garbage = match target_last_index {
824 Some(last_index) => self.calculate_trailing_garbage(app, last_index),
825 None => 0,
826 };
827 self.collect_garbage(app, leading_garbage, trailing_garbage);
828 } else {
829 self.collect_garbage(app, 0, 0);
830 }
831
832 let first_child_grid_geometry = layout.get_geometry_for_child_index(first_index);
833
834 if self.first_child(app).is_none()
835 && !self.add_initial_child(app, first_index, first_child_grid_geometry.scroll_offset)
836 {
837 let max = layout.compute_max_scroll_offset(child_manager.child_count(app));
839 self.set_geometry(
840 app,
841 SliverGeometry::builder()
842 .scroll_extent(max)
843 .max_paint_extent(max)
844 .build(),
845 );
846 child_manager.did_finish_layout(app);
847 return;
848 }
849
850 let leading_scroll_offset = first_child_grid_geometry.scroll_offset;
851 let mut trailing_scroll_offset = first_child_grid_geometry.trailing_scroll_offset();
852 let mut trailing_child_with_layout: Option<AnyRenderBox> = None;
853 let mut reached_end = false;
854
855 let first_child = self.first_child(app).expect("added above");
856 let mut index = self.index_of(app, first_child) - 1;
857 while index >= first_index {
858 let grid_geometry = layout.get_geometry_for_child_index(index);
859 let child = self
860 .insert_and_layout_leading_child(
861 app,
862 grid_geometry.get_box_constraints(constraints),
863 false,
864 )
865 .expect("the children before the first one are there");
866 Self::place(app, child, grid_geometry);
867 debug_assert_eq!(
868 child
869 .as_object()
870 .parent_data_of::<SliverMultiBoxAdaptorParentData>(app)
871 .index,
872 Some(index)
873 );
874 trailing_child_with_layout.get_or_insert(child);
875 trailing_scroll_offset =
876 trailing_scroll_offset.max(grid_geometry.trailing_scroll_offset());
877 index -= 1;
878 }
879
880 if trailing_child_with_layout.is_none() {
881 let first_child = self.first_child(app).expect("the child list is not empty");
882 first_child.layout(
883 app,
884 first_child_grid_geometry.get_box_constraints(constraints),
885 false,
886 );
887 Self::place(app, first_child, first_child_grid_geometry);
888 trailing_child_with_layout = Some(first_child);
889 }
890
891 let mut index = self.index_of(app, trailing_child_with_layout.expect("set above")) + 1;
892 while target_last_index.is_none_or(|last_index| index <= last_index) {
893 let grid_geometry = layout.get_geometry_for_child_index(index);
894 let child_constraints = grid_geometry.get_box_constraints(constraints);
895 let after = trailing_child_with_layout.expect("set above");
896 let mut child = self.child_after(app, after);
897 if child.is_none_or(|current| self.index_of(app, current) != index) {
898 child = self.insert_and_layout_child(app, child_constraints, Some(after), false);
899 if child.is_none() {
900 reached_end = true;
901 break;
903 }
904 } else {
905 child
906 .expect("checked")
907 .layout(app, child_constraints, false);
908 }
909 let child = child.expect("set above");
910 trailing_child_with_layout = Some(child);
911 Self::place(app, child, grid_geometry);
912 debug_assert_eq!(
913 child
914 .as_object()
915 .parent_data_of::<SliverMultiBoxAdaptorParentData>(app)
916 .index,
917 Some(index)
918 );
919 trailing_scroll_offset =
920 trailing_scroll_offset.max(grid_geometry.trailing_scroll_offset());
921 index += 1;
922 }
923
924 let last_index = self.index_of(app, self.last_child(app).expect("not empty"));
925
926 debug_assert!(self.debug_assert_child_list_is_non_empty_and_contiguous(app));
927 debug_assert_eq!(
928 self.index_of(app, self.first_child(app).expect("not empty")),
929 first_index
930 );
931 debug_assert!(target_last_index.is_none_or(|target| last_index <= target));
932
933 let estimated_total_extent = if reached_end {
934 trailing_scroll_offset
935 } else {
936 child_manager.estimate_max_scroll_offset(
937 app,
938 constraints,
939 Some(first_index),
940 Some(last_index),
941 Some(leading_scroll_offset),
942 Some(trailing_scroll_offset),
943 )
944 };
945 let paint_extent = calculate_paint_offset(
946 constraints,
947 constraints.scroll_offset.min(leading_scroll_offset),
948 trailing_scroll_offset,
949 );
950 let cache_extent =
951 calculate_cache_offset(constraints, leading_scroll_offset, trailing_scroll_offset);
952
953 self.set_geometry(
954 app,
955 SliverGeometry::builder()
956 .scroll_extent(estimated_total_extent)
957 .paint_extent(paint_extent)
958 .max_paint_extent(estimated_total_extent)
959 .cache_extent(cache_extent)
960 .has_visual_overflow(
961 estimated_total_extent > paint_extent
962 || constraints.scroll_offset > 0.0
963 || constraints.overlap != 0.0,
964 )
965 .build(),
966 );
967
968 if estimated_total_extent == trailing_scroll_offset {
971 child_manager.set_did_underflow(app, true);
972 }
973 child_manager.did_finish_layout(app);
974 }
975}
976
977impl RenderSliver for RenderSliverGrid {
978 crate::render_sliver_accessors!();
979
980 fn hit_test_children(
981 self: RenderHandle<Self>,
982 app: &mut App,
983 result: &mut SliverHitTestResult<'_>,
984 main_axis_position: f64,
985 cross_axis_position: f64,
986 ) -> bool {
987 RenderSliverMultiBoxAdaptor::hit_test_children(
988 self,
989 app,
990 result,
991 main_axis_position,
992 cross_axis_position,
993 )
994 }
995
996 fn child_main_axis_position(
997 self: RenderHandle<Self>,
998 app: &App,
999 child: AnyRenderObject,
1000 ) -> f64 {
1001 RenderSliverMultiBoxAdaptor::child_main_axis_position(self, app, child)
1002 }
1003
1004 fn child_cross_axis_position(
1005 self: RenderHandle<Self>,
1006 app: &App,
1007 child: AnyRenderObject,
1008 ) -> f64 {
1009 child
1010 .parent_data_of::<SliverGridParentData>(app)
1011 .cross_axis_offset
1012 .expect("laid out")
1013 }
1014
1015 fn child_scroll_offset(
1016 self: RenderHandle<Self>,
1017 app: &App,
1018 child: AnyRenderObject,
1019 ) -> Option<f64> {
1020 RenderSliverMultiBoxAdaptor::child_scroll_offset(self, app, child)
1021 }
1022}
1023
1024#[cfg(test)]
1025mod tests {
1026 use waft_embedder::Size;
1027 use waft_foundation::AppCell;
1028 use waft_gestures::HitTestResult;
1029 use waft_painting::AxisDirection;
1030
1031 use super::*;
1032 use crate::sliver::GrowthDirection;
1033 use crate::sliver_multi_box_adaptor::test_support::TestChildManager;
1034 use crate::sliver_multi_box_adaptor::viewport_test_support::ScrollHarness;
1035 use crate::viewport_offset::ScrollDirection;
1036
1037 const VIEWPORT: Size = Size::new(500.0, 200.0);
1038
1039 fn sliver_grid(
1040 app: &mut App,
1041 count: usize,
1042 delegate: Rc<dyn SliverGridDelegate>,
1043 ) -> (
1044 RenderHandle<RenderSliverGrid>,
1045 Rc<TestChildManager<RenderSliverGrid>>,
1046 ScrollHarness,
1047 ) {
1048 let manager = TestChildManager::new(vec![1000.0; count]);
1049 let grid = RenderSliverGrid::new(app, manager.clone(), delegate);
1050 manager.attach(grid);
1051 let harness = ScrollHarness::new(app, grid.as_sliver(), VIEWPORT);
1052 (grid, manager, harness)
1053 }
1054
1055 fn constraints(cross_axis_extent: f64) -> SliverConstraints {
1057 SliverConstraints::new(
1058 AxisDirection::Down,
1059 GrowthDirection::Forward,
1060 ScrollDirection::Idle,
1061 0.0,
1062 0.0,
1063 0.0,
1064 600.0,
1065 cross_axis_extent,
1066 AxisDirection::Right,
1067 600.0,
1068 1100.0,
1069 0.0,
1070 )
1071 }
1072
1073 fn placed(app: &App, grid: RenderHandle<RenderSliverGrid>) -> Vec<(i32, f64, f64, Size)> {
1075 let mut placed = Vec::new();
1076 let mut child = grid.first_child(app);
1077 while let Some(current) = child {
1078 let data = current
1079 .as_object()
1080 .parent_data_of::<SliverGridParentData>(app);
1081 placed.push((
1082 data.adaptor.index.expect("indexed"),
1083 data.adaptor.layout_offset().expect("laid out"),
1084 data.cross_axis_offset.expect("laid out"),
1085 current.size(app),
1086 ));
1087 child = grid.child_after(app, current);
1088 }
1089 placed
1090 }
1091
1092 #[test]
1095 fn a_max_extent_grid_fits_as_many_columns_as_it_can() {
1096 let delegate = SliverGridDelegateWithMaxCrossAxisExtent::new(150.0);
1097 let layout = delegate.get_layout(constraints(500.0));
1098 let geometry = layout.get_geometry_for_child_index(5);
1099 assert_eq!(geometry.cross_axis_extent, 125.0, "4 columns of 125 in 500");
1100 assert_eq!(geometry.cross_axis_offset, 125.0);
1101 assert_eq!(geometry.scroll_offset, 125.0, "the second row");
1102 assert_eq!(layout.compute_max_scroll_offset(9), 375.0, "3 rows");
1103 assert_eq!(layout.compute_max_scroll_offset(0), 0.0);
1104 }
1105
1106 #[test]
1108 fn a_reversed_cross_axis_places_the_first_column_last() {
1109 let mut leftward = constraints(400.0);
1110 leftward.cross_axis_direction = AxisDirection::Left;
1111 let layout = SliverGridDelegateWithFixedCrossAxisCount::new(4)
1112 .cross_axis_spacing(20.0)
1113 .get_layout(leftward);
1114 assert_eq!(
1116 layout.get_geometry_for_child_index(0).cross_axis_offset,
1117 315.0
1118 );
1119 assert_eq!(
1120 layout.get_geometry_for_child_index(3).cross_axis_offset,
1121 0.0
1122 );
1123 }
1124
1125 #[test]
1126 fn a_grid_lays_out_only_the_rows_it_shows_with_their_spacing() {
1127 let cell = AppCell::new();
1128 let mut app = cell.borrow_mut();
1129 let delegate = SliverGridDelegateWithFixedCrossAxisCount::new(2)
1130 .main_axis_spacing(10.0)
1131 .cross_axis_spacing(20.0)
1132 .child_aspect_ratio(2.0);
1133 let (grid, manager, _harness) = sliver_grid(&mut app, 100, Rc::new(delegate));
1134 let placed = placed(&app, grid);
1137 assert_eq!(
1138 placed[..3],
1139 [
1140 (0, 0.0, 0.0, Size::new(240.0, 120.0)),
1141 (1, 0.0, 260.0, Size::new(240.0, 120.0)),
1142 (2, 130.0, 0.0, Size::new(240.0, 120.0)),
1143 ]
1144 );
1145 assert_eq!(placed.len(), 8, "four rows of two");
1146 assert!(manager.created.borrow().iter().all(|index| *index < 8));
1147 }
1148
1149 #[test]
1150 fn scrolling_a_grid_replaces_its_rows() {
1151 let cell = AppCell::new();
1152 let mut app = cell.borrow_mut();
1153 let delegate = SliverGridDelegateWithFixedCrossAxisCount::new(4).main_axis_extent(100.0);
1154 let (grid, _, harness) = sliver_grid(&mut app, 100, Rc::new(delegate));
1155 harness.scroll_to(&mut app, 1000.0);
1156 let placed = placed(&app, grid);
1157 assert_eq!((placed[0].0, placed[0].1), (28, 700.0));
1159 assert!(placed.iter().all(|(index, ..)| *index >= 28));
1160 assert!(grid.geometry(&app).has_visual_overflow);
1161 }
1162
1163 #[test]
1164 fn a_short_grid_reports_its_exact_extent() {
1165 let cell = AppCell::new();
1166 let mut app = cell.borrow_mut();
1167 let delegate = SliverGridDelegateWithFixedCrossAxisCount::new(4).main_axis_extent(50.0);
1168 let (grid, manager, _harness) = sliver_grid(&mut app, 6, Rc::new(delegate));
1169 let geometry = grid.geometry(&app);
1170 assert_eq!(geometry.scroll_extent, 100.0, "two rows of 50");
1171 assert_eq!(geometry.paint_extent, 100.0);
1172 assert!(!geometry.has_visual_overflow);
1173 assert!(manager.did_underflow.get());
1174 }
1175
1176 #[test]
1179 fn a_grid_hit_tests_the_tile_under_the_point() {
1180 let cell = AppCell::new();
1181 let mut app = cell.borrow_mut();
1182 let delegate = SliverGridDelegateWithFixedCrossAxisCount::new(5).main_axis_extent(100.0);
1183 let (grid, _, _harness) = sliver_grid(&mut app, 20, Rc::new(delegate));
1184 let tile = placed(&app, grid)
1185 .iter()
1186 .position(|(index, ..)| *index == 8)
1187 .expect("tile 8 is laid out");
1188 let mut child = grid.first_child(&app).expect("tiles");
1189 for _ in 0..tile {
1190 child = grid.child_after(&app, child).expect("tile");
1191 }
1192 assert_eq!(
1193 RenderSliver::child_cross_axis_position(grid, &app, child.as_object()),
1194 300.0
1195 );
1196
1197 let mut result = HitTestResult::new();
1198 let hit = grid.hit_test(
1199 &mut app,
1200 &mut SliverHitTestResult::wrap(&mut result),
1201 150.0,
1202 350.0,
1203 );
1204 assert!(hit);
1205 assert_eq!(result.path().len(), 2, "tile 8 and the grid");
1206 }
1207
1208 #[test]
1209 fn a_new_delegate_relays_out_only_when_it_changes_the_tiles() {
1210 let cell = AppCell::new();
1211 let mut app = cell.borrow_mut();
1212 let delegate = SliverGridDelegateWithFixedCrossAxisCount::new(2);
1213 let (grid, _, harness) = sliver_grid(&mut app, 10, Rc::new(delegate.clone()));
1214 grid.set_grid_delegate(&mut app, Rc::new(delegate.clone()));
1215 assert!(!grid.as_object().debug_needs_layout(&app), "the same tiles");
1216 grid.set_grid_delegate(&mut app, Rc::new(delegate.main_axis_spacing(4.0)));
1217 assert!(grid.as_object().debug_needs_layout(&app));
1218 harness.owner.flush_layout(&mut app);
1219 grid.set_grid_delegate(
1220 &mut app,
1221 Rc::new(SliverGridDelegateWithMaxCrossAxisExtent::new(250.0)),
1222 );
1223 assert!(
1224 grid.as_object().debug_needs_layout(&app),
1225 "another kind of delegate"
1226 );
1227 }
1228}