Skip to main content

waft_rendering/
sliver.rs

1//! Flutter counterpart: `rendering/sliver.dart`.
2
3use std::any::{Any, TypeId};
4use std::fmt::{self, Debug, Display};
5use std::hash::Hasher;
6use std::ops::{Deref, DerefMut};
7
8use waft_embedder::{Matrix4, Offset, Rect, Size, clamp_double};
9use waft_foundation::{
10    App, DiagnosticPropertiesBuilder, Diagnosticable, DiagnosticsProperty, DoubleProperty,
11    FlagProperty, Handle, HandleId, PRECISION_ERROR_TOLERANCE, describe_enum,
12};
13use waft_gestures::{HitTestEntry, HitTestResult, HitTestTarget, PointerEvent};
14use waft_painting::{
15    Axis, AxisDirection, axis_direction_is_reversed, axis_direction_to_axis, flip_axis_direction,
16};
17
18use crate::box_::{AnyRenderBox, BoxConstraints, BoxHitTestResult};
19use crate::object::{
20    AnyRenderObject, Constraints, ContainerParentData, ContainerParentDataMixin, ParentData,
21    RenderHandle, RenderObject, RenderObjectVTable, RenderObjectWithChildData,
22    RenderObjectWithChildMixin, create, resolve, translate,
23};
24use crate::painting_context::PaintingContext;
25use crate::pipeline_owner::PipelineOwner;
26use crate::viewport_offset::{ScrollDirection, flip_scroll_direction};
27
28/// Signature for a callback that reports the main-axis extent of the item at `index`.
29///
30/// Used by `ListView.itemExtentBuilder` and `SliverVariedExtentList.itemExtentBuilder`.
31///
32/// Dart compares two builders with `==`; an [`Rc`](std::rc::Rc) compares by pointer.
33pub type ItemExtentBuilder = std::rc::Rc<dyn Fn(i32, SliverLayoutDimensions) -> Option<f64>>;
34
35/// Relates the dimensions of the [`RenderSliver`] during layout.
36#[derive(Clone, Copy, Debug, PartialEq)]
37pub struct SliverLayoutDimensions {
38    /// Scroll offset in this sliver's coordinate system of the earliest visible part of this
39    /// sliver.
40    pub scroll_offset: f64,
41
42    /// Scroll distance consumed by all slivers that came before this one.
43    pub preceding_scroll_extent: f64,
44
45    /// The number of pixels the viewport can display in the main axis.
46    ///
47    /// For a vertical list, this is the height of the viewport.
48    pub viewport_main_axis_extent: f64,
49
50    /// The number of pixels in the cross-axis.
51    ///
52    /// For a vertical list, this is the width of the sliver.
53    pub cross_axis_extent: f64,
54}
55
56impl SliverLayoutDimensions {
57    /// Constructs the layout dimensions with the specified parameters.
58    pub const fn new(
59        scroll_offset: f64,
60        preceding_scroll_extent: f64,
61        viewport_main_axis_extent: f64,
62        cross_axis_extent: f64,
63    ) -> SliverLayoutDimensions {
64        SliverLayoutDimensions {
65            scroll_offset,
66            preceding_scroll_extent,
67            viewport_main_axis_extent,
68            cross_axis_extent,
69        }
70    }
71}
72
73impl Display for SliverLayoutDimensions {
74    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75        write!(
76            f,
77            "scrollOffset: {} precedingScrollExtent: {} viewportMainAxisExtent: {} \
78             crossAxisExtent: {}",
79            self.scroll_offset,
80            self.preceding_scroll_extent,
81            self.viewport_main_axis_extent,
82            self.cross_axis_extent
83        )
84    }
85}
86
87/// The direction in which a sliver's contents are ordered, relative to the
88/// scroll offset axis.
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
90pub enum GrowthDirection {
91    /// Contents are ordered in the same direction as the [`AxisDirection`].
92    Forward,
93
94    /// Contents are ordered in the opposite direction of the [`AxisDirection`].
95    Reverse,
96}
97
98/// Flips the [`AxisDirection`] if the [`GrowthDirection`] is
99/// [`GrowthDirection::Reverse`].
100pub fn apply_growth_direction_to_axis_direction(
101    axis_direction: AxisDirection,
102    growth_direction: GrowthDirection,
103) -> AxisDirection {
104    match growth_direction {
105        GrowthDirection::Forward => axis_direction,
106        GrowthDirection::Reverse => flip_axis_direction(axis_direction),
107    }
108}
109
110/// Flips the [`ScrollDirection`] if the [`GrowthDirection`] is
111/// [`GrowthDirection::Reverse`].
112pub fn apply_growth_direction_to_scroll_direction(
113    scroll_direction: ScrollDirection,
114    growth_direction: GrowthDirection,
115) -> ScrollDirection {
116    match growth_direction {
117        GrowthDirection::Forward => scroll_direction,
118        GrowthDirection::Reverse => flip_scroll_direction(scroll_direction),
119    }
120}
121
122/// Immutable layout constraints for [`RenderSliver`] layout.
123#[derive(Clone, Copy, Debug)]
124pub struct SliverConstraints {
125    /// The direction in which [`scroll_offset`](Self::scroll_offset) and
126    /// [`remaining_paint_extent`](Self::remaining_paint_extent) increase.
127    pub axis_direction: AxisDirection,
128    /// The direction in which the contents of slivers are ordered.
129    pub growth_direction: GrowthDirection,
130    /// The direction in which the user is attempting to scroll.
131    pub user_scroll_direction: ScrollDirection,
132    /// Scroll offset in this sliver's coordinate system of the earliest visible
133    /// part of this sliver.
134    pub scroll_offset: f64,
135    /// Scroll distance consumed by all slivers that came before this one.
136    pub preceding_scroll_extent: f64,
137    /// Pixels from the painted [`scroll_offset`](Self::scroll_offset) up to the
138    /// first pixel not yet painted by an earlier sliver.
139    pub overlap: f64,
140    /// Pixels of content the sliver should consider providing.
141    pub remaining_paint_extent: f64,
142    /// Pixels in the cross-axis.
143    pub cross_axis_extent: f64,
144    /// Direction in which children should be placed in the cross axis.
145    pub cross_axis_direction: AxisDirection,
146    /// Pixels the viewport can display in the main axis.
147    pub viewport_main_axis_extent: f64,
148    /// How much content the sliver should provide starting from
149    /// [`cache_origin`](Self::cache_origin).
150    pub remaining_cache_extent: f64,
151    /// Where the cache area starts relative to the
152    /// [`scroll_offset`](Self::scroll_offset). Always negative or zero.
153    pub cache_origin: f64,
154}
155
156impl fmt::Display for SliverConstraints {
157    /// Dart's `SliverConstraints.toString`, its enums as Dart prints them (`AxisDirection.down`).
158    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159        let mut properties = vec![
160            format!("AxisDirection.{}", describe_enum(&self.axis_direction)),
161            format!("GrowthDirection.{}", describe_enum(&self.growth_direction)),
162            format!(
163                "ScrollDirection.{}",
164                describe_enum(&self.user_scroll_direction)
165            ),
166            format!("scrollOffset: {:.1}", self.scroll_offset),
167            format!("precedingScrollExtent: {:.1}", self.preceding_scroll_extent),
168            format!("remainingPaintExtent: {:.1}", self.remaining_paint_extent),
169        ];
170        if self.overlap != 0.0 {
171            properties.push(format!("overlap: {:.1}", self.overlap));
172        }
173        properties.extend([
174            format!("crossAxisExtent: {:.1}", self.cross_axis_extent),
175            format!(
176                "crossAxisDirection: AxisDirection.{}",
177                describe_enum(&self.cross_axis_direction)
178            ),
179            format!(
180                "viewportMainAxisExtent: {:.1}",
181                self.viewport_main_axis_extent
182            ),
183            format!("remainingCacheExtent: {:.1}", self.remaining_cache_extent),
184            format!("cacheOrigin: {:.1}", self.cache_origin),
185        ]);
186        write!(f, "SliverConstraints({})", properties.join(", "))
187    }
188}
189
190impl SliverConstraints {
191    /// Creates sliver constraints with the given information.
192    #[allow(clippy::too_many_arguments)]
193    pub const fn new(
194        axis_direction: AxisDirection,
195        growth_direction: GrowthDirection,
196        user_scroll_direction: ScrollDirection,
197        scroll_offset: f64,
198        preceding_scroll_extent: f64,
199        overlap: f64,
200        remaining_paint_extent: f64,
201        cross_axis_extent: f64,
202        cross_axis_direction: AxisDirection,
203        viewport_main_axis_extent: f64,
204        remaining_cache_extent: f64,
205        cache_origin: f64,
206    ) -> SliverConstraints {
207        SliverConstraints {
208            axis_direction,
209            growth_direction,
210            user_scroll_direction,
211            scroll_offset,
212            preceding_scroll_extent,
213            overlap,
214            remaining_paint_extent,
215            cross_axis_extent,
216            cross_axis_direction,
217            viewport_main_axis_extent,
218            remaining_cache_extent,
219            cache_origin,
220        }
221    }
222
223    /// Creates a copy of this object. Chain field replacements.
224    pub const fn copy_with(self) -> SliverConstraints {
225        self
226    }
227
228    /// Sets [`axis_direction`](Self::axis_direction).
229    pub const fn axis_direction(mut self, value: AxisDirection) -> SliverConstraints {
230        self.axis_direction = value;
231        self
232    }
233
234    /// Sets [`growth_direction`](Self::growth_direction).
235    pub const fn growth_direction(mut self, value: GrowthDirection) -> SliverConstraints {
236        self.growth_direction = value;
237        self
238    }
239
240    /// Sets [`user_scroll_direction`](Self::user_scroll_direction).
241    pub const fn user_scroll_direction(mut self, value: ScrollDirection) -> SliverConstraints {
242        self.user_scroll_direction = value;
243        self
244    }
245
246    /// Sets [`scroll_offset`](Self::scroll_offset).
247    pub const fn scroll_offset(mut self, value: f64) -> SliverConstraints {
248        self.scroll_offset = value;
249        self
250    }
251
252    /// Sets [`preceding_scroll_extent`](Self::preceding_scroll_extent).
253    pub const fn preceding_scroll_extent(mut self, value: f64) -> SliverConstraints {
254        self.preceding_scroll_extent = value;
255        self
256    }
257
258    /// Sets [`overlap`](Self::overlap).
259    pub const fn overlap(mut self, value: f64) -> SliverConstraints {
260        self.overlap = value;
261        self
262    }
263
264    /// Sets [`remaining_paint_extent`](Self::remaining_paint_extent).
265    pub const fn remaining_paint_extent(mut self, value: f64) -> SliverConstraints {
266        self.remaining_paint_extent = value;
267        self
268    }
269
270    /// Sets [`cross_axis_extent`](Self::cross_axis_extent).
271    pub const fn cross_axis_extent(mut self, value: f64) -> SliverConstraints {
272        self.cross_axis_extent = value;
273        self
274    }
275
276    /// Sets [`cross_axis_direction`](Self::cross_axis_direction).
277    pub const fn cross_axis_direction(mut self, value: AxisDirection) -> SliverConstraints {
278        self.cross_axis_direction = value;
279        self
280    }
281
282    /// Sets [`viewport_main_axis_extent`](Self::viewport_main_axis_extent).
283    pub const fn viewport_main_axis_extent(mut self, value: f64) -> SliverConstraints {
284        self.viewport_main_axis_extent = value;
285        self
286    }
287
288    /// Sets [`remaining_cache_extent`](Self::remaining_cache_extent).
289    pub const fn remaining_cache_extent(mut self, value: f64) -> SliverConstraints {
290        self.remaining_cache_extent = value;
291        self
292    }
293
294    /// Sets [`cache_origin`](Self::cache_origin).
295    pub const fn cache_origin(mut self, value: f64) -> SliverConstraints {
296        self.cache_origin = value;
297        self
298    }
299
300    /// The axis along which the scroll offset is measured.
301    pub fn axis(self) -> Axis {
302        axis_direction_to_axis(self.axis_direction)
303    }
304
305    /// [`growth_direction`](Self::growth_direction) as if the axis were down or
306    /// right.
307    pub fn normalized_growth_direction(self) -> GrowthDirection {
308        if axis_direction_is_reversed(self.axis_direction) {
309            match self.growth_direction {
310                GrowthDirection::Forward => GrowthDirection::Reverse,
311                GrowthDirection::Reverse => GrowthDirection::Forward,
312            }
313        } else {
314            self.growth_direction
315        }
316    }
317
318    /// [`BoxConstraints`] that reflect these sliver constraints.
319    ///
320    /// Dart named defaults: `min_extent` 0, `max_extent` infinity, `cross_axis_extent`
321    /// this sliver's cross extent.
322    pub fn as_box_constraints(
323        self,
324        min_extent: f64,
325        max_extent: f64,
326        cross_axis_extent: Option<f64>,
327    ) -> BoxConstraints {
328        let cross = cross_axis_extent.unwrap_or(self.cross_axis_extent);
329        match self.axis() {
330            Axis::Horizontal => BoxConstraints {
331                min_width: min_extent,
332                max_width: max_extent,
333                min_height: cross,
334                max_height: cross,
335            },
336            Axis::Vertical => BoxConstraints {
337                min_width: cross,
338                max_width: cross,
339                min_height: min_extent,
340                max_height: max_extent,
341            },
342        }
343    }
344}
345
346impl Constraints for SliverConstraints {
347    fn is_tight(&self) -> bool {
348        false
349    }
350
351    fn is_normalized(&self) -> bool {
352        self.scroll_offset >= 0.0
353            && self.cross_axis_extent >= 0.0
354            && axis_direction_to_axis(self.axis_direction)
355                != axis_direction_to_axis(self.cross_axis_direction)
356            && self.viewport_main_axis_extent >= 0.0
357            && self.remaining_paint_extent >= 0.0
358    }
359}
360
361impl PartialEq for SliverConstraints {
362    fn eq(&self, other: &SliverConstraints) -> bool {
363        debug_assert!(self.debug_assert_is_valid(false));
364        debug_assert!(other.debug_assert_is_valid(false));
365        self.axis_direction == other.axis_direction
366            && self.growth_direction == other.growth_direction
367            && self.user_scroll_direction == other.user_scroll_direction
368            && self.scroll_offset == other.scroll_offset
369            && self.preceding_scroll_extent == other.preceding_scroll_extent
370            && self.overlap == other.overlap
371            && self.remaining_paint_extent == other.remaining_paint_extent
372            && self.cross_axis_extent == other.cross_axis_extent
373            && self.cross_axis_direction == other.cross_axis_direction
374            && self.viewport_main_axis_extent == other.viewport_main_axis_extent
375            && self.remaining_cache_extent == other.remaining_cache_extent
376            && self.cache_origin == other.cache_origin
377    }
378}
379
380/// The amount of space a sliver occupies.
381#[derive(Clone, Copy, Debug)]
382pub struct SliverGeometry {
383    /// Estimated total scrollable extent this sliver has content for.
384    pub scroll_extent: f64,
385    /// Visual location of the first visible part relative to the layout
386    /// position.
387    pub paint_origin: f64,
388    /// Currently visible visual space taken by this sliver.
389    pub paint_extent: f64,
390    /// Distance from the first visible part of this sliver to the first visible
391    /// part of the next.
392    pub layout_extent: f64,
393    /// Estimated total paint extent if remaining paint extent were infinite.
394    pub max_paint_extent: f64,
395    /// Maximum extent by which a pinned sliver can reduce the scrollable area.
396    pub max_scroll_obstruction_extent: f64,
397    /// Distance from where this sliver started painting to the bottom of where
398    /// it should accept hits.
399    pub hit_test_extent: f64,
400    /// Whether this sliver should be painted.
401    pub visible: bool,
402    /// Whether this sliver has visual overflow.
403    pub has_visual_overflow: bool,
404    /// Non-zero asks the parent to correct the scroll offset and relayout.
405    pub scroll_offset_correction: Option<f64>,
406    /// Pixels consumed in the remaining cache extent.
407    pub cache_extent: f64,
408    /// Cross-axis extent, if the sliver reports one.
409    pub cross_axis_extent: Option<f64>,
410}
411
412impl SliverGeometry {
413    /// A sliver that occupies no space at all.
414    pub const ZERO: SliverGeometry = SliverGeometry {
415        scroll_extent: 0.0,
416        paint_origin: 0.0,
417        paint_extent: 0.0,
418        layout_extent: 0.0,
419        max_paint_extent: 0.0,
420        max_scroll_obstruction_extent: 0.0,
421        hit_test_extent: 0.0,
422        visible: false,
423        has_visual_overflow: false,
424        scroll_offset_correction: None,
425        cache_extent: 0.0,
426        cross_axis_extent: None,
427    };
428
429    /// Starts geometry with Flutter's constructor defaults. Extents left out are filled in by
430    /// [`SliverGeometryBuilder::build`], as Flutter's constructor fills them.
431    pub const fn builder() -> SliverGeometryBuilder {
432        SliverGeometryBuilder {
433            scroll_extent: 0.0,
434            paint_origin: 0.0,
435            paint_extent: 0.0,
436            layout_extent: None,
437            max_paint_extent: 0.0,
438            max_scroll_obstruction_extent: 0.0,
439            hit_test_extent: None,
440            visible: None,
441            has_visual_overflow: false,
442            scroll_offset_correction: None,
443            cache_extent: None,
444            cross_axis_extent: None,
445        }
446    }
447
448    /// Dart `copyWith`: a builder holding this geometry's values, for fields to be replaced.
449    pub const fn copy_with(self) -> SliverGeometryBuilder {
450        SliverGeometryBuilder {
451            scroll_extent: self.scroll_extent,
452            paint_origin: self.paint_origin,
453            paint_extent: self.paint_extent,
454            layout_extent: Some(self.layout_extent),
455            max_paint_extent: self.max_paint_extent,
456            max_scroll_obstruction_extent: self.max_scroll_obstruction_extent,
457            hit_test_extent: Some(self.hit_test_extent),
458            visible: Some(self.visible),
459            has_visual_overflow: self.has_visual_overflow,
460            scroll_offset_correction: self.scroll_offset_correction,
461            cache_extent: Some(self.cache_extent),
462            cross_axis_extent: self.cross_axis_extent,
463        }
464    }
465
466    /// Dart's `geometry == SliverGeometry.zero`: whether this geometry occupies no space at
467    /// all.
468    pub fn is_zero(&self) -> bool {
469        self.scroll_extent == SliverGeometry::ZERO.scroll_extent
470            && self.paint_origin == SliverGeometry::ZERO.paint_origin
471            && self.paint_extent == SliverGeometry::ZERO.paint_extent
472            && self.layout_extent == SliverGeometry::ZERO.layout_extent
473            && self.max_paint_extent == SliverGeometry::ZERO.max_paint_extent
474            && self.max_scroll_obstruction_extent
475                == SliverGeometry::ZERO.max_scroll_obstruction_extent
476            && self.hit_test_extent == SliverGeometry::ZERO.hit_test_extent
477            && self.visible == SliverGeometry::ZERO.visible
478            && self.has_visual_overflow == SliverGeometry::ZERO.has_visual_overflow
479            && self.scroll_offset_correction == SliverGeometry::ZERO.scroll_offset_correction
480            && self.cache_extent == SliverGeometry::ZERO.cache_extent
481            && self.cross_axis_extent == SliverGeometry::ZERO.cross_axis_extent
482    }
483
484    /// Asserts that this geometry is internally consistent.
485    ///
486    /// Does nothing if asserts are disabled. Always returns true.
487    pub fn debug_assert_is_valid(&self) -> bool {
488        debug_assert!(self.scroll_extent >= 0.0, "The scroll_extent is negative.");
489        debug_assert!(self.paint_extent >= 0.0, "The paint_extent is negative.");
490        debug_assert!(self.layout_extent >= 0.0, "The layout_extent is negative.");
491        debug_assert!(self.cache_extent >= 0.0, "The cache_extent is negative.");
492        debug_assert!(
493            self.layout_extent <= self.paint_extent,
494            "The layout_extent ({}) exceeds the paint_extent ({}).",
495            self.layout_extent,
496            self.paint_extent
497        );
498        // If the paint_extent is slightly more than the max_paint_extent, but the difference is
499        // still less than PRECISION_ERROR_TOLERANCE, we will not fail the assert below.
500        debug_assert!(
501            self.paint_extent - self.max_paint_extent <= PRECISION_ERROR_TOLERANCE,
502            "The max_paint_extent ({}) is less than the paint_extent ({}). By definition, a \
503             sliver can't paint more than the maximum that it can paint!",
504            self.max_paint_extent,
505            self.paint_extent
506        );
507        debug_assert!(
508            self.hit_test_extent >= 0.0,
509            "The hit_test_extent is negative."
510        );
511        debug_assert!(
512            self.scroll_offset_correction != Some(0.0),
513            "The scroll_offset_correction is zero."
514        );
515        true
516    }
517}
518
519/// `SliverGeometryBuilder` collects a [`SliverGeometry`]'s values, as Dart's constructor takes
520/// them, and fills in the ones left out when it builds.
521#[derive(Clone, Copy, Debug)]
522pub struct SliverGeometryBuilder {
523    scroll_extent: f64,
524    paint_origin: f64,
525    paint_extent: f64,
526    layout_extent: Option<f64>,
527    max_paint_extent: f64,
528    max_scroll_obstruction_extent: f64,
529    hit_test_extent: Option<f64>,
530    visible: Option<bool>,
531    has_visual_overflow: bool,
532    scroll_offset_correction: Option<f64>,
533    cache_extent: Option<f64>,
534    cross_axis_extent: Option<f64>,
535}
536
537impl SliverGeometryBuilder {
538    /// Sets [`SliverGeometry::scroll_extent`].
539    pub const fn scroll_extent(mut self, value: f64) -> SliverGeometryBuilder {
540        self.scroll_extent = value;
541        self
542    }
543
544    /// Sets [`SliverGeometry::paint_origin`].
545    pub const fn paint_origin(mut self, value: f64) -> SliverGeometryBuilder {
546        self.paint_origin = value;
547        self
548    }
549
550    /// Sets [`SliverGeometry::paint_extent`].
551    pub const fn paint_extent(mut self, value: f64) -> SliverGeometryBuilder {
552        self.paint_extent = value;
553        self
554    }
555
556    /// Sets [`SliverGeometry::layout_extent`].
557    pub const fn layout_extent(mut self, value: f64) -> SliverGeometryBuilder {
558        self.layout_extent = Some(value);
559        self
560    }
561
562    /// Sets [`SliverGeometry::max_paint_extent`].
563    pub const fn max_paint_extent(mut self, value: f64) -> SliverGeometryBuilder {
564        self.max_paint_extent = value;
565        self
566    }
567
568    /// Sets [`SliverGeometry::max_scroll_obstruction_extent`].
569    pub const fn max_scroll_obstruction_extent(mut self, value: f64) -> SliverGeometryBuilder {
570        self.max_scroll_obstruction_extent = value;
571        self
572    }
573
574    /// Sets [`SliverGeometry::hit_test_extent`].
575    pub const fn hit_test_extent(mut self, value: f64) -> SliverGeometryBuilder {
576        self.hit_test_extent = Some(value);
577        self
578    }
579
580    /// Sets [`SliverGeometry::visible`].
581    pub const fn visible(mut self, value: bool) -> SliverGeometryBuilder {
582        self.visible = Some(value);
583        self
584    }
585
586    /// Sets [`SliverGeometry::has_visual_overflow`].
587    pub const fn has_visual_overflow(mut self, value: bool) -> SliverGeometryBuilder {
588        self.has_visual_overflow = value;
589        self
590    }
591
592    /// Sets [`SliverGeometry::scroll_offset_correction`].
593    pub fn scroll_offset_correction(mut self, value: f64) -> SliverGeometryBuilder {
594        debug_assert!(value != 0.0);
595        self.scroll_offset_correction = Some(value);
596        self
597    }
598
599    /// Sets [`SliverGeometry::cache_extent`].
600    pub const fn cache_extent(mut self, value: f64) -> SliverGeometryBuilder {
601        self.cache_extent = Some(value);
602        self
603    }
604
605    /// Sets [`SliverGeometry::cross_axis_extent`].
606    pub const fn cross_axis_extent(mut self, value: f64) -> SliverGeometryBuilder {
607        self.cross_axis_extent = Some(value);
608        self
609    }
610
611    /// `build` makes the geometry, filling the extents left out as Dart's constructor does:
612    /// the layout and hit-test extents and `visible` from the paint extent, and the cache
613    /// extent from the layout extent.
614    pub fn build(self) -> SliverGeometry {
615        SliverGeometry {
616            scroll_extent: self.scroll_extent,
617            paint_origin: self.paint_origin,
618            paint_extent: self.paint_extent,
619            layout_extent: self.layout_extent.unwrap_or(self.paint_extent),
620            max_paint_extent: self.max_paint_extent,
621            max_scroll_obstruction_extent: self.max_scroll_obstruction_extent,
622            hit_test_extent: self.hit_test_extent.unwrap_or(self.paint_extent),
623            visible: self.visible.unwrap_or(self.paint_extent > 0.0),
624            has_visual_overflow: self.has_visual_overflow,
625            scroll_offset_correction: self.scroll_offset_correction,
626            cache_extent: self
627                .cache_extent
628                .or(self.layout_extent)
629                .unwrap_or(self.paint_extent),
630            cross_axis_extent: self.cross_axis_extent,
631        }
632    }
633}
634
635impl Default for SliverGeometry {
636    fn default() -> SliverGeometry {
637        SliverGeometry::builder().build()
638    }
639}
640
641impl Diagnosticable for SliverGeometry {
642    /// Dart's `toStringShort`: `objectRuntimeType(this, 'SliverGeometry')`, without an identity.
643    fn to_string_short(&self) -> String {
644        "SliverGeometry".to_owned()
645    }
646
647    /// Dart's `debugFillProperties`.
648    fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
649        properties.add(DoubleProperty::new("scrollExtent", self.scroll_extent));
650        if self.paint_extent > 0.0 {
651            let property = DoubleProperty::new("paintExtent", self.paint_extent);
652            properties.add(if self.visible {
653                property
654            } else {
655                property.unit(" but not painting")
656            });
657        } else if self.paint_extent == 0.0 {
658            if self.visible {
659                // Dart writes `unit: visible ? null : ' but visible'` inside `if (visible)`, so
660                // the unit is always null.
661                properties.add(DoubleProperty::new("paintExtent", self.paint_extent));
662            }
663            properties.add(FlagProperty::new("visible", self.visible).if_false("hidden"));
664        } else {
665            // Negative paintExtent!
666            properties.add(DoubleProperty::new("paintExtent", self.paint_extent).tooltip("!"));
667        }
668        properties
669            .add(DoubleProperty::new("paintOrigin", self.paint_origin).default_value(Some(0.0)));
670        properties.add(
671            DoubleProperty::new("layoutExtent", self.layout_extent)
672                .default_value(Some(self.paint_extent)),
673        );
674        properties.add(DoubleProperty::new("maxPaintExtent", self.max_paint_extent));
675        properties.add(
676            DoubleProperty::new("hitTestExtent", self.hit_test_extent)
677                .default_value(Some(self.paint_extent)),
678        );
679        properties.add(
680            DiagnosticsProperty::<bool>::new("hasVisualOverflow", self.has_visual_overflow)
681                .default_value(Some(false)),
682        );
683        properties.add(
684            DoubleProperty::new("scrollOffsetCorrection", self.scroll_offset_correction)
685                .default_value(None),
686        );
687        properties
688            .add(DoubleProperty::new("cacheExtent", self.cache_extent).default_value(Some(0.0)));
689    }
690}
691
692/// Dart's `SliverGeometry.toString`, the single-line form of its `debugFillProperties`.
693impl Display for SliverGeometry {
694    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
695        f.write_str(&Diagnosticable::to_string(self))
696    }
697}
698
699/// Method signature for hit testing a [`RenderSliver`].
700///
701/// Used by [`SliverHitTestResult::add_with_axis_offset`] to hit test [`RenderSliver`] children.
702///
703/// See also:
704///
705///  * [`RenderSliver::hit_test`], which documents more details around hit testing slivers.
706pub type SliverHitTest<'r> = dyn FnOnce(&mut SliverHitTestResult<'r>, f64, f64) -> bool;
707
708/// The result of performing a hit test on [`RenderSliver`]s.
709///
710/// A view over a [`HitTestResult`]: Dart's `SliverHitTestResult.wrap`. Dart's bare
711/// `SliverHitTestResult()` constructor is `wrap` over a fresh [`HitTestResult`].
712pub struct SliverHitTestResult<'a>(&'a mut HitTestResult);
713
714impl<'a> SliverHitTestResult<'a> {
715    /// Wraps `result` to create a [`SliverHitTestResult`] that shares its path.
716    ///
717    /// This is used by render objects that adapt between the sliver world and the non-sliver
718    /// world.
719    pub fn wrap(result: &'a mut HitTestResult) -> SliverHitTestResult<'a> {
720        SliverHitTestResult(result)
721    }
722
723    /// Transforms `main_axis_position` and `cross_axis_position` to the local coordinate system
724    /// of a child for hit-testing the child.
725    ///
726    /// The actual hit testing of the child needs to be implemented in the provided `hit_test`
727    /// callback, which is invoked with the transformed positions as arguments.
728    ///
729    /// For the transform `main_axis_offset` is subtracted from `main_axis_position` and
730    /// `cross_axis_offset` is subtracted from `cross_axis_position`.
731    ///
732    /// The `paint_offset` describes how the paint position of a point painted at the provided
733    /// `main_axis_position` and `cross_axis_position` would change after `main_axis_offset` and
734    /// `cross_axis_offset` have been applied. It is used to properly convert pointer events to
735    /// the local coordinate system of the event receiver.
736    ///
737    /// The `paint_offset` may be `None` if `main_axis_offset` and `cross_axis_offset` are both
738    /// zero.
739    ///
740    /// The function returns the return value of `hit_test`.
741    pub fn add_with_axis_offset(
742        &mut self,
743        paint_offset: Option<Offset>,
744        main_axis_offset: f64,
745        cross_axis_offset: f64,
746        main_axis_position: f64,
747        cross_axis_position: f64,
748        hit_test: impl FnOnce(&mut SliverHitTestResult<'_>, f64, f64) -> bool,
749    ) -> bool {
750        if let Some(paint_offset) = paint_offset {
751            self.0.push_offset(Offset::ZERO - paint_offset);
752        }
753        let is_hit = hit_test(
754            self,
755            main_axis_position - main_axis_offset,
756            cross_axis_position - cross_axis_offset,
757        );
758        if paint_offset.is_some() {
759            self.0.pop_transform();
760        }
761        is_hit
762    }
763}
764
765impl Deref for SliverHitTestResult<'_> {
766    type Target = HitTestResult;
767
768    fn deref(&self) -> &HitTestResult {
769        self.0
770    }
771}
772
773impl DerefMut for SliverHitTestResult<'_> {
774    fn deref_mut(&mut self) -> &mut HitTestResult {
775        self.0
776    }
777}
778
779/// A hit test entry used by [`RenderSliver`].
780///
781/// The coordinate system used by this hit test entry is relative to the [`AxisDirection`] of
782/// the target sliver.
783///
784/// Dart's `SliverHitTestEntry` subclasses `HitTestEntry`; here it is the entry's target,
785/// carrying the sliver and the two positions. It becomes a [`HitTestEntry`] with [`From`].
786#[derive(Clone, Copy, Debug)]
787pub struct SliverHitTestEntry {
788    target: AnyRenderSliver,
789    main_axis_position: f64,
790    cross_axis_position: f64,
791}
792
793impl SliverHitTestEntry {
794    /// Creates a sliver hit test entry.
795    pub fn new(
796        target: AnyRenderSliver,
797        main_axis_position: f64,
798        cross_axis_position: f64,
799    ) -> SliverHitTestEntry {
800        SliverHitTestEntry {
801            target,
802            main_axis_position,
803            cross_axis_position,
804        }
805    }
806
807    /// The [`RenderSliver`] that was hit.
808    pub fn target(&self) -> AnyRenderSliver {
809        self.target
810    }
811
812    /// The distance in the [`AxisDirection`] from the edge of the sliver's painted area (as
813    /// given by the [`SliverConstraints::scroll_offset`]) to the hit point.
814    ///
815    /// This can be an unusual direction, for example in the [`AxisDirection::Up`] case this is
816    /// a distance from the _bottom_ of the sliver's painted area.
817    pub fn main_axis_position(&self) -> f64 {
818        self.main_axis_position
819    }
820
821    /// The distance to the hit point in the axis opposite the [`SliverConstraints::axis`].
822    ///
823    /// If the cross axis is horizontal (i.e. the [`SliverConstraints::axis_direction`] is
824    /// either [`AxisDirection::Down`] or [`AxisDirection::Up`]), then this is a distance from
825    /// the left edge of the sliver. If the cross axis is vertical, then this is a distance
826    /// from the top edge of the sliver.
827    ///
828    /// This is always a distance from the left or top of the parent, never a distance from the
829    /// right or bottom.
830    pub fn cross_axis_position(&self) -> f64 {
831        self.cross_axis_position
832    }
833}
834
835impl HitTestTarget for SliverHitTestEntry {
836    fn arena_id(&self) -> Option<HandleId> {
837        Some(self.target.id)
838    }
839
840    fn handle_event(&self, app: &mut App, event: &PointerEvent, _entry: &HitTestEntry) {
841        self.target.handle_event(app, event, self);
842    }
843}
844
845impl From<SliverHitTestEntry> for HitTestEntry {
846    fn from(entry: SliverHitTestEntry) -> HitTestEntry {
847        HitTestEntry::new(entry)
848    }
849}
850
851/// Parent data structure used by parents of slivers that position their children using layout
852/// offsets.
853///
854/// This data structure is optimized for fast layout. It is best used by parents that expect to
855/// have many children whose relative positions don't change even when the scroll offset does.
856#[derive(Clone, Copy, Debug, Default)]
857pub struct SliverLogicalParentData {
858    /// The position of the child relative to the zero scroll offset.
859    ///
860    /// The number of pixels from the zero scroll offset of the parent sliver (the line at
861    /// which its [`SliverConstraints::scroll_offset`] is zero) to the side of the child closest
862    /// to that offset. It can be `None` when it cannot be determined. The value will be set
863    /// after layout.
864    ///
865    /// In a typical list, this does not change as the parent is scrolled.
866    pub layout_offset: Option<f64>,
867}
868
869impl SliverLogicalParentData {
870    /// Creates parent data with no layout offset.
871    pub const fn new() -> SliverLogicalParentData {
872        SliverLogicalParentData {
873            layout_offset: None,
874        }
875    }
876}
877
878impl ParentData for SliverLogicalParentData {
879    fn provide(&self, id: TypeId) -> Option<&dyn Any> {
880        (id == TypeId::of::<SliverLogicalParentData>()).then_some(self)
881    }
882
883    fn provide_mut(&mut self, id: TypeId) -> Option<&mut dyn Any> {
884        (id == TypeId::of::<SliverLogicalParentData>()).then_some(self)
885    }
886}
887
888impl Display for SliverLogicalParentData {
889    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
890        match self.layout_offset {
891            None => f.write_str("layoutOffset=None"),
892            Some(offset) => write!(f, "layoutOffset={offset:.1}"),
893        }
894    }
895}
896
897/// Parent data for slivers that have multiple children and that position their children using
898/// layout offsets.
899#[derive(Debug)]
900pub struct SliverLogicalContainerParentData {
901    sliver_logical: SliverLogicalParentData,
902    container: ContainerParentData<AnyRenderSliver>,
903}
904
905impl SliverLogicalContainerParentData {
906    /// Creates parent data with no layout offset and no siblings.
907    pub const fn new() -> SliverLogicalContainerParentData {
908        SliverLogicalContainerParentData {
909            sliver_logical: SliverLogicalParentData::new(),
910            container: ContainerParentData::new(),
911        }
912    }
913
914    /// The [`SliverLogicalParentData`] half.
915    pub fn sliver_logical_parent_data(&self) -> &SliverLogicalParentData {
916        &self.sliver_logical
917    }
918
919    /// See [`sliver_logical_parent_data`](Self::sliver_logical_parent_data).
920    pub fn sliver_logical_parent_data_mut(&mut self) -> &mut SliverLogicalParentData {
921        &mut self.sliver_logical
922    }
923
924    /// See [`SliverLogicalParentData::layout_offset`].
925    pub fn layout_offset(&self) -> Option<f64> {
926        self.sliver_logical.layout_offset
927    }
928
929    /// Sets [`layout_offset`](Self::layout_offset).
930    pub fn set_layout_offset(&mut self, value: Option<f64>) {
931        self.sliver_logical.layout_offset = value;
932    }
933}
934
935impl Default for SliverLogicalContainerParentData {
936    fn default() -> SliverLogicalContainerParentData {
937        SliverLogicalContainerParentData::new()
938    }
939}
940
941impl ParentData for SliverLogicalContainerParentData {
942    fn detach(&mut self) {
943        ContainerParentDataMixin::detach(self);
944    }
945
946    fn provide(&self, id: TypeId) -> Option<&dyn Any> {
947        if id == TypeId::of::<SliverLogicalContainerParentData>() {
948            return Some(self);
949        }
950        self.sliver_logical.provide(id)
951    }
952
953    fn provide_mut(&mut self, id: TypeId) -> Option<&mut dyn Any> {
954        if id == TypeId::of::<SliverLogicalContainerParentData>() {
955            return Some(self);
956        }
957        self.sliver_logical.provide_mut(id)
958    }
959}
960
961impl ContainerParentDataMixin for SliverLogicalContainerParentData {
962    type ChildType = AnyRenderSliver;
963
964    fn container_parent_data(&self) -> &ContainerParentData<AnyRenderSliver> {
965        &self.container
966    }
967
968    fn container_parent_data_mut(&mut self) -> &mut ContainerParentData<AnyRenderSliver> {
969        &mut self.container
970    }
971}
972
973impl Display for SliverLogicalContainerParentData {
974    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
975        Display::fmt(&self.sliver_logical, f)
976    }
977}
978
979/// Parent data structure used by parents of slivers that position their children using absolute
980/// coordinates.
981///
982/// For example, used by [`crate::RenderViewport`].
983///
984/// This data structure is optimized for fast painting, at the cost of requiring additional work
985/// during layout when the children change their offsets. It is best used by parents that expect
986/// to have few children, especially if those children will themselves be very tall relative to
987/// the parent.
988#[derive(Clone, Copy, Debug)]
989pub struct SliverPhysicalParentData {
990    /// The position of the child relative to the parent.
991    ///
992    /// This is the distance from the top left visible corner of the parent to the top left
993    /// visible corner of the sliver.
994    pub paint_offset: Offset,
995
996    /// The cross axis flex factor to use for this sliver child.
997    ///
998    /// If used outside of a `SliverCrossAxisGroup` widget, this value has no meaning.
999    ///
1000    /// If `None` or zero, the child is inflexible and determines its own size in the cross
1001    /// axis. If non-zero, the amount of space the child can occupy in the cross axis is
1002    /// determined by dividing the free space (after placing the inflexible children) according
1003    /// to the flex factors of the flexible children.
1004    pub cross_axis_flex: Option<i32>,
1005}
1006
1007impl SliverPhysicalParentData {
1008    /// Creates parent data with a zero paint offset.
1009    pub const fn new() -> SliverPhysicalParentData {
1010        SliverPhysicalParentData {
1011            paint_offset: Offset::ZERO,
1012            cross_axis_flex: None,
1013        }
1014    }
1015
1016    /// Apply the [`paint_offset`](Self::paint_offset) to the given `transform`.
1017    ///
1018    /// Used to implement [`RenderObject::apply_paint_transform`] by slivers that use
1019    /// [`SliverPhysicalParentData`].
1020    pub fn apply_paint_transform(&self, transform: &mut Matrix4) {
1021        // Hit test logic relies on this always providing an invertible matrix.
1022        translate(transform, self.paint_offset.dx(), self.paint_offset.dy());
1023    }
1024}
1025
1026impl Default for SliverPhysicalParentData {
1027    fn default() -> SliverPhysicalParentData {
1028        SliverPhysicalParentData::new()
1029    }
1030}
1031
1032impl ParentData for SliverPhysicalParentData {
1033    fn provide(&self, id: TypeId) -> Option<&dyn Any> {
1034        (id == TypeId::of::<SliverPhysicalParentData>()).then_some(self)
1035    }
1036
1037    fn provide_mut(&mut self, id: TypeId) -> Option<&mut dyn Any> {
1038        (id == TypeId::of::<SliverPhysicalParentData>()).then_some(self)
1039    }
1040}
1041
1042impl Display for SliverPhysicalParentData {
1043    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1044        write!(f, "paintOffset={}", self.paint_offset)
1045    }
1046}
1047
1048/// Parent data for slivers that have multiple children and that position their children using
1049/// absolute coordinates.
1050#[derive(Debug)]
1051pub struct SliverPhysicalContainerParentData {
1052    sliver_physical: SliverPhysicalParentData,
1053    container: ContainerParentData<AnyRenderSliver>,
1054}
1055
1056impl SliverPhysicalContainerParentData {
1057    /// Creates parent data with a zero paint offset and no siblings.
1058    pub const fn new() -> SliverPhysicalContainerParentData {
1059        SliverPhysicalContainerParentData {
1060            sliver_physical: SliverPhysicalParentData::new(),
1061            container: ContainerParentData::new(),
1062        }
1063    }
1064
1065    /// The [`SliverPhysicalParentData`] half.
1066    pub fn sliver_physical_parent_data(&self) -> &SliverPhysicalParentData {
1067        &self.sliver_physical
1068    }
1069
1070    /// See [`sliver_physical_parent_data`](Self::sliver_physical_parent_data).
1071    pub fn sliver_physical_parent_data_mut(&mut self) -> &mut SliverPhysicalParentData {
1072        &mut self.sliver_physical
1073    }
1074
1075    /// See [`SliverPhysicalParentData::paint_offset`].
1076    pub fn paint_offset(&self) -> Offset {
1077        self.sliver_physical.paint_offset
1078    }
1079
1080    /// Sets [`paint_offset`](Self::paint_offset).
1081    pub fn set_paint_offset(&mut self, value: Offset) {
1082        self.sliver_physical.paint_offset = value;
1083    }
1084
1085    /// See [`SliverPhysicalParentData::apply_paint_transform`].
1086    pub fn apply_paint_transform(&self, transform: &mut Matrix4) {
1087        self.sliver_physical.apply_paint_transform(transform);
1088    }
1089}
1090
1091impl Default for SliverPhysicalContainerParentData {
1092    fn default() -> SliverPhysicalContainerParentData {
1093        SliverPhysicalContainerParentData::new()
1094    }
1095}
1096
1097impl ParentData for SliverPhysicalContainerParentData {
1098    fn detach(&mut self) {
1099        ContainerParentDataMixin::detach(self);
1100    }
1101
1102    fn provide(&self, id: TypeId) -> Option<&dyn Any> {
1103        if id == TypeId::of::<SliverPhysicalContainerParentData>() {
1104            return Some(self);
1105        }
1106        self.sliver_physical.provide(id)
1107    }
1108
1109    fn provide_mut(&mut self, id: TypeId) -> Option<&mut dyn Any> {
1110        if id == TypeId::of::<SliverPhysicalContainerParentData>() {
1111            return Some(self);
1112        }
1113        self.sliver_physical.provide_mut(id)
1114    }
1115}
1116
1117impl ContainerParentDataMixin for SliverPhysicalContainerParentData {
1118    type ChildType = AnyRenderSliver;
1119
1120    fn container_parent_data(&self) -> &ContainerParentData<AnyRenderSliver> {
1121        &self.container
1122    }
1123
1124    fn container_parent_data_mut(&mut self) -> &mut ContainerParentData<AnyRenderSliver> {
1125        &mut self.container
1126    }
1127}
1128
1129impl Display for SliverPhysicalContainerParentData {
1130    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1131        Display::fmt(&self.sliver_physical, f)
1132    }
1133}
1134
1135/// The body of [`RenderSliver::calculate_paint_offset`], reachable without a sliver.
1136pub(crate) fn calculate_paint_offset(constraints: SliverConstraints, from: f64, to: f64) -> f64 {
1137    debug_assert!(from <= to);
1138    let a = constraints.scroll_offset;
1139    let b = constraints.scroll_offset + constraints.remaining_paint_extent;
1140    // the clamp on the next line is to avoid floating point rounding errors
1141    clamp_double(
1142        clamp_double(to, a, b) - clamp_double(from, a, b),
1143        0.0,
1144        constraints.remaining_paint_extent,
1145    )
1146}
1147
1148/// The body of [`RenderSliver::calculate_cache_offset`], reachable without a sliver.
1149pub(crate) fn calculate_cache_offset(constraints: SliverConstraints, from: f64, to: f64) -> f64 {
1150    debug_assert!(from <= to);
1151    let a = constraints.scroll_offset + constraints.cache_origin;
1152    let b = constraints.scroll_offset + constraints.remaining_cache_extent;
1153    // the clamp on the next line is to avoid floating point rounding errors
1154    clamp_double(
1155        clamp_double(to, a, b) - clamp_double(from, a, b),
1156        0.0,
1157        constraints.remaining_cache_extent,
1158    )
1159}
1160
1161/// Flutter's `RenderSliver` fields.
1162pub struct RenderSliverData {
1163    pub(crate) geometry: Option<SliverGeometry>,
1164    pub(crate) constraints: Option<SliverConstraints>,
1165}
1166
1167impl RenderSliverData {
1168    /// Unlaid-out sliver state.
1169    pub fn new() -> RenderSliverData {
1170        RenderSliverData {
1171            geometry: None,
1172            constraints: None,
1173        }
1174    }
1175}
1176
1177impl Default for RenderSliverData {
1178    fn default() -> RenderSliverData {
1179        RenderSliverData::new()
1180    }
1181}
1182
1183/// Implements [`RenderSliver`] field accessors for a `render_sliver` field.
1184#[macro_export]
1185macro_rules! render_sliver_accessors {
1186    () => {
1187        fn render_sliver_data(
1188            self: $crate::RenderHandle<Self>,
1189            app: &::waft_foundation::App,
1190        ) -> &$crate::RenderSliverData {
1191            &self.get(app).render_sliver
1192        }
1193        fn render_sliver_data_mut(
1194            self: $crate::RenderHandle<Self>,
1195            app: &mut ::waft_foundation::App,
1196        ) -> &mut $crate::RenderSliverData {
1197            &mut self.get_mut(app).render_sliver
1198        }
1199    };
1200}
1201
1202/// A render object using the sliver protocol.
1203///
1204/// Flutter's counterpart is `RenderSliver`. [`RenderObject::perform_layout`] is the leaf
1205/// override; [`AnyRenderSliver::layout`] is the framework wrapper. `RenderObject`'s tree
1206/// operations are provided here and forward to [`as_object`](Self::as_object).
1207pub trait RenderSliver: RenderObject {
1208    /// Mixin field access.
1209    fn render_sliver_data(self: RenderHandle<Self>, app: &App) -> &RenderSliverData;
1210
1211    /// See [`render_sliver_data`](Self::render_sliver_data).
1212    fn render_sliver_data_mut(self: RenderHandle<Self>, app: &mut App) -> &mut RenderSliverData;
1213
1214    /// Whether this sliver should be included in the semantics tree.
1215    ///
1216    /// This value is used by [`RenderViewportBase`](crate::RenderViewportBase) to ensure a
1217    /// sliver is included in the semantics tree regardless of its geometry.
1218    ///
1219    /// A [`RenderSliver`] should override this value to `true` to ensure its child is included
1220    /// in the semantics tree. For example if your sliver is under a [`crate::RenderViewport`]
1221    /// you may want to wrap it with a `SliverEnsureSemantics` to ensure that:
1222    ///
1223    /// 1. It is still visited by `RenderViewportBase.visitChildrenForSemantics` regardless of
1224    ///    its geometry. This includes cases where your sliver is outside the current viewport
1225    ///    and cache extent.
1226    /// 2. Its semantic information is not clipped out by the [`crate::RenderViewport`] in
1227    ///    `RenderViewportBase.describeSemanticsClip` or
1228    ///    [`RenderViewportBase::describe_approximate_paint_clip`](crate::RenderViewportBase::describe_approximate_paint_clip).
1229    ///
1230    /// If a given [`RenderSliver`] does not provide a valid `semanticBounds` it will still be
1231    /// dropped from the semantics tree.
1232    ///
1233    /// Defaults to `false`.
1234    fn ensure_semantics(self: RenderHandle<Self>, _app: &App) -> bool {
1235        let _ = self;
1236        false
1237    }
1238
1239    /// The sliver constraints most recently supplied by the parent.
1240    fn constraints(self: RenderHandle<Self>, app: &App) -> SliverConstraints {
1241        self.render_sliver_data(app).constraints.unwrap_or_else(|| {
1242            panic!("A RenderObject does not have any constraints before it has been laid out.")
1243        })
1244    }
1245
1246    /// The amount of space this sliver occupies.
1247    fn geometry(self: RenderHandle<Self>, app: &App) -> SliverGeometry {
1248        self.as_sliver().geometry(app)
1249    }
1250
1251    /// Sets the geometry of this sliver. Call from [`RenderObject::perform_layout`].
1252    fn set_geometry(self: RenderHandle<Self>, app: &mut App, geometry: SliverGeometry) {
1253        self.as_sliver().set_geometry(app, geometry)
1254    }
1255
1256    /// An estimate of the bounds within which this render object will paint: the paint extent
1257    /// along the main axis by the cross axis extent.
1258    fn paint_bounds(self: RenderHandle<Self>, app: &App) -> Rect {
1259        let constraints = self.constraints(app);
1260        let geometry = self.geometry(app);
1261        match constraints.axis() {
1262            Axis::Horizontal => Rect::from_ltwh(
1263                0.0,
1264                0.0,
1265                geometry.paint_extent,
1266                constraints.cross_axis_extent,
1267            ),
1268            Axis::Vertical => Rect::from_ltwh(
1269                0.0,
1270                0.0,
1271                constraints.cross_axis_extent,
1272                geometry.paint_extent,
1273            ),
1274        }
1275    }
1276
1277    /// For a center sliver, the distance before the absolute zero scroll offset that this
1278    /// sliver can cover.
1279    ///
1280    /// For example, if an [`AxisDirection::Down`] viewport with a
1281    /// [`crate::RenderViewport::anchor`] of 0.5 has a single sliver with a height of 100.0 and
1282    /// its `center_offset_adjustment` returns 50.0, then the sliver will be centered in the
1283    /// viewport when the scroll offset is 0.0.
1284    ///
1285    /// The distance here is in the opposite direction of the viewport's axis direction, so
1286    /// values will typically be positive.
1287    fn center_offset_adjustment(self: RenderHandle<Self>, _app: &App) -> f64 {
1288        let _ = self;
1289        0.0
1290    }
1291
1292    /// Determines the set of render objects located at the given position.
1293    ///
1294    /// Returns true if the given point is contained in this render object or one of its
1295    /// descendants. Adds any render objects that contain the point to the given hit test
1296    /// result.
1297    ///
1298    /// The caller is responsible for providing the position in the local coordinate space of
1299    /// the callee. The callee is responsible for checking whether the given position is within
1300    /// its bounds.
1301    ///
1302    /// # Coordinates for `RenderSliver` objects
1303    ///
1304    /// The `main_axis_position` is the distance in the [`AxisDirection`] (after applying the
1305    /// [`GrowthDirection`]) from the edge of the sliver's painted area. This can be an unusual
1306    /// direction, for example in the [`AxisDirection::Up`] case this is a distance from the
1307    /// _bottom_ of the sliver's painted area.
1308    ///
1309    /// The `cross_axis_position` is the distance in the other axis. If the cross axis is
1310    /// horizontal (i.e. the [`SliverConstraints::axis_direction`] is either
1311    /// [`AxisDirection::Down`] or [`AxisDirection::Up`]), then the `cross_axis_position` is a
1312    /// distance from the left edge of the sliver. Otherwise it is a distance from the top edge.
1313    ///
1314    /// # Implementing hit testing for slivers
1315    ///
1316    /// The most straight-forward way to implement hit testing for a new sliver render object is
1317    /// to override its [`hit_test_self`](Self::hit_test_self) and
1318    /// [`hit_test_children`](Self::hit_test_children) methods.
1319    fn hit_test(
1320        self: RenderHandle<Self>,
1321        app: &mut App,
1322        result: &mut SliverHitTestResult<'_>,
1323        main_axis_position: f64,
1324        cross_axis_position: f64,
1325    ) -> bool {
1326        if main_axis_position >= 0.0
1327            && main_axis_position < self.geometry(app).hit_test_extent
1328            && cross_axis_position >= 0.0
1329            && cross_axis_position < self.constraints(app).cross_axis_extent
1330            && (self.hit_test_children(app, result, main_axis_position, cross_axis_position)
1331                || self.hit_test_self(app, main_axis_position, cross_axis_position))
1332        {
1333            result.add(
1334                SliverHitTestEntry::new(self.as_sliver(), main_axis_position, cross_axis_position)
1335                    .into(),
1336            );
1337            return true;
1338        }
1339        false
1340    }
1341
1342    /// Override this method if this render object can be hit even if its children were not hit.
1343    ///
1344    /// Used by [`hit_test`](Self::hit_test). If you override `hit_test` and do not call this
1345    /// function, then you don't need to implement this function.
1346    fn hit_test_self(
1347        self: RenderHandle<Self>,
1348        _app: &App,
1349        _main_axis_position: f64,
1350        _cross_axis_position: f64,
1351    ) -> bool {
1352        let _ = self;
1353        false
1354    }
1355
1356    /// Override this method to check whether any children are located at the given position.
1357    ///
1358    /// Typically children should be hit-tested in reverse paint order so that hit tests at
1359    /// locations where children overlap hit the child that is visually "on top" (i.e., paints
1360    /// later).
1361    ///
1362    /// Used by [`hit_test`](Self::hit_test). If you override `hit_test` and do not call this
1363    /// function, then you don't need to implement this function.
1364    fn hit_test_children(
1365        self: RenderHandle<Self>,
1366        _app: &mut App,
1367        _result: &mut SliverHitTestResult<'_>,
1368        _main_axis_position: f64,
1369        _cross_axis_position: f64,
1370    ) -> bool {
1371        let _ = self;
1372        false
1373    }
1374
1375    /// Override to handle pointer events that hit this render object.
1376    fn handle_event(
1377        self: RenderHandle<Self>,
1378        _app: &mut App,
1379        _event: &PointerEvent,
1380        _entry: &SliverHitTestEntry,
1381    ) {
1382        let _ = self;
1383    }
1384
1385    /// Computes the portion of the region from `from` to `to` that is visible, assuming that
1386    /// only the region from the [`SliverConstraints::scroll_offset`] that is
1387    /// [`SliverConstraints::remaining_paint_extent`] high is visible, and that the relationship
1388    /// between scroll offsets and paint offsets is linear.
1389    ///
1390    /// For example, if the constraints have a scroll offset of 100 and a remaining paint extent
1391    /// of 100, and the arguments to this method describe the region 50..150, then the returned
1392    /// value would be 50 (from scroll offset 100 to scroll offset 150).
1393    ///
1394    /// This method is not useful if there is not a 1:1 relationship between consumed scroll
1395    /// offset and consumed paint extent.
1396    fn calculate_paint_offset(
1397        self: RenderHandle<Self>,
1398        _app: &App,
1399        constraints: SliverConstraints,
1400        from: f64,
1401        to: f64,
1402    ) -> f64 {
1403        let _ = self;
1404        calculate_paint_offset(constraints, from, to)
1405    }
1406
1407    /// Computes the portion of the region from `from` to `to` that is within the cache extent
1408    /// of the viewport, assuming that only the region from the
1409    /// [`SliverConstraints::cache_origin`] that is
1410    /// [`SliverConstraints::remaining_cache_extent`] high is visible, and that the relationship
1411    /// between scroll offsets and paint offsets is linear.
1412    ///
1413    /// This method is not useful if there is not a 1:1 relationship between consumed scroll
1414    /// offset and consumed cache extent.
1415    fn calculate_cache_offset(
1416        self: RenderHandle<Self>,
1417        _app: &App,
1418        constraints: SliverConstraints,
1419        from: f64,
1420        to: f64,
1421    ) -> f64 {
1422        let _ = self;
1423        calculate_cache_offset(constraints, from, to)
1424    }
1425
1426    /// Returns the distance from the leading _visible_ edge of the sliver to the side of the
1427    /// given child closest to that edge.
1428    ///
1429    /// For example, if the [`constraints`](Self::constraints) describe this sliver as having an
1430    /// axis direction of [`AxisDirection::Down`], then this is the distance from the top of the
1431    /// visible portion of the sliver to the top of the child. On the other hand, if the axis
1432    /// direction is [`AxisDirection::Up`], then this is the distance from the bottom of the
1433    /// visible portion of the sliver to the bottom of the child. In both cases, this is the
1434    /// direction of increasing [`SliverConstraints::scroll_offset`] and
1435    /// [`SliverLogicalParentData::layout_offset`].
1436    ///
1437    /// For children that are slivers, the leading edge of the _child_ will be the leading
1438    /// _visible_ edge of the child, not the part of the child that would locally be at scroll
1439    /// offset 0.0. For box children it is the actual distance to the edge of the box, since
1440    /// those boxes do not know how to handle being scrolled.
1441    ///
1442    /// This method differs from [`child_scroll_offset`](Self::child_scroll_offset) in that it
1443    /// gives the distance from the leading _visible_ edge of the sliver whereas
1444    /// `child_scroll_offset` gives the distance from the sliver's zero scroll offset.
1445    ///
1446    /// Calling this for a child that is not visible is not valid.
1447    fn child_main_axis_position(
1448        self: RenderHandle<Self>,
1449        _app: &App,
1450        _child: AnyRenderObject,
1451    ) -> f64 {
1452        let _ = self;
1453        panic!("this RenderSliver does not implement child_main_axis_position")
1454    }
1455
1456    /// Returns the distance along the cross axis from the zero of the cross axis in this
1457    /// sliver's paint coordinate space to the nearest side of the given child.
1458    ///
1459    /// For example, if the [`constraints`](Self::constraints) describe this sliver as having an
1460    /// axis direction of [`AxisDirection::Down`] or [`AxisDirection::Up`], then this is the
1461    /// distance from the left of the sliver to the left of the child. If the axis direction is
1462    /// [`AxisDirection::Left`] or [`AxisDirection::Right`], then it is the distance from the
1463    /// top of the sliver to the top of the child.
1464    ///
1465    /// Calling this for a child that is not visible is not valid.
1466    fn child_cross_axis_position(
1467        self: RenderHandle<Self>,
1468        _app: &App,
1469        _child: AnyRenderObject,
1470    ) -> f64 {
1471        let _ = self;
1472        0.0
1473    }
1474
1475    /// Returns the scroll offset for the leading edge of the given child.
1476    ///
1477    /// The `child` must be a child of this sliver.
1478    ///
1479    /// If there are pinned slivers before `child`, the offset should be reduced by the extent
1480    /// of the pinned children.
1481    ///
1482    /// This method differs from [`child_main_axis_position`](Self::child_main_axis_position) in
1483    /// that `child_main_axis_position` gives the distance from the leading _visible_ edge of
1484    /// the sliver whereas this gives the distance from the sliver's zero scroll offset.
1485    fn child_scroll_offset(
1486        self: RenderHandle<Self>,
1487        app: &App,
1488        child: AnyRenderObject,
1489    ) -> Option<f64> {
1490        debug_assert_eq!(child.parent(app), Some(self.as_object()));
1491        Some(0.0)
1492    }
1493
1494    /// This returns a [`Size`] with dimensions relative to the leading edge of the sliver,
1495    /// specifically the same offset that is given to the [`RenderObject::paint`] method. This
1496    /// means that the dimensions may be negative.
1497    ///
1498    /// This is only valid after layout has completed.
1499    ///
1500    /// See also:
1501    ///
1502    ///  * [`get_absolute_size`](Self::get_absolute_size), which returns absolute size.
1503    fn get_absolute_size_relative_to_origin(self: RenderHandle<Self>, app: &App) -> Size {
1504        debug_assert!(!self.as_object().debug_needs_layout(app));
1505        let constraints = self.constraints(app);
1506        let paint_extent = self.geometry(app).paint_extent;
1507        match apply_growth_direction_to_axis_direction(
1508            constraints.axis_direction,
1509            constraints.growth_direction,
1510        ) {
1511            AxisDirection::Up => Size::new(constraints.cross_axis_extent, -paint_extent),
1512            AxisDirection::Down => Size::new(constraints.cross_axis_extent, paint_extent),
1513            AxisDirection::Left => Size::new(-paint_extent, constraints.cross_axis_extent),
1514            AxisDirection::Right => Size::new(paint_extent, constraints.cross_axis_extent),
1515        }
1516    }
1517
1518    /// This returns the absolute [`Size`] of the sliver.
1519    ///
1520    /// The dimensions are always positive and calling this is only valid after layout has
1521    /// completed.
1522    ///
1523    /// See also:
1524    ///
1525    ///  * [`get_absolute_size_relative_to_origin`](Self::get_absolute_size_relative_to_origin),
1526    ///    which returns the size relative to the leading edge of the sliver.
1527    fn get_absolute_size(self: RenderHandle<Self>, app: &App) -> Size {
1528        debug_assert!(!self.as_object().debug_needs_layout(app));
1529        let constraints = self.constraints(app);
1530        let paint_extent = self.geometry(app).paint_extent;
1531        match constraints.axis_direction {
1532            AxisDirection::Up | AxisDirection::Down => {
1533                Size::new(constraints.cross_axis_extent, paint_extent)
1534            }
1535            AxisDirection::Right | AxisDirection::Left => {
1536                Size::new(paint_extent, constraints.cross_axis_extent)
1537            }
1538        }
1539    }
1540
1541    /// Returns the [`Rect`] that covers the total paint extent of the sliver.
1542    ///
1543    /// The rect is expressed in the sliver's local coordinate system, which is axis-aligned
1544    /// with the painting context's canvas. The coordinate system's origin (0,0) corresponds to
1545    /// the `offset` argument passed to [`RenderObject::paint`].
1546    fn get_max_paint_rect(self: RenderHandle<Self>, app: &App) -> Rect {
1547        let Some(geometry) = self.render_sliver_data(app).geometry else {
1548            return Rect::ZERO;
1549        };
1550        if geometry.is_zero() {
1551            return Rect::ZERO;
1552        }
1553        let constraints = self.constraints(app);
1554        let mut max_paint_extent = geometry.max_paint_extent;
1555        if max_paint_extent.is_infinite() {
1556            max_paint_extent =
1557                constraints.scroll_offset + geometry.cache_extent + constraints.cache_origin;
1558        }
1559        let paint_extent = geometry.paint_extent;
1560        // To ensure the computed rect remains visible when pinned, the leading offset is capped
1561        // at the sliver's `scroll_extent - max_scroll_obstruction_extent`.
1562        let leading_offset = clamp_double(
1563            constraints.scroll_offset,
1564            0.0,
1565            geometry.scroll_extent - geometry.max_scroll_obstruction_extent,
1566        );
1567        let cross_axis_extent = geometry
1568            .cross_axis_extent
1569            .unwrap_or(constraints.cross_axis_extent);
1570
1571        let rect = match constraints.axis() {
1572            Axis::Horizontal => {
1573                Rect::from_ltwh(-leading_offset, 0.0, max_paint_extent, cross_axis_extent)
1574            }
1575            Axis::Vertical => {
1576                Rect::from_ltwh(0.0, -leading_offset, cross_axis_extent, max_paint_extent)
1577            }
1578        };
1579
1580        match apply_growth_direction_to_axis_direction(
1581            constraints.axis_direction,
1582            constraints.growth_direction,
1583        ) {
1584            AxisDirection::Right | AxisDirection::Down => rect,
1585            AxisDirection::Left => Rect::from_ltrb(
1586                paint_extent - rect.right,
1587                rect.top,
1588                paint_extent - rect.left,
1589                rect.bottom,
1590            ),
1591            AxisDirection::Up => Rect::from_ltrb(
1592                rect.left,
1593                paint_extent - rect.bottom,
1594                rect.right,
1595                paint_extent - rect.top,
1596            ),
1597        }
1598    }
1599
1600    /// See [`AnyRenderSliver::layout`].
1601    fn layout(
1602        self: RenderHandle<Self>,
1603        app: &mut App,
1604        constraints: SliverConstraints,
1605        parent_uses_size: bool,
1606    ) {
1607        self.as_sliver().layout(app, constraints, parent_uses_size)
1608    }
1609
1610    /// The type-erased `RenderSliver` handle. Free: the vtable is a `const`, and the id is copied.
1611    fn as_sliver(self: RenderHandle<Self>) -> AnyRenderSliver {
1612        AnyRenderSliver {
1613            id: self.id(),
1614            vtable: const { &RenderSliverVTable::of::<Self>() },
1615        }
1616    }
1617
1618    /// The type-erased `RenderObject` handle, through [`as_sliver`](Self::as_sliver).
1619    fn as_object(self: RenderHandle<Self>) -> AnyRenderObject {
1620        self.as_sliver().as_object()
1621    }
1622
1623    /// See [`AnyRenderObject::adopt_child`].
1624    fn adopt_child(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
1625        self.as_object().adopt_child(app, child)
1626    }
1627
1628    /// See [`AnyRenderObject::drop_child`].
1629    fn drop_child(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
1630        self.as_object().drop_child(app, child)
1631    }
1632
1633    /// See [`AnyRenderObject::mark_needs_layout`].
1634    fn mark_needs_layout(self: RenderHandle<Self>, app: &mut App) {
1635        self.as_object().mark_needs_layout(app)
1636    }
1637
1638    /// See [`AnyRenderObject::mark_needs_paint`].
1639    fn mark_needs_paint(self: RenderHandle<Self>, app: &mut App) {
1640        self.as_object().mark_needs_paint(app)
1641    }
1642
1643    /// See [`AnyRenderObject::mark_needs_composited_layer_update`].
1644    fn mark_needs_composited_layer_update(self: RenderHandle<Self>, app: &mut App) {
1645        self.as_object().mark_needs_composited_layer_update(app)
1646    }
1647
1648    /// See [`AnyRenderObject::schedule_initial_layout`].
1649    fn schedule_initial_layout(self: RenderHandle<Self>, app: &mut App) {
1650        self.as_object().schedule_initial_layout(app)
1651    }
1652
1653    /// See [`AnyRenderObject::parent`].
1654    fn parent(self: RenderHandle<Self>, app: &App) -> Option<AnyRenderObject> {
1655        self.as_object().parent(app)
1656    }
1657
1658    /// See [`AnyRenderObject::owner`].
1659    fn owner(self: RenderHandle<Self>, app: &App) -> Option<Handle<PipelineOwner>> {
1660        self.as_object().owner(app)
1661    }
1662
1663    /// See [`AnyRenderObject::attached`].
1664    fn attached(self: RenderHandle<Self>, app: &App) -> bool {
1665        self.as_object().attached(app)
1666    }
1667
1668    /// See [`AnyRenderObject::debug_needs_layout`].
1669    fn debug_needs_layout(self: RenderHandle<Self>, app: &App) -> bool {
1670        self.as_object().debug_needs_layout(app)
1671    }
1672}
1673
1674/// The vtable of an [`AnyRenderSliver`]: the object vtable plus the sliver accessors.
1675pub(crate) struct RenderSliverVTable {
1676    pub object: RenderObjectVTable,
1677    pub sliver_data: fn(&App, HandleId) -> &RenderSliverData,
1678    pub sliver_data_mut: fn(&mut App, HandleId) -> &mut RenderSliverData,
1679    pub ensure_semantics: fn(&App, HandleId) -> bool,
1680    pub hit_test: fn(&mut App, HandleId, &mut SliverHitTestResult<'_>, f64, f64) -> bool,
1681    pub handle_event: fn(&mut App, HandleId, &PointerEvent, &SliverHitTestEntry),
1682    pub center_offset_adjustment: fn(&App, HandleId) -> f64,
1683    pub child_scroll_offset: fn(&App, HandleId, AnyRenderObject) -> Option<f64>,
1684    pub child_main_axis_position: fn(&App, HandleId, AnyRenderObject) -> f64,
1685}
1686
1687impl RenderSliverVTable {
1688    const fn of<T: RenderSliver>() -> RenderSliverVTable {
1689        RenderSliverVTable {
1690            object: RenderObjectVTable::of::<T>(
1691                |app, id, child| <T as RenderObject>::setup_parent_data(resolve(id), app, child),
1692                |app, id| T::paint_bounds(resolve(id), app),
1693                |app, id, child, transform| {
1694                    <T as RenderObject>::apply_paint_transform(resolve(id), app, child, transform)
1695                },
1696                |app, id| <T as RenderObject>::perform_resize(resolve(id), app),
1697                |app, id| crate::object::RenderObjectBase::mark_needs_layout(resolve::<T>(id), app),
1698                None,
1699                Some(|| const { &RenderSliverVTable::of::<T>() }),
1700            ),
1701            sliver_data: |app, id| T::render_sliver_data(resolve(id), app),
1702            sliver_data_mut: |app, id| T::render_sliver_data_mut(resolve(id), app),
1703            ensure_semantics: |app, id| T::ensure_semantics(resolve(id), app),
1704            hit_test: |app, id, result, main, cross| {
1705                T::hit_test(resolve(id), app, result, main, cross)
1706            },
1707            handle_event: |app, id, event, entry| T::handle_event(resolve(id), app, event, entry),
1708            center_offset_adjustment: |app, id| T::center_offset_adjustment(resolve(id), app),
1709            child_scroll_offset: |app, id, child| T::child_scroll_offset(resolve(id), app, child),
1710            child_main_axis_position: |app, id, child| {
1711                T::child_main_axis_position(resolve(id), app, child)
1712            },
1713        }
1714    }
1715}
1716
1717impl<T: RenderSliver> RenderHandle<T> {
1718    /// Creates a sliver-protocol render object in `app`.
1719    pub fn new_sliver(app: &mut App, object: T) -> RenderHandle<T> {
1720        let this = create(app, object);
1721        let data = this.render_object_data_mut(app);
1722        data.object_vtable = Some(&const { RenderSliverVTable::of::<T>() }.object);
1723        // Flutter's `RenderObject()` constructor:
1724        // `_needsCompositing = isRepaintBoundary || alwaysNeedsCompositing` and
1725        // `_wasRepaintBoundary = isRepaintBoundary`.
1726        let is_repaint_boundary = this.is_repaint_boundary(app);
1727        let always_needs_compositing = this.always_needs_compositing(app);
1728        let data = this.render_object_data_mut(app);
1729        data.was_repaint_boundary = is_repaint_boundary;
1730        data.needs_compositing = is_repaint_boundary || always_needs_compositing;
1731        this
1732    }
1733}
1734
1735/// Erased `RenderSliver`.
1736#[derive(Clone, Copy)]
1737pub struct AnyRenderSliver {
1738    id: HandleId,
1739    vtable: &'static RenderSliverVTable,
1740}
1741
1742impl PartialEq for AnyRenderSliver {
1743    fn eq(&self, other: &AnyRenderSliver) -> bool {
1744        self.id == other.id
1745    }
1746}
1747
1748impl Eq for AnyRenderSliver {}
1749
1750impl std::hash::Hash for AnyRenderSliver {
1751    fn hash<H: Hasher>(&self, state: &mut H) {
1752        self.id.hash(state);
1753    }
1754}
1755
1756impl Debug for AnyRenderSliver {
1757    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1758        write!(f, "AnyRenderSliver({:?})", self.id)
1759    }
1760}
1761
1762impl AnyRenderSliver {
1763    pub(crate) fn from_vtable(
1764        id: HandleId,
1765        vtable: &'static RenderSliverVTable,
1766    ) -> AnyRenderSliver {
1767        AnyRenderSliver { id, vtable }
1768    }
1769
1770    /// The `RenderObject` view of this sliver. Free: points into the nested table.
1771    pub fn as_object(self) -> AnyRenderObject {
1772        AnyRenderObject::from_vtable(self.id, &self.vtable.object)
1773    }
1774
1775    pub(crate) fn sliver_data(self, app: &App) -> &RenderSliverData {
1776        (self.vtable.sliver_data)(app, self.id)
1777    }
1778
1779    fn sliver_data_mut(self, app: &mut App) -> &mut RenderSliverData {
1780        (self.vtable.sliver_data_mut)(app, self.id)
1781    }
1782
1783    /// See [`RenderSliver::ensure_semantics`].
1784    pub fn ensure_semantics(self, app: &App) -> bool {
1785        (self.vtable.ensure_semantics)(app, self.id)
1786    }
1787
1788    /// Compute the layout for this sliver.
1789    pub fn layout(self, app: &mut App, constraints: SliverConstraints, parent_uses_size: bool) {
1790        debug_assert!(constraints.debug_assert_is_valid(true));
1791        let same = self.sliver_data(app).constraints == Some(constraints);
1792        self.as_object()
1793            .run_layout(app, parent_uses_size, constraints.is_tight(), same, |app| {
1794                self.sliver_data_mut(app).constraints = Some(constraints)
1795            });
1796    }
1797
1798    /// The sliver constraints most recently supplied by the parent.
1799    ///
1800    /// # Panics
1801    ///
1802    /// If this sliver has not been laid out.
1803    pub fn constraints(self, app: &App) -> SliverConstraints {
1804        self.sliver_data(app).constraints.unwrap_or_else(|| {
1805            panic!("A RenderObject does not have any constraints before it has been laid out.")
1806        })
1807    }
1808
1809    /// See [`RenderSliver::hit_test`].
1810    pub fn hit_test(
1811        self,
1812        app: &mut App,
1813        result: &mut SliverHitTestResult<'_>,
1814        main_axis_position: f64,
1815        cross_axis_position: f64,
1816    ) -> bool {
1817        (self.vtable.hit_test)(
1818            app,
1819            self.id,
1820            result,
1821            main_axis_position,
1822            cross_axis_position,
1823        )
1824    }
1825
1826    /// See [`RenderSliver::handle_event`].
1827    pub fn handle_event(self, app: &mut App, event: &PointerEvent, entry: &SliverHitTestEntry) {
1828        (self.vtable.handle_event)(app, self.id, event, entry)
1829    }
1830
1831    /// See [`RenderSliver::center_offset_adjustment`].
1832    pub fn center_offset_adjustment(self, app: &App) -> f64 {
1833        (self.vtable.center_offset_adjustment)(app, self.id)
1834    }
1835
1836    /// See [`RenderSliver::child_scroll_offset`].
1837    pub fn child_scroll_offset(self, app: &App, child: AnyRenderObject) -> Option<f64> {
1838        (self.vtable.child_scroll_offset)(app, self.id, child)
1839    }
1840
1841    /// See [`RenderSliver::child_main_axis_position`].
1842    pub fn child_main_axis_position(self, app: &App, child: AnyRenderObject) -> f64 {
1843        (self.vtable.child_main_axis_position)(app, self.id, child)
1844    }
1845
1846    /// The amount of space this sliver occupies.
1847    ///
1848    /// # Panics
1849    ///
1850    /// If this sliver has not been laid out.
1851    pub fn geometry(self, app: &App) -> SliverGeometry {
1852        self.sliver_data(app)
1853            .geometry
1854            .unwrap_or_else(|| panic!("RenderSliver was not laid out: {self:?}"))
1855    }
1856
1857    /// Sets the geometry of this sliver.
1858    pub fn set_geometry(self, app: &mut App, geometry: SliverGeometry) {
1859        self.sliver_data_mut(app).geometry = Some(geometry);
1860    }
1861}
1862
1863impl crate::object::ErasedRenderObject for AnyRenderSliver {
1864    fn as_object(self) -> AnyRenderObject {
1865        AnyRenderSliver::as_object(self)
1866    }
1867
1868    fn from_object(object: AnyRenderObject) -> AnyRenderSliver {
1869        object
1870            .as_sliver()
1871            .expect("the render object is not a RenderSliver")
1872    }
1873}
1874
1875impl From<AnyRenderSliver> for AnyRenderObject {
1876    fn from(sliver: AnyRenderSliver) -> AnyRenderObject {
1877        sliver.as_object()
1878    }
1879}
1880
1881/// Whether the sliver's growth direction and axis direction agree, so that a box child is
1882/// positioned from the sliver's leading edge.
1883///
1884/// Flutter's private `RenderSliverHelpers._getRightWayUp`.
1885fn get_right_way_up(constraints: SliverConstraints) -> bool {
1886    let reversed = axis_direction_is_reversed(constraints.axis_direction);
1887    match constraints.growth_direction {
1888        GrowthDirection::Forward => !reversed,
1889        GrowthDirection::Reverse => reversed,
1890    }
1891}
1892
1893/// Mixin for [`RenderSliver`] subclasses that provides some utility functions.
1894pub trait RenderSliverHelpers: RenderSliver {
1895    /// Utility function for [`RenderSliver::hit_test_children`] for use when the children are
1896    /// [`crate::RenderBox`] widgets.
1897    ///
1898    /// This function takes care of converting the position from the sliver coordinate system to
1899    /// the Cartesian coordinate system used by the box protocol.
1900    ///
1901    /// This function relies on [`RenderSliver::child_main_axis_position`] to determine the
1902    /// position of the child in question.
1903    ///
1904    /// Calling this for a child that is not visible is not valid.
1905    fn hit_test_box_child(
1906        self: RenderHandle<Self>,
1907        app: &mut App,
1908        result: &mut BoxHitTestResult<'_>,
1909        child: AnyRenderBox,
1910        main_axis_position: f64,
1911        cross_axis_position: f64,
1912    ) -> bool {
1913        let constraints = self.constraints(app);
1914        let right_way_up = get_right_way_up(constraints);
1915        let mut delta = self.child_main_axis_position(app, child.as_object());
1916        let cross_axis_delta = self.child_cross_axis_position(app, child.as_object());
1917        let mut absolute_position = main_axis_position - delta;
1918        let absolute_cross_axis_position = cross_axis_position - cross_axis_delta;
1919        let size = child.size(app);
1920        let paint_extent = self.geometry(app).paint_extent;
1921        let (paint_offset, transformed_position) = match constraints.axis() {
1922            Axis::Horizontal => {
1923                if !right_way_up {
1924                    absolute_position = size.width() - absolute_position;
1925                    delta = paint_extent - size.width() - delta;
1926                }
1927                (
1928                    Offset::new(delta, cross_axis_delta),
1929                    Offset::new(absolute_position, absolute_cross_axis_position),
1930                )
1931            }
1932            Axis::Vertical => {
1933                if !right_way_up {
1934                    absolute_position = size.height() - absolute_position;
1935                    delta = paint_extent - size.height() - delta;
1936                }
1937                (
1938                    Offset::new(cross_axis_delta, delta),
1939                    Offset::new(absolute_cross_axis_position, absolute_position),
1940                )
1941            }
1942        };
1943        result.add_with_out_of_band_position(Some(paint_offset), None, None, |result| {
1944            child.hit_test(app, result, transformed_position)
1945        })
1946    }
1947
1948    /// Utility function for [`RenderObject::apply_paint_transform`] for use when the children
1949    /// are [`crate::RenderBox`] widgets.
1950    ///
1951    /// This function turns the value returned by [`RenderSliver::child_main_axis_position`] and
1952    /// [`RenderSliver::child_cross_axis_position`] for the child in question into a translation
1953    /// that it then applies to the given matrix.
1954    ///
1955    /// Calling this for a child that is not visible is not valid.
1956    fn apply_paint_transform_for_box_child(
1957        self: RenderHandle<Self>,
1958        app: &App,
1959        child: AnyRenderBox,
1960        transform: &mut Matrix4,
1961    ) {
1962        let constraints = self.constraints(app);
1963        let right_way_up = get_right_way_up(constraints);
1964        let mut delta = self.child_main_axis_position(app, child.as_object());
1965        let cross_axis_delta = self.child_cross_axis_position(app, child.as_object());
1966        let size = child.size(app);
1967        let paint_extent = self.geometry(app).paint_extent;
1968        match constraints.axis() {
1969            Axis::Horizontal => {
1970                if !right_way_up {
1971                    delta = paint_extent - size.width() - delta;
1972                }
1973                translate(transform, delta, cross_axis_delta);
1974            }
1975            Axis::Vertical => {
1976                if !right_way_up {
1977                    delta = paint_extent - size.height() - delta;
1978                }
1979                translate(transform, cross_axis_delta, delta);
1980            }
1981        }
1982    }
1983}
1984
1985// ADAPTER FOR RENDER BOXES INSIDE SLIVERS
1986// Transitions from the RenderSliver world to the RenderBox world.
1987
1988/// A [`RenderSliver`] that contains a single [`crate::RenderBox`].
1989///
1990/// See also:
1991///
1992///  * [`RenderSliverToBoxAdapter`], which implements this trait to size the child according to
1993///    its preferred size.
1994pub trait RenderSliverSingleBoxAdapter:
1995    RenderSliver + RenderObjectWithChildMixin<ChildType = AnyRenderBox> + RenderSliverHelpers
1996{
1997    /// The body of Flutter's `setupParentData` override; call it from
1998    /// [`RenderObject::setup_parent_data`].
1999    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
2000        if !child.parent_data_is::<SliverPhysicalParentData>(app) {
2001            child.set_parent_data(app, SliverPhysicalParentData::new());
2002        }
2003    }
2004
2005    /// Sets the [`SliverPhysicalParentData::paint_offset`] for the given child according to the
2006    /// [`SliverConstraints::axis_direction`] and [`SliverConstraints::growth_direction`] and
2007    /// the given geometry.
2008    fn set_child_parent_data(
2009        self: RenderHandle<Self>,
2010        app: &mut App,
2011        child: AnyRenderObject,
2012        constraints: SliverConstraints,
2013        geometry: SliverGeometry,
2014    ) {
2015        RenderSliverSingleBoxAdapterBase::set_child_parent_data(
2016            self,
2017            app,
2018            child,
2019            constraints,
2020            geometry,
2021        )
2022    }
2023
2024    /// The body of Flutter's `hitTestChildren` override.
2025    fn hit_test_children(
2026        self: RenderHandle<Self>,
2027        app: &mut App,
2028        result: &mut SliverHitTestResult<'_>,
2029        main_axis_position: f64,
2030        cross_axis_position: f64,
2031    ) -> bool {
2032        debug_assert!(self.geometry(app).hit_test_extent > 0.0);
2033        let Some(child) = self.child(app) else {
2034            return false;
2035        };
2036        self.hit_test_box_child(
2037            app,
2038            &mut BoxHitTestResult::wrap(result),
2039            child,
2040            main_axis_position,
2041            cross_axis_position,
2042        )
2043    }
2044
2045    /// The body of Flutter's `childMainAxisPosition` override.
2046    fn child_main_axis_position(
2047        self: RenderHandle<Self>,
2048        app: &App,
2049        child: AnyRenderObject,
2050    ) -> f64 {
2051        debug_assert_eq!(Some(child), self.child(app).map(AnyRenderBox::as_object));
2052        -self.constraints(app).scroll_offset
2053    }
2054
2055    /// The body of Flutter's `applyPaintTransform` override.
2056    fn apply_paint_transform(
2057        self: RenderHandle<Self>,
2058        app: &App,
2059        child: AnyRenderObject,
2060        transform: &mut Matrix4,
2061    ) {
2062        debug_assert_eq!(Some(child), self.child(app).map(AnyRenderBox::as_object));
2063        child
2064            .parent_data_of::<SliverPhysicalParentData>(app)
2065            .apply_paint_transform(transform);
2066    }
2067
2068    /// The body of Flutter's `paint` override.
2069    fn paint(
2070        self: RenderHandle<Self>,
2071        app: &mut App,
2072        context: &mut PaintingContext,
2073        offset: Offset,
2074    ) {
2075        let Some(child) = self.child(app) else {
2076            return;
2077        };
2078        if !self.geometry(app).visible {
2079            return;
2080        }
2081        let paint_offset = child
2082            .as_object()
2083            .parent_data_of::<SliverPhysicalParentData>(app)
2084            .paint_offset;
2085        context.paint_child(app, child.as_object(), offset + paint_offset);
2086    }
2087}
2088
2089/// Flutter's `RenderSliverSingleBoxAdapter` bodies that an override calls through `super`.
2090///
2091/// Blanket-implemented for every single-box adapter. It holds Flutter's
2092/// `RenderSliverSingleBoxAdapter.setChildParentData` body, and the default of
2093/// [`RenderSliverSingleBoxAdapter::set_child_parent_data`] forwards here, so a leaf that
2094/// overrides it can still call `super`; inlining the body back into the default breaks that.
2095pub trait RenderSliverSingleBoxAdapterBase: RenderSliverSingleBoxAdapter {
2096    /// Flutter's `RenderSliverSingleBoxAdapter.setChildParentData`; an override calls it where
2097    /// Dart writes `super.setChildParentData(child, constraints, geometry)`.
2098    fn set_child_parent_data(
2099        self: RenderHandle<Self>,
2100        app: &mut App,
2101        child: AnyRenderObject,
2102        constraints: SliverConstraints,
2103        geometry: SliverGeometry,
2104    ) {
2105        let paint_offset = match apply_growth_direction_to_axis_direction(
2106            constraints.axis_direction,
2107            constraints.growth_direction,
2108        ) {
2109            AxisDirection::Up => Offset::new(
2110                0.0,
2111                geometry.paint_extent + constraints.scroll_offset - geometry.scroll_extent,
2112            ),
2113            AxisDirection::Left => Offset::new(
2114                geometry.paint_extent + constraints.scroll_offset - geometry.scroll_extent,
2115                0.0,
2116            ),
2117            AxisDirection::Right => Offset::new(-constraints.scroll_offset, 0.0),
2118            AxisDirection::Down => Offset::new(0.0, -constraints.scroll_offset),
2119        };
2120        child
2121            .parent_data_of_mut::<SliverPhysicalParentData>(app)
2122            .paint_offset = paint_offset;
2123    }
2124}
2125
2126impl<T: RenderSliverSingleBoxAdapter> RenderSliverSingleBoxAdapterBase for T {}
2127
2128/// A [`RenderSliver`] that contains a single [`crate::RenderBox`].
2129///
2130/// The child will not be laid out if it is not visible. It is sized according to the child's
2131/// preferences in the main axis, and with a tight constraint forcing it to the dimensions of
2132/// the viewport in the cross axis.
2133///
2134/// See also:
2135///
2136///  * [`crate::RenderViewport`], which allows [`RenderSliver`] objects to be placed inside a
2137///    [`crate::RenderBox`] (the opposite of this class).
2138pub struct RenderSliverToBoxAdapter {
2139    render_object: crate::object::RenderObjectData,
2140    render_sliver: RenderSliverData,
2141    child: RenderObjectWithChildData<AnyRenderBox>,
2142}
2143
2144impl RenderSliverToBoxAdapter {
2145    /// Creates a [`RenderSliver`] that wraps a [`crate::RenderBox`].
2146    pub fn new(
2147        app: &mut App,
2148        child: Option<AnyRenderBox>,
2149    ) -> RenderHandle<RenderSliverToBoxAdapter> {
2150        let this = RenderHandle::new_sliver(
2151            app,
2152            RenderSliverToBoxAdapter {
2153                render_object: crate::object::RenderObjectData::new(),
2154                render_sliver: RenderSliverData::new(),
2155                child: RenderObjectWithChildData::new(),
2156            },
2157        );
2158        this.set_child(app, child);
2159        this
2160    }
2161}
2162
2163impl RenderObjectWithChildMixin for RenderSliverToBoxAdapter {
2164    type ChildType = AnyRenderBox;
2165
2166    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
2167        &self.get(app).child
2168    }
2169
2170    fn child_data_mut(
2171        self: RenderHandle<Self>,
2172        app: &mut App,
2173    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
2174        &mut self.get_mut(app).child
2175    }
2176}
2177
2178impl RenderSliverHelpers for RenderSliverToBoxAdapter {}
2179
2180impl RenderSliverSingleBoxAdapter for RenderSliverToBoxAdapter {}
2181
2182impl RenderObject for RenderSliverToBoxAdapter {
2183    crate::render_object_accessors!();
2184
2185    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
2186        RenderSliverSingleBoxAdapter::setup_parent_data(self, app, child)
2187    }
2188
2189    fn visit_children(
2190        self: RenderHandle<Self>,
2191        app: &App,
2192        visitor: &mut dyn FnMut(AnyRenderObject),
2193    ) {
2194        if let Some(child) = self.child(app) {
2195            visitor(child.as_object());
2196        }
2197    }
2198
2199    fn apply_paint_transform(
2200        self: RenderHandle<Self>,
2201        app: &App,
2202        child: AnyRenderObject,
2203        transform: &mut Matrix4,
2204    ) {
2205        RenderSliverSingleBoxAdapter::apply_paint_transform(self, app, child, transform)
2206    }
2207
2208    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
2209        let Some(child) = self.child(app) else {
2210            self.set_geometry(app, SliverGeometry::ZERO);
2211            return;
2212        };
2213        let constraints = self.constraints(app);
2214        child.layout(
2215            app,
2216            constraints.as_box_constraints(0.0, f64::INFINITY, None),
2217            true,
2218        );
2219        let child_extent = match constraints.axis() {
2220            Axis::Horizontal => child.size(app).width(),
2221            Axis::Vertical => child.size(app).height(),
2222        };
2223        let painted_child_size = calculate_paint_offset(constraints, 0.0, child_extent);
2224        let cache_extent = calculate_cache_offset(constraints, 0.0, child_extent);
2225
2226        debug_assert!(painted_child_size.is_finite());
2227        debug_assert!(painted_child_size >= 0.0);
2228        let geometry = SliverGeometry::builder()
2229            .scroll_extent(child_extent)
2230            .paint_extent(painted_child_size)
2231            .cache_extent(cache_extent)
2232            .max_paint_extent(child_extent)
2233            .hit_test_extent(painted_child_size)
2234            .has_visual_overflow(
2235                child_extent > constraints.remaining_paint_extent
2236                    || constraints.scroll_offset > 0.0,
2237            )
2238            .build();
2239        self.set_geometry(app, geometry);
2240        RenderSliverSingleBoxAdapter::set_child_parent_data(
2241            self,
2242            app,
2243            child.as_object(),
2244            constraints,
2245            geometry,
2246        );
2247    }
2248
2249    fn paint(
2250        self: RenderHandle<Self>,
2251        app: &mut App,
2252        context: &mut PaintingContext,
2253        offset: Offset,
2254    ) {
2255        RenderSliverSingleBoxAdapter::paint(self, app, context, offset)
2256    }
2257}
2258
2259impl RenderSliver for RenderSliverToBoxAdapter {
2260    render_sliver_accessors!();
2261
2262    fn hit_test_children(
2263        self: RenderHandle<Self>,
2264        app: &mut App,
2265        result: &mut SliverHitTestResult<'_>,
2266        main_axis_position: f64,
2267        cross_axis_position: f64,
2268    ) -> bool {
2269        RenderSliverSingleBoxAdapter::hit_test_children(
2270            self,
2271            app,
2272            result,
2273            main_axis_position,
2274            cross_axis_position,
2275        )
2276    }
2277
2278    fn child_main_axis_position(
2279        self: RenderHandle<Self>,
2280        app: &App,
2281        child: AnyRenderObject,
2282    ) -> f64 {
2283        RenderSliverSingleBoxAdapter::child_main_axis_position(self, app, child)
2284    }
2285}
2286
2287#[cfg(test)]
2288mod tests {
2289    use waft_foundation::AppCell;
2290    use waft_gestures::HitTestResult;
2291
2292    use super::*;
2293    use crate::box_::{RenderBox, RenderBoxData};
2294    use crate::proxy_box::RenderConstrainedBox;
2295
2296    struct TestSliver {
2297        render_object: crate::object::RenderObjectData,
2298        render_sliver: RenderSliverData,
2299    }
2300
2301    impl RenderObject for TestSliver {
2302        crate::render_object_accessors!();
2303
2304        fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
2305            let constraints = self.constraints(app);
2306            let extent = constraints.remaining_paint_extent.min(20.0);
2307            self.set_geometry(
2308                app,
2309                SliverGeometry::builder()
2310                    .scroll_extent(20.0)
2311                    .paint_extent(extent)
2312                    .max_paint_extent(20.0)
2313                    .build(),
2314            );
2315        }
2316    }
2317
2318    impl RenderSliver for TestSliver {
2319        render_sliver_accessors!();
2320    }
2321
2322    fn vertical_constraints(remaining_paint: f64) -> SliverConstraints {
2323        SliverConstraints::new(
2324            AxisDirection::Down,
2325            GrowthDirection::Forward,
2326            ScrollDirection::Idle,
2327            0.0,
2328            0.0,
2329            0.0,
2330            remaining_paint,
2331            100.0,
2332            AxisDirection::Right,
2333            400.0,
2334            remaining_paint,
2335            0.0,
2336        )
2337    }
2338
2339    /// `slivers_test.dart`: a geometry's `toString` is its single-line properties, from
2340    /// `scrollExtent` through `cacheExtent`, with a hidden sliver's `visible` flag reading
2341    /// `hidden`.
2342    #[test]
2343    fn sliver_geometry_prints_its_properties_like_dart() {
2344        let visible = SliverGeometry::builder()
2345            .scroll_extent(400.0)
2346            .paint_extent(400.0)
2347            .max_paint_extent(400.0)
2348            .build();
2349        assert_eq!(
2350            format!("{visible}"),
2351            "SliverGeometry(scrollExtent: 400.0, paintExtent: 400.0, maxPaintExtent: 400.0, cacheExtent: 400.0)"
2352        );
2353
2354        let partly_visible = SliverGeometry::builder()
2355            .scroll_extent(400.0)
2356            .paint_extent(200.0)
2357            .max_paint_extent(400.0)
2358            .has_visual_overflow(true)
2359            .cache_extent(400.0)
2360            .build();
2361        assert_eq!(
2362            format!("{partly_visible}"),
2363            "SliverGeometry(scrollExtent: 400.0, paintExtent: 200.0, maxPaintExtent: 400.0, hasVisualOverflow: true, cacheExtent: 400.0)"
2364        );
2365
2366        let hidden = SliverGeometry::builder()
2367            .scroll_extent(400.0)
2368            .paint_extent(0.0)
2369            .max_paint_extent(400.0)
2370            .has_visual_overflow(true)
2371            .build();
2372        assert_eq!(
2373            format!("{hidden}"),
2374            "SliverGeometry(scrollExtent: 400.0, hidden, maxPaintExtent: 400.0, hasVisualOverflow: true)"
2375        );
2376    }
2377
2378    #[test]
2379    fn sliver_layout_sets_geometry() {
2380        let cell = AppCell::new();
2381        let mut app = cell.borrow_mut();
2382        let sliver = RenderHandle::new_sliver(
2383            &mut app,
2384            TestSliver {
2385                render_object: crate::object::RenderObjectData::new(),
2386                render_sliver: RenderSliverData::new(),
2387            },
2388        );
2389        sliver.layout(&mut app, vertical_constraints(50.0), false);
2390        let geometry = sliver.geometry(&app);
2391        assert_eq!(geometry.scroll_extent, 20.0);
2392        assert_eq!(geometry.paint_extent, 20.0);
2393        assert!(geometry.visible);
2394    }
2395
2396    /// A box that fills the constraints it is given and accepts hits, so that a hit test walks
2397    /// all the way through the sliver adapter.
2398    struct HitTestableBox {
2399        render_object: crate::object::RenderObjectData,
2400        render_box: RenderBoxData,
2401    }
2402
2403    impl RenderObject for HitTestableBox {
2404        crate::render_object_accessors!();
2405
2406        fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
2407            let size = self.constraints(app).constrain(Size::new(60.0, 60.0));
2408            self.set_size(app, size);
2409        }
2410    }
2411
2412    impl RenderBox for HitTestableBox {
2413        crate::render_box_accessors!();
2414
2415        fn hit_test_self(self: RenderHandle<Self>, _app: &App, _position: Offset) -> bool {
2416            let _ = self;
2417            true
2418        }
2419    }
2420
2421    fn hit_testable_box(app: &mut App) -> AnyRenderBox {
2422        RenderHandle::new_box(
2423            app,
2424            HitTestableBox {
2425                render_object: crate::object::RenderObjectData::new(),
2426                render_box: RenderBoxData::new(),
2427            },
2428        )
2429        .as_box()
2430    }
2431
2432    fn adapter_constraints(scroll_offset: f64, remaining_paint: f64) -> SliverConstraints {
2433        SliverConstraints::new(
2434            AxisDirection::Down,
2435            GrowthDirection::Forward,
2436            ScrollDirection::Idle,
2437            scroll_offset,
2438            0.0,
2439            0.0,
2440            remaining_paint,
2441            100.0,
2442            AxisDirection::Right,
2443            remaining_paint,
2444            remaining_paint,
2445            0.0,
2446        )
2447    }
2448
2449    /// `sliver_test.dart`: a `RenderSliverToBoxAdapter` sizes itself to its box child in the main
2450    /// axis and reports the visible portion as its paint extent.
2451    #[test]
2452    fn a_box_adapter_reports_its_child_extent() {
2453        let cell = AppCell::new();
2454        let mut app = cell.borrow_mut();
2455        let child =
2456            RenderConstrainedBox::new(&mut app, BoxConstraints::tight_for(None, Some(60.0)), None);
2457        let adapter = RenderSliverToBoxAdapter::new(&mut app, Some(child.as_box()));
2458
2459        adapter.layout(&mut app, adapter_constraints(0.0, 400.0), true);
2460
2461        let geometry = adapter.geometry(&app);
2462        assert_eq!(geometry.scroll_extent, 60.0);
2463        assert_eq!(geometry.paint_extent, 60.0);
2464        assert_eq!(geometry.max_paint_extent, 60.0);
2465        assert!(!geometry.has_visual_overflow);
2466        // The cross axis is tight to the sliver's cross axis extent.
2467        assert_eq!(child.size(&app), Size::new(100.0, 60.0));
2468        assert_eq!(
2469            child
2470                .as_box()
2471                .as_object()
2472                .parent_data_of::<SliverPhysicalParentData>(&app)
2473                .paint_offset,
2474            Offset::ZERO
2475        );
2476    }
2477
2478    /// A scrolled adapter moves its child up by the scroll offset and shrinks its paint extent.
2479    #[test]
2480    fn a_scrolled_box_adapter_offsets_its_child() {
2481        let cell = AppCell::new();
2482        let mut app = cell.borrow_mut();
2483        let child =
2484            RenderConstrainedBox::new(&mut app, BoxConstraints::tight_for(None, Some(60.0)), None);
2485        let adapter = RenderSliverToBoxAdapter::new(&mut app, Some(child.as_box()));
2486
2487        adapter.layout(&mut app, adapter_constraints(20.0, 400.0), true);
2488
2489        let geometry = adapter.geometry(&app);
2490        assert_eq!(geometry.scroll_extent, 60.0);
2491        assert_eq!(geometry.paint_extent, 40.0);
2492        assert!(geometry.has_visual_overflow);
2493        assert_eq!(
2494            child
2495                .as_box()
2496                .as_object()
2497                .parent_data_of::<SliverPhysicalParentData>(&app)
2498                .paint_offset,
2499            Offset::new(0.0, -20.0)
2500        );
2501        assert_eq!(
2502            RenderSliver::child_main_axis_position(adapter, &app, child.as_object()),
2503            -20.0
2504        );
2505    }
2506
2507    /// An empty adapter reports zero geometry.
2508    #[test]
2509    fn a_childless_box_adapter_is_zero() {
2510        let cell = AppCell::new();
2511        let mut app = cell.borrow_mut();
2512        let adapter = RenderSliverToBoxAdapter::new(&mut app, None);
2513        adapter.layout(&mut app, adapter_constraints(0.0, 400.0), true);
2514        assert!(adapter.geometry(&app).is_zero());
2515    }
2516
2517    /// A hit inside the visible part of the child lands on both the child and the sliver.
2518    #[test]
2519    fn a_box_adapter_hit_tests_its_child() {
2520        let cell = AppCell::new();
2521        let mut app = cell.borrow_mut();
2522        let child = hit_testable_box(&mut app);
2523        let adapter = RenderSliverToBoxAdapter::new(&mut app, Some(child));
2524        adapter.layout(&mut app, adapter_constraints(0.0, 400.0), true);
2525
2526        let mut result = HitTestResult::new();
2527        let hit = adapter.hit_test(
2528            &mut app,
2529            &mut SliverHitTestResult::wrap(&mut result),
2530            30.0,
2531            50.0,
2532        );
2533
2534        assert!(hit);
2535        assert_eq!(result.path().len(), 2);
2536    }
2537
2538    /// `calculate_paint_offset` clamps the requested region to the visible window.
2539    #[test]
2540    fn paint_and_cache_offsets_clamp_to_the_window() {
2541        let constraints = adapter_constraints(20.0, 50.0);
2542        assert_eq!(calculate_paint_offset(constraints, 0.0, 100.0), 50.0);
2543        assert_eq!(calculate_paint_offset(constraints, 0.0, 30.0), 10.0);
2544        assert_eq!(calculate_paint_offset(constraints, 0.0, 10.0), 0.0);
2545        assert_eq!(calculate_cache_offset(constraints, 0.0, 100.0), 50.0);
2546    }
2547
2548    /// `SliverGeometry.debugAssertIsValid` accepts a consistent geometry.
2549    #[test]
2550    fn a_consistent_geometry_is_valid() {
2551        let geometry = SliverGeometry::builder()
2552            .scroll_extent(100.0)
2553            .paint_extent(40.0)
2554            .max_paint_extent(100.0)
2555            .build();
2556        assert!(geometry.debug_assert_is_valid());
2557        assert!(!geometry.is_zero());
2558        assert!(SliverGeometry::ZERO.is_zero());
2559    }
2560
2561    #[test]
2562    fn extents_left_out_follow_the_ones_given_in_any_order() {
2563        let geometry = SliverGeometry::builder()
2564            .layout_extent(10.0)
2565            .hit_test_extent(20.0)
2566            .paint_extent(40.0)
2567            .build();
2568        assert_eq!(geometry.layout_extent, 10.0);
2569        assert_eq!(geometry.hit_test_extent, 20.0);
2570        assert_eq!(geometry.cache_extent, 10.0);
2571        assert!(geometry.visible);
2572        let geometry = SliverGeometry::builder()
2573            .cache_extent(5.0)
2574            .layout_extent(10.0)
2575            .paint_extent(40.0)
2576            .build();
2577        assert_eq!(geometry.cache_extent, 5.0);
2578    }
2579
2580    #[test]
2581    fn a_copy_keeps_the_extents_it_was_made_with() {
2582        let copy = SliverGeometry::builder()
2583            .paint_extent(40.0)
2584            .layout_extent(10.0)
2585            .build()
2586            .copy_with()
2587            .paint_extent(0.0)
2588            .build();
2589        assert_eq!(copy.layout_extent, 10.0);
2590        assert_eq!(copy.cache_extent, 10.0);
2591        assert!(copy.visible);
2592    }
2593}