Skip to main content

waft_rendering/
viewport.rs

1//! Flutter counterpart: `rendering/viewport.dart`.
2//!
3//! Semantics and debug paint wait; see `PORTING.md`.
4
5use std::any::{Any, TypeId};
6use std::fmt::{self, Debug};
7use std::rc::Rc;
8use std::time::Duration;
9
10use waft_animation::Curve;
11use waft_embedder::{Clip, Matrix4, Offset, Rect, Size, clamp_double};
12use waft_foundation::{
13    App, DiagnosticPropertiesBuilder, DiagnosticsNode, DiagnosticsProperty, DoubleProperty,
14    EnumProperty, Handle, HandleId, Listener,
15};
16use waft_painting::{Axis, AxisDirection, axis_direction_to_axis, transform_rect};
17
18use crate::box_::{BoxConstraints, BoxHitTestResult, RenderBox, RenderBoxData};
19use crate::debug::debug_check_has_bounded_axis;
20use crate::layer::{ClipRectLayer, LayerHandle};
21use crate::object::{
22    AnyRenderObject, ContainerRenderObjectData, ContainerRenderObjectMixin, RenderHandle,
23    RenderObject, RenderObjectData, debug_checking_intrinsics, resolve, translate,
24};
25use crate::painting_context::PaintingContext;
26use crate::pipeline_owner::PipelineOwner;
27use crate::sliver::{
28    AnyRenderSliver, GrowthDirection, SliverConstraints, SliverGeometry, SliverHitTestResult,
29    SliverLogicalContainerParentData, SliverPhysicalContainerParentData,
30    apply_growth_direction_to_axis_direction, apply_growth_direction_to_scroll_direction,
31};
32use crate::viewport_offset::{AnyViewportOffset, ViewportOffsetRef};
33
34/// The unit of measurement for a viewport's cache extent.
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
36pub enum CacheExtentStyle {
37    /// Treat the cache extent as logical pixels.
38    Pixel,
39
40    /// Treat the cache extent as a multiplier of the main axis extent.
41    Viewport,
42}
43
44/// The amount of additional content to display and lay out around the viewport.
45///
46/// The cache area is used to lay out slivers before they are visible on screen. Items that fall
47/// in this cache area are laid out even though they are not visible on screen. This allows the
48/// viewport to render them ahead of time, enabling a smoother scrolling experience.
49///
50/// This type encapsulates both the value and the style of the cache extent. It allows the cache
51/// extent to be defined either as a fixed number of logical pixels using
52/// [`ScrollCacheExtent::Pixels`] or as a multiplier of the viewport's main axis extent using
53/// [`ScrollCacheExtent::Viewport`].
54#[derive(Debug, Clone, Copy, PartialEq)]
55pub enum ScrollCacheExtent {
56    /// A cache extent in logical pixels.
57    Pixels(f64),
58
59    /// A cache extent as a multiplier of the viewport's main axis extent.
60    ///
61    /// The main axis extent is the size of the viewport in its main axis. For example, for a
62    /// vertically scrolling list, the main axis extent is the height of the viewport. If the
63    /// viewport is 600 logical pixels tall, then `ScrollCacheExtent::Viewport(2.0)` results in a
64    /// cache extent of 1200 logical pixels.
65    Viewport(f64),
66}
67
68/// Dart's `ScrollCacheExtent.toString`, which a scroll view's dump prints.
69impl std::fmt::Display for ScrollCacheExtent {
70    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71        match self {
72            ScrollCacheExtent::Pixels(pixels) => write!(f, "ScrollCacheExtent.pixels({pixels})"),
73            ScrollCacheExtent::Viewport(viewports) => {
74                write!(f, "ScrollCacheExtent.viewport({viewports})")
75            }
76        }
77    }
78}
79
80impl ScrollCacheExtent {
81    /// Returns the cache extent in logical pixels for a given `main_axis_extent`.
82    fn calculate_cache_offset(self, main_axis_extent: f64) -> f64 {
83        match self {
84            ScrollCacheExtent::Pixels(pixels) => pixels,
85            ScrollCacheExtent::Viewport(value) => value * main_axis_extent,
86        }
87    }
88
89    /// Returns the style of the cache extent.
90    pub fn style(self) -> CacheExtentStyle {
91        match self {
92            ScrollCacheExtent::Pixels(_) => CacheExtentStyle::Pixel,
93            ScrollCacheExtent::Viewport(_) => CacheExtentStyle::Viewport,
94        }
95    }
96
97    /// Returns the raw value of the cache extent.
98    ///
99    /// If [`style`](Self::style) is [`CacheExtentStyle::Pixel`], this is the number of pixels to
100    /// cache. If it is [`CacheExtentStyle::Viewport`], this is the multiplier of the viewport's
101    /// main axis extent to cache.
102    pub fn value(self) -> f64 {
103        match self {
104            ScrollCacheExtent::Pixels(pixels) => pixels,
105            ScrollCacheExtent::Viewport(value) => value,
106        }
107    }
108}
109
110/// Specifies an order in which to paint the slivers of a viewport.
111///
112/// Whichever order the slivers are painted in, they will be hit-tested in the opposite order.
113///
114/// This can also be thought of as an ordering in the z-direction: whichever sliver is painted
115/// last (and hit-tested first) is on top, because it will paint over other slivers if there is
116/// overlap. Similarly, whichever sliver is painted first (and hit-tested last) is on the bottom.
117#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
118pub enum SliverPaintOrder {
119    /// The first sliver paints on top, and the last sliver on bottom.
120    ///
121    /// The slivers are painted in the reverse order of the viewport's children, and hit-tested
122    /// in the same order as the viewport's children.
123    ///
124    /// This is the default order.
125    #[default]
126    FirstIsTop,
127
128    /// The last sliver paints on top, and the first sliver on bottom.
129    ///
130    /// The slivers are painted in the same order as the viewport's children, and hit-tested in
131    /// the reverse order.
132    LastIsTop,
133}
134
135/// An interface for render objects that are bigger on the inside.
136///
137/// Some render objects, such as [`RenderViewport`], present a portion of their content, which
138/// can be controlled by a [`crate::ViewportOffset`]. This interface lets the framework recognize
139/// such render objects and interact with them without having specific knowledge of all the
140/// various types of viewports.
141///
142/// Answer [`RenderObject::interface`] for [`AnyRenderAbstractViewport`] with
143/// [`as_abstract_viewport`](Self::as_abstract_viewport) so that
144/// [`AnyRenderAbstractViewport::maybe_of`] can find this render object.
145pub trait RenderAbstractViewport: RenderObject {
146    /// Returns the offset that would be needed to reveal the `target` render object.
147    ///
148    /// This is used by [`show_in_viewport`], which is itself used by
149    /// [`RenderObject::show_on_screen`] for [`RenderViewportBase`].
150    ///
151    /// The optional `rect` parameter describes which area of that `target` object should be
152    /// revealed in the viewport. If `rect` is `None`, the entire `target` (as defined by its
153    /// paint bounds) will be revealed. If `rect` is provided it has to be given in the
154    /// coordinate system of the `target` object.
155    ///
156    /// The `alignment` argument describes where the target should be positioned after applying
157    /// the returned offset. If `alignment` is 0.0, the child must be positioned as close to the
158    /// leading edge of the viewport as possible. If `alignment` is 1.0, the child must be
159    /// positioned as close to the trailing edge of the viewport as possible. If `alignment` is
160    /// 0.5, the child must be positioned as close to the center of the viewport as possible.
161    ///
162    /// The `target` might not be a direct child of this viewport but it must be a descendant of
163    /// the viewport. Other viewports in between this viewport and the `target` will not be
164    /// adjusted.
165    ///
166    /// This method assumes that the content of the viewport moves linearly, i.e. when the offset
167    /// of the viewport is changed by x then `target` also moves by x within the viewport.
168    ///
169    /// The optional [`Axis`] determines which of two axes to compute an offset for.
170    /// One-dimensional viewports ignore it, since there is only one [`Axis`].
171    fn get_offset_to_reveal(
172        self: RenderHandle<Self>,
173        app: &App,
174        target: AnyRenderObject,
175        alignment: f64,
176        rect: Option<Rect>,
177        axis: Option<Axis>,
178    ) -> RevealedOffset;
179
180    /// The type-erased `RenderAbstractViewport` handle. Free: the vtable is a `const`, and the
181    /// id is copied.
182    fn as_abstract_viewport(self: RenderHandle<Self>) -> AnyRenderAbstractViewport {
183        AnyRenderAbstractViewport {
184            id: self.id(),
185            vtable: const { &RenderAbstractViewportVTable::of::<Self>() },
186        }
187    }
188}
189
190/// The vtable of an erased [`AnyRenderAbstractViewport`].
191struct RenderAbstractViewportVTable {
192    get_offset_to_reveal: GetOffsetToRevealFn,
193    as_object: fn(&App, HandleId) -> AnyRenderObject,
194}
195
196/// The dispatch signature of [`RenderAbstractViewport::get_offset_to_reveal`].
197type GetOffsetToRevealFn =
198    fn(&App, HandleId, AnyRenderObject, f64, Option<Rect>, Option<Axis>) -> RevealedOffset;
199
200impl RenderAbstractViewportVTable {
201    const fn of<T: RenderAbstractViewport>() -> RenderAbstractViewportVTable {
202        RenderAbstractViewportVTable {
203            get_offset_to_reveal: |app, id, target, alignment, rect, axis| {
204                T::get_offset_to_reveal(resolve(id), app, target, alignment, rect, axis)
205            },
206            as_object: |app, id| resolve::<T>(id).as_render_object(app),
207        }
208    }
209}
210
211/// Erased [`RenderAbstractViewport`]: what a field or parameter Dart types as
212/// `RenderAbstractViewport` becomes.
213#[derive(Clone, Copy)]
214pub struct AnyRenderAbstractViewport {
215    id: HandleId,
216    vtable: &'static RenderAbstractViewportVTable,
217}
218
219impl AnyRenderAbstractViewport {
220    /// The default value for the cache extent of a viewport.
221    ///
222    /// This default assumes [`CacheExtentStyle::Pixel`].
223    pub const DEFAULT_CACHE_EXTENT: f64 = 250.0;
224
225    /// Returns the viewport that most tightly encloses the given render object.
226    ///
227    /// If the object does not have a viewport as an ancestor, this returns `None`.
228    ///
229    /// Dart's `RenderAbstractViewport.maybeOf`.
230    pub fn maybe_of(
231        app: &App,
232        object: Option<AnyRenderObject>,
233    ) -> Option<AnyRenderAbstractViewport> {
234        let mut object = object;
235        while let Some(current) = object {
236            if let Some(viewport) = current.interface::<AnyRenderAbstractViewport>() {
237                return Some(viewport);
238            }
239            object = current.parent(app);
240        }
241        None
242    }
243
244    /// Returns the viewport that most tightly encloses the given render object.
245    ///
246    /// Dart's `RenderAbstractViewport.of`.
247    ///
248    /// # Panics
249    ///
250    /// If the object does not have a viewport as an ancestor.
251    pub fn of(app: &App, object: Option<AnyRenderObject>) -> AnyRenderAbstractViewport {
252        AnyRenderAbstractViewport::maybe_of(app, object).unwrap_or_else(|| {
253            panic!(
254                "RenderAbstractViewport::of was called with a render object that was not a \
255                 descendant of a RenderAbstractViewport: {object:?}"
256            )
257        })
258    }
259
260    /// The `RenderObject` view of this viewport.
261    pub fn as_object(self, app: &App) -> AnyRenderObject {
262        (self.vtable.as_object)(app, self.id)
263    }
264
265    /// See [`RenderAbstractViewport::get_offset_to_reveal`].
266    pub fn get_offset_to_reveal(
267        self,
268        app: &App,
269        target: AnyRenderObject,
270        alignment: f64,
271        rect: Option<Rect>,
272        axis: Option<Axis>,
273    ) -> RevealedOffset {
274        (self.vtable.get_offset_to_reveal)(app, self.id, target, alignment, rect, axis)
275    }
276}
277
278impl PartialEq for AnyRenderAbstractViewport {
279    fn eq(&self, other: &AnyRenderAbstractViewport) -> bool {
280        self.id == other.id
281    }
282}
283
284impl Eq for AnyRenderAbstractViewport {}
285
286impl Debug for AnyRenderAbstractViewport {
287    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
288        write!(f, "AnyRenderAbstractViewport({:?})", self.id)
289    }
290}
291
292/// Return value for [`RenderAbstractViewport::get_offset_to_reveal`].
293///
294/// It indicates the [`offset`](Self::offset) required to reveal an element in a viewport and the
295/// [`rect`](Self::rect) position said element would have in the viewport at that offset.
296#[derive(Clone, Copy, Debug)]
297pub struct RevealedOffset {
298    /// Offset for the viewport to reveal a specific element in the viewport.
299    pub offset: f64,
300
301    /// The [`Rect`] in the outer coordinate system of the viewport at which the to-be-revealed
302    /// element would be located if the viewport's offset is set to [`offset`](Self::offset).
303    ///
304    /// A viewport usually has two coordinate systems and works as an adapter between the two:
305    ///
306    /// The inner coordinate system has its origin at the top left corner of the content that
307    /// moves inside the viewport. The origin of this coordinate system usually moves around
308    /// relative to the leading edge of the viewport when the viewport offset changes.
309    ///
310    /// The outer coordinate system has its origin at the top left corner of the visible part of
311    /// the viewport. This origin stays at the same position regardless of the current viewport
312    /// offset.
313    pub rect: Rect,
314}
315
316impl RevealedOffset {
317    /// Instantiates a return value for [`RenderAbstractViewport::get_offset_to_reveal`].
318    pub const fn new(offset: f64, rect: Rect) -> RevealedOffset {
319        RevealedOffset { offset, rect }
320    }
321
322    /// Determines which provided leading or trailing edge of the viewport will be used for
323    /// [`show_in_viewport`], accounting for the size and already visible portion of the render
324    /// object that is being revealed.
325    ///
326    /// If the target render object is already fully visible, this returns `None`.
327    pub fn clamp_offset(
328        leading_edge_offset: RevealedOffset,
329        trailing_edge_offset: RevealedOffset,
330        current_offset: f64,
331    ) -> Option<RevealedOffset> {
332        //           scrollOffset
333        //                       0 +---------+
334        //                         |         |
335        //                       _ |         |
336        //    viewport position |  |         |
337        // with `descendant` at |  |         | _
338        //        trailing edge |_ | xxxxxxx |  | viewport position
339        //                         |         |  | with `descendant` at
340        //                         |         | _| leading edge
341        //                         |         |
342        //                     800 +---------+
343        //
344        // `trailing_edge_offset`: Distance from scrollOffset 0 to the start of the viewport on
345        //                         the left in the image above.
346        // `leading_edge_offset`: Distance from scrollOffset 0 to the start of the viewport on
347        //                        the right in the image above.
348        //
349        // The viewport position on the left is achieved by setting `offset.pixels` to
350        // `trailing_edge_offset`, the one on the right by setting it to `leading_edge_offset`.
351        let inverted = leading_edge_offset.offset < trailing_edge_offset.offset;
352        let (smaller, larger) = if inverted {
353            (leading_edge_offset, trailing_edge_offset)
354        } else {
355            (trailing_edge_offset, leading_edge_offset)
356        };
357        if current_offset > larger.offset {
358            Some(larger)
359        } else if current_offset < smaller.offset {
360            Some(smaller)
361        } else {
362            None
363        }
364    }
365}
366
367/// Flutter's `layoutChildSequence`'s `advance` callback: `childBefore` or `childAfter`.
368pub type SliverAdvance<T> =
369    dyn Fn(RenderHandle<T>, &App, AnyRenderSliver) -> Option<AnyRenderSliver>;
370
371/// Flutter's `RenderViewportBase` fields.
372pub struct RenderViewportBaseData {
373    axis_direction: AxisDirection,
374    cross_axis_direction: AxisDirection,
375    offset: ViewportOffsetRef,
376    scroll_cache_extent: ScrollCacheExtent,
377    /// This value is set during layout based on the
378    /// [`scroll_cache_extent`](RenderViewportBase::scroll_cache_extent).
379    ///
380    /// When the style is [`CacheExtentStyle::Viewport`], it is the main axis extent of the
381    /// viewport multiplied by the requested cache extent, which is still expressed in pixels.
382    calculated_cache_extent: Option<f64>,
383    paint_order: SliverPaintOrder,
384    clip_behavior: Clip,
385    clip_rect_layer: LayerHandle<Handle<ClipRectLayer>>,
386}
387
388impl RenderViewportBaseData {
389    /// Initializes fields with Flutter's constructor defaults: an [`AxisDirection::Down`] axis,
390    /// a [`AnyRenderAbstractViewport::DEFAULT_CACHE_EXTENT`] pixel cache extent,
391    /// [`SliverPaintOrder::FirstIsTop`], and [`Clip::HardEdge`].
392    pub fn new(
393        cross_axis_direction: AxisDirection,
394        offset: ViewportOffsetRef,
395    ) -> RenderViewportBaseData {
396        RenderViewportBaseData {
397            axis_direction: AxisDirection::Down,
398            cross_axis_direction,
399            offset,
400            scroll_cache_extent: ScrollCacheExtent::Pixels(
401                AnyRenderAbstractViewport::DEFAULT_CACHE_EXTENT,
402            ),
403            calculated_cache_extent: None,
404            paint_order: SliverPaintOrder::FirstIsTop,
405            clip_behavior: Clip::HardEdge,
406            clip_rect_layer: LayerHandle::new(),
407        }
408    }
409}
410
411/// Implements [`RenderViewportBase`] field accessors for a `viewport` field.
412#[macro_export]
413macro_rules! render_viewport_base_accessors {
414    () => {
415        fn viewport_data(
416            self: $crate::RenderHandle<Self>,
417            app: &::waft_foundation::App,
418        ) -> &$crate::RenderViewportBaseData {
419            &self.get(app).viewport
420        }
421        fn viewport_data_mut(
422            self: $crate::RenderHandle<Self>,
423            app: &mut ::waft_foundation::App,
424        ) -> &mut $crate::RenderViewportBaseData {
425            &mut self.get_mut(app).viewport
426        }
427    };
428}
429
430/// A base class for render objects that are bigger on the inside.
431///
432/// This render object provides the shared code for render objects that host [`AnyRenderSliver`]
433/// render objects inside a [`RenderBox`]. The viewport establishes an
434/// [`axis_direction`](Self::axis_direction), which orients the sliver's coordinate system, which
435/// is based on scroll offsets rather than Cartesian coordinates.
436///
437/// The viewport also listens to an [`offset`](Self::offset), which determines the
438/// [`SliverConstraints::scroll_offset`] input to the sliver layout protocol.
439///
440/// Implementors typically override [`RenderObject::perform_layout`] and call
441/// [`layout_child_sequence`](Self::layout_child_sequence), perhaps multiple times.
442///
443/// Flutter's `RenderViewportBase`; the state lives in a [`RenderViewportBaseData`] field.
444pub trait RenderViewportBase:
445    RenderBox + RenderAbstractViewport + ContainerRenderObjectMixin<ChildType = AnyRenderSliver>
446{
447    /// Mixin field access.
448    fn viewport_data(self: RenderHandle<Self>, app: &App) -> &RenderViewportBaseData;
449
450    /// See [`viewport_data`](Self::viewport_data).
451    fn viewport_data_mut(self: RenderHandle<Self>, app: &mut App) -> &mut RenderViewportBaseData;
452
453    /// The direction in which the [`SliverConstraints::scroll_offset`] increases.
454    ///
455    /// For example, if the axis direction is [`AxisDirection::Down`], a scroll offset of zero is
456    /// at the top of the viewport and increases towards the bottom of the viewport.
457    fn axis_direction(self: RenderHandle<Self>, app: &App) -> AxisDirection {
458        self.viewport_data(app).axis_direction
459    }
460
461    /// Sets [`axis_direction`](Self::axis_direction).
462    fn set_axis_direction(self: RenderHandle<Self>, app: &mut App, value: AxisDirection) {
463        if value == self.axis_direction(app) {
464            return;
465        }
466        self.viewport_data_mut(app).axis_direction = value;
467        self.mark_needs_layout(app);
468    }
469
470    /// The direction in which child should be laid out in the cross axis.
471    ///
472    /// For example, if the [`axis_direction`](Self::axis_direction) is [`AxisDirection::Down`],
473    /// this property is typically [`AxisDirection::Left`] if the ambient text direction is
474    /// right-to-left and [`AxisDirection::Right`] if it is left-to-right.
475    fn cross_axis_direction(self: RenderHandle<Self>, app: &App) -> AxisDirection {
476        self.viewport_data(app).cross_axis_direction
477    }
478
479    /// Sets [`cross_axis_direction`](Self::cross_axis_direction).
480    fn set_cross_axis_direction(self: RenderHandle<Self>, app: &mut App, value: AxisDirection) {
481        if value == self.cross_axis_direction(app) {
482            return;
483        }
484        self.viewport_data_mut(app).cross_axis_direction = value;
485        self.mark_needs_layout(app);
486    }
487
488    /// The axis along which the viewport scrolls.
489    ///
490    /// For example, if the [`axis_direction`](Self::axis_direction) is [`AxisDirection::Down`],
491    /// then the axis is [`Axis::Vertical`] and the viewport scrolls vertically.
492    fn axis(self: RenderHandle<Self>, app: &App) -> Axis {
493        axis_direction_to_axis(self.axis_direction(app))
494    }
495
496    /// Which part of the content inside the viewport should be visible.
497    ///
498    /// The [`crate::ViewportOffset::pixels`] value determines the scroll offset that the
499    /// viewport uses to select which part of its content to display. As the user scrolls the
500    /// viewport, this value changes, which changes the content that is displayed.
501    fn offset(self: RenderHandle<Self>, app: &App) -> AnyViewportOffset {
502        self.viewport_data(app).offset.handle()
503    }
504
505    /// Sets [`offset`](Self::offset).
506    fn set_offset(self: RenderHandle<Self>, app: &mut App, value: ViewportOffsetRef) {
507        let old = self.offset(app);
508        if value == old {
509            return;
510        }
511        if self.attached(app) {
512            old.remove_listener(app, &self.mark_needs_layout_listener());
513        }
514        let new = value.handle();
515        // The old offset goes when this local does, after the listener moved off it.
516        let _old = std::mem::replace(&mut self.viewport_data_mut(app).offset, value);
517        if self.attached(app) {
518            new.add_listener(app, self.mark_needs_layout_listener());
519        }
520        // We need to go through layout even if the new offset has the same pixels value as the
521        // old offset so that we will apply our viewport and content dimensions.
522        self.mark_needs_layout(app);
523    }
524
525    /// Dart's `_offset.addListener(markNeedsLayout)` tear-off.
526    fn mark_needs_layout_listener(self: RenderHandle<Self>) -> Listener {
527        Listener::handle_method(self.handle(), viewport_offset_changed::<Self>)
528    }
529
530    /// The viewport has an area before and after the visible area to cache items that are about
531    /// to become visible when the user scrolls.
532    ///
533    /// Items that fall in this cache area are laid out even though they are not (yet) visible on
534    /// screen. The scroll cache extent describes how much the cache area extends before the
535    /// leading edge and after the trailing edge of the viewport.
536    ///
537    /// The total extent, which the viewport will try to cover with children, is the scroll cache
538    /// extent before the leading edge + extent of the main axis + the scroll cache extent after
539    /// the trailing edge.
540    fn scroll_cache_extent(self: RenderHandle<Self>, app: &App) -> ScrollCacheExtent {
541        self.viewport_data(app).scroll_cache_extent
542    }
543
544    /// Sets [`scroll_cache_extent`](Self::scroll_cache_extent).
545    ///
546    /// `None` resets the value to [`AnyRenderAbstractViewport::DEFAULT_CACHE_EXTENT`] pixels.
547    fn set_scroll_cache_extent(
548        self: RenderHandle<Self>,
549        app: &mut App,
550        value: Option<ScrollCacheExtent>,
551    ) {
552        let effective_value = value.unwrap_or(ScrollCacheExtent::Pixels(
553            AnyRenderAbstractViewport::DEFAULT_CACHE_EXTENT,
554        ));
555        if effective_value == self.scroll_cache_extent(app) {
556            return;
557        }
558        self.viewport_data_mut(app).scroll_cache_extent = effective_value;
559        self.mark_needs_layout(app);
560    }
561
562    /// Deprecated. Use [`scroll_cache_extent`](Self::scroll_cache_extent) instead.
563    #[deprecated(note = "Use scroll_cache_extent instead.")]
564    fn cache_extent(self: RenderHandle<Self>, app: &App) -> f64 {
565        self.scroll_cache_extent(app).value()
566    }
567
568    /// Deprecated. Use [`set_scroll_cache_extent`](Self::set_scroll_cache_extent) instead.
569    ///
570    /// `None` resets the value to [`AnyRenderAbstractViewport::DEFAULT_CACHE_EXTENT`] pixels, in
571    /// which case the style becomes [`CacheExtentStyle::Pixel`].
572    #[deprecated(note = "Use set_scroll_cache_extent instead.")]
573    fn set_cache_extent(self: RenderHandle<Self>, app: &mut App, value: Option<f64>) {
574        let current = self.scroll_cache_extent(app);
575        if value == Some(current.value()) {
576            return;
577        }
578        let replacement = match value {
579            None => ScrollCacheExtent::Pixels(AnyRenderAbstractViewport::DEFAULT_CACHE_EXTENT),
580            Some(value) => match current {
581                ScrollCacheExtent::Pixels(_) => ScrollCacheExtent::Pixels(value),
582                ScrollCacheExtent::Viewport(_) => ScrollCacheExtent::Viewport(value),
583            },
584        };
585        self.viewport_data_mut(app).scroll_cache_extent = replacement;
586        self.mark_needs_layout(app);
587    }
588
589    /// Deprecated. Use [`scroll_cache_extent`](Self::scroll_cache_extent) instead.
590    #[deprecated(note = "Use scroll_cache_extent instead.")]
591    fn cache_extent_style(self: RenderHandle<Self>, app: &App) -> CacheExtentStyle {
592        self.scroll_cache_extent(app).style()
593    }
594
595    /// Deprecated. Use [`set_scroll_cache_extent`](Self::set_scroll_cache_extent) instead.
596    #[deprecated(note = "Use set_scroll_cache_extent instead.")]
597    fn set_cache_extent_style(self: RenderHandle<Self>, app: &mut App, value: CacheExtentStyle) {
598        let current = self.scroll_cache_extent(app);
599        if value == current.style() {
600            return;
601        }
602        self.viewport_data_mut(app).scroll_cache_extent = match value {
603            CacheExtentStyle::Pixel => ScrollCacheExtent::Pixels(current.value()),
604            CacheExtentStyle::Viewport => ScrollCacheExtent::Viewport(current.value()),
605        };
606        self.mark_needs_layout(app);
607    }
608
609    /// The order in which to paint the slivers; equivalently, the order in which to arrange them
610    /// in the z-direction.
611    ///
612    /// Whichever order the slivers are painted in, they will be hit-tested in the opposite
613    /// order.
614    ///
615    /// The default is [`SliverPaintOrder::FirstIsTop`].
616    fn paint_order(self: RenderHandle<Self>, app: &App) -> SliverPaintOrder {
617        self.viewport_data(app).paint_order
618    }
619
620    /// Sets [`paint_order`](Self::paint_order).
621    fn set_paint_order(self: RenderHandle<Self>, app: &mut App, value: SliverPaintOrder) {
622        if value == self.paint_order(app) {
623            return;
624        }
625        self.viewport_data_mut(app).paint_order = value;
626        self.mark_needs_paint(app);
627    }
628
629    /// The content will be clipped (or not) according to this option.
630    ///
631    /// Defaults to [`Clip::HardEdge`].
632    fn clip_behavior(self: RenderHandle<Self>, app: &App) -> Clip {
633        self.viewport_data(app).clip_behavior
634    }
635
636    /// Sets [`clip_behavior`](Self::clip_behavior).
637    fn set_clip_behavior(self: RenderHandle<Self>, app: &mut App, value: Clip) {
638        if value == self.clip_behavior(app) {
639            return;
640        }
641        self.viewport_data_mut(app).clip_behavior = value;
642        self.mark_needs_paint(app);
643    }
644
645    /// The body of Flutter's `attach` override: listens to the offset.
646    fn did_attach(
647        self: RenderHandle<Self>,
648        app: &mut App,
649        owner: waft_foundation::Handle<PipelineOwner>,
650    ) {
651        ContainerRenderObjectMixin::did_attach(self, app, owner);
652        self.offset(app)
653            .add_listener(app, self.mark_needs_layout_listener());
654    }
655
656    /// The body of Flutter's `detach` override: stops listening to the offset.
657    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
658        self.offset(app)
659            .remove_listener(app, &self.mark_needs_layout_listener());
660        ContainerRenderObjectMixin::did_detach(self, app);
661    }
662
663    /// Panics saying that the object does not support returning intrinsic dimensions if, in
664    /// debug mode, we are not in the [`debug_checking_intrinsics`] mode.
665    ///
666    /// This is used by [`compute_min_intrinsic_width`](Self::compute_min_intrinsic_width) et al
667    /// because viewports do not generally support returning intrinsic dimensions. See the
668    /// discussion at [`RenderBox::compute_min_intrinsic_width`].
669    fn debug_throw_if_not_checking_intrinsics(self: RenderHandle<Self>) -> bool {
670        let _ = self;
671        debug_assert!(
672            debug_checking_intrinsics(),
673            "{} does not support returning intrinsic dimensions.\n\
674             Calculating the intrinsic dimensions would require instantiating every child of \
675             the viewport, which defeats the point of viewports being lazy.\n\
676             If you are merely trying to shrink-wrap the viewport in the main axis direction, \
677             consider a RenderShrinkWrappingViewport render object (ShrinkWrappingViewport \
678             widget), which achieves that effect without implementing the intrinsic dimension \
679             API.",
680            std::any::type_name::<Self>()
681        );
682        true
683    }
684
685    /// Zero; a viewport has no intrinsic dimensions.
686    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
687        let _ = (app, height);
688        debug_assert!(self.debug_throw_if_not_checking_intrinsics());
689        0.0
690    }
691
692    /// Zero; a viewport has no intrinsic dimensions.
693    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
694        let _ = (app, height);
695        debug_assert!(self.debug_throw_if_not_checking_intrinsics());
696        0.0
697    }
698
699    /// Zero; a viewport has no intrinsic dimensions.
700    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
701        let _ = (app, width);
702        debug_assert!(self.debug_throw_if_not_checking_intrinsics());
703        0.0
704    }
705
706    /// Zero; a viewport has no intrinsic dimensions.
707    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
708        let _ = (app, width);
709        debug_assert!(self.debug_throw_if_not_checking_intrinsics());
710        0.0
711    }
712
713    /// Determines the size and position of some of the children of the viewport.
714    ///
715    /// This function is the workhorse of `perform_layout` implementations in implementors.
716    ///
717    /// Layout starts with `child`, proceeds according to the `advance` callback, and stops once
718    /// `advance` returns `None`.
719    ///
720    ///  * `scroll_offset` is the [`SliverConstraints::scroll_offset`] to pass the first child.
721    ///    The scroll offset is adjusted by [`SliverGeometry::scroll_extent`] for subsequent
722    ///    children.
723    ///  * `overlap` is the [`SliverConstraints::overlap`] to pass the first child. The overlap
724    ///    is adjusted by the [`SliverGeometry::paint_origin`] and
725    ///    [`SliverGeometry::paint_extent`] for subsequent children.
726    ///  * `layout_offset` is the layout offset at which to place the first child. The layout
727    ///    offset is updated by the [`SliverGeometry::layout_extent`] for subsequent children.
728    ///  * `remaining_paint_extent` is [`SliverConstraints::remaining_paint_extent`] to pass the
729    ///    first child. The remaining paint extent is updated by the
730    ///    [`SliverGeometry::layout_extent`] for subsequent children.
731    ///  * `main_axis_extent` is the [`SliverConstraints::viewport_main_axis_extent`] to pass to
732    ///    each child.
733    ///  * `cross_axis_extent` is the [`SliverConstraints::cross_axis_extent`] to pass to each
734    ///    child.
735    ///  * `growth_direction` is the [`SliverConstraints::growth_direction`] to pass to each
736    ///    child.
737    ///
738    /// Returns the first non-zero [`SliverGeometry::scroll_offset_correction`] encountered, if
739    /// any. Otherwise returns 0.0. Typical callers will call this function repeatedly until it
740    /// returns 0.0.
741    #[allow(clippy::too_many_arguments)]
742    fn layout_child_sequence(
743        self: RenderHandle<Self>,
744        app: &mut App,
745        child: Option<AnyRenderSliver>,
746        scroll_offset: f64,
747        overlap: f64,
748        layout_offset: f64,
749        remaining_paint_extent: f64,
750        main_axis_extent: f64,
751        cross_axis_extent: f64,
752        growth_direction: GrowthDirection,
753        advance: &SliverAdvance<Self>,
754        remaining_cache_extent: f64,
755        cache_origin: f64,
756    ) -> f64 {
757        debug_assert!(scroll_offset.is_finite());
758        debug_assert!(scroll_offset >= 0.0);
759        let initial_layout_offset = layout_offset;
760        let adjusted_user_scroll_direction = apply_growth_direction_to_scroll_direction(
761            self.offset(app).user_scroll_direction(app),
762            growth_direction,
763        );
764        let axis_direction = self.axis_direction(app);
765        let cross_axis_direction = self.cross_axis_direction(app);
766        let mut max_paint_offset = layout_offset + overlap;
767        let mut preceding_scroll_extent = 0.0;
768        let mut scroll_offset = scroll_offset;
769        let mut layout_offset = layout_offset;
770        let mut remaining_cache_extent = remaining_cache_extent;
771        let mut cache_origin = cache_origin;
772        let mut child = child;
773
774        while let Some(current) = child {
775            let sliver_scroll_offset = scroll_offset.max(0.0);
776            // If the scrollOffset is too small we adjust the paddedOrigin because it doesn't
777            // make sense to ask a sliver for content before its scroll offset.
778            let corrected_cache_origin = cache_origin.max(-sliver_scroll_offset);
779            let cache_extent_correction = cache_origin - corrected_cache_origin;
780
781            debug_assert!(sliver_scroll_offset >= corrected_cache_origin.abs());
782            debug_assert!(corrected_cache_origin <= 0.0);
783            debug_assert!(sliver_scroll_offset >= 0.0);
784            debug_assert!(cache_extent_correction <= 0.0);
785
786            current.layout(
787                app,
788                SliverConstraints::new(
789                    axis_direction,
790                    growth_direction,
791                    adjusted_user_scroll_direction,
792                    sliver_scroll_offset,
793                    preceding_scroll_extent,
794                    max_paint_offset - layout_offset,
795                    (remaining_paint_extent - layout_offset + initial_layout_offset).max(0.0),
796                    cross_axis_extent,
797                    cross_axis_direction,
798                    main_axis_extent,
799                    (remaining_cache_extent + cache_extent_correction).max(0.0),
800                    corrected_cache_origin,
801                ),
802                true,
803            );
804
805            let child_layout_geometry = current.geometry(app);
806            debug_assert!(child_layout_geometry.debug_assert_is_valid());
807
808            // If there is a correction to apply, we'll have to start over.
809            if let Some(correction) = child_layout_geometry.scroll_offset_correction {
810                return correction;
811            }
812
813            // We use the child's paint origin in our coordinate system as the layoutOffset we
814            // store in the child's parent data.
815            let effective_layout_offset = layout_offset + child_layout_geometry.paint_origin;
816
817            // `effective_layout_offset` becomes meaningless once we moved past the trailing edge
818            // because `child_layout_geometry.layout_extent` is zero. Using the still increasing
819            // `scroll_offset` to roughly position these invisible slivers in the right order.
820            if child_layout_geometry.visible || scroll_offset > 0.0 {
821                self.update_child_layout_offset(
822                    app,
823                    current,
824                    effective_layout_offset,
825                    growth_direction,
826                );
827            } else {
828                self.update_child_layout_offset(
829                    app,
830                    current,
831                    -scroll_offset + initial_layout_offset,
832                    growth_direction,
833                );
834            }
835
836            max_paint_offset = (effective_layout_offset + child_layout_geometry.paint_extent)
837                .max(max_paint_offset);
838            scroll_offset -= child_layout_geometry.scroll_extent;
839            preceding_scroll_extent += child_layout_geometry.scroll_extent;
840            layout_offset += child_layout_geometry.layout_extent;
841            if child_layout_geometry.cache_extent != 0.0 {
842                remaining_cache_extent -=
843                    child_layout_geometry.cache_extent - cache_extent_correction;
844                cache_origin =
845                    (corrected_cache_origin + child_layout_geometry.cache_extent).min(0.0);
846            }
847
848            self.update_out_of_band_data(app, growth_direction, child_layout_geometry);
849
850            // move on to the next child
851            child = advance(self, app, current);
852        }
853
854        // we made it without a correction, whee!
855        0.0
856    }
857
858    /// Dart's `describeApproximatePaintClip`: the rectangle a sliver is painted within, the
859    /// viewport's bounds less the part another sliver covers.
860    fn describe_approximate_paint_clip(
861        self: RenderHandle<Self>,
862        app: &App,
863        child: AnyRenderSliver,
864    ) -> Option<Rect> {
865        let geometry = child.geometry(app);
866        if child.ensure_semantics(app) && !(geometry.visible || geometry.cache_extent > 0.0) {
867            // Return null here so we don't end up clipping out a semantics node rect
868            // for a sliver child when we explicitly want it to be included in the semantics
869            // tree.
870            return None;
871        }
872
873        match self.clip_behavior(app) {
874            Clip::None => return None,
875            Clip::HardEdge | Clip::AntiAlias | Clip::AntiAliasWithSaveLayer => {}
876        }
877
878        let viewport_clip = Offset::ZERO & self.size(app);
879        let constraints = child.constraints(app);
880        // The child's viewportMainAxisExtent can be infinite when a
881        // RenderShrinkWrappingViewport is given infinite constraints, such as when it is the
882        // child of a Row or Column (depending on orientation).
883        //
884        // For example, a shrink wrapping render sliver may have infinite constraints along the
885        // viewport's main axis but may also have bouncing scroll physics, which will allow for
886        // some scrolling effect to occur. We should just use the viewport_clip - the start of
887        // the overlap is at double.infinity and so it is effectively meaningless.
888        if constraints.overlap == 0.0 || !constraints.viewport_main_axis_extent.is_finite() {
889            return Some(viewport_clip);
890        }
891
892        // Adjust the clip rect for this sliver by the overlap from the previous sliver.
893        let mut left = viewport_clip.left;
894        let mut right = viewport_clip.right;
895        let mut top = viewport_clip.top;
896        let mut bottom = viewport_clip.bottom;
897        let start_of_overlap =
898            constraints.viewport_main_axis_extent - constraints.remaining_paint_extent;
899        let overlap_correction = start_of_overlap + constraints.overlap;
900        match apply_growth_direction_to_axis_direction(
901            self.axis_direction(app),
902            constraints.growth_direction,
903        ) {
904            AxisDirection::Down => top += overlap_correction,
905            AxisDirection::Up => bottom -= overlap_correction,
906            AxisDirection::Right => left += overlap_correction,
907            AxisDirection::Left => right -= overlap_correction,
908        }
909        Some(Rect::from_ltrb(left, top, right, bottom))
910    }
911
912    /// The body of Flutter's `paint` override.
913    fn paint(
914        self: RenderHandle<Self>,
915        app: &mut App,
916        context: &mut PaintingContext,
917        offset: Offset,
918    ) {
919        if self.first_child(app).is_none() {
920            return;
921        }
922        let clip_behavior = self.clip_behavior(app);
923        if self.has_visual_overflow(app) && clip_behavior != Clip::None {
924            let bounds = Offset::ZERO & self.size(app);
925            let old = self.viewport_data(app).clip_rect_layer.layer();
926            let layer = context.push_clip_rect(
927                app,
928                self.as_object().needs_compositing(app),
929                offset,
930                bounds,
931                |app, context, offset| self.paint_contents(app, context, offset),
932                clip_behavior,
933                old,
934            );
935            LayerHandle::set_layer(
936                app,
937                |app| &mut self.viewport_data_mut(app).clip_rect_layer,
938                layer,
939            );
940        } else {
941            LayerHandle::set_layer(
942                app,
943                |app| &mut self.viewport_data_mut(app).clip_rect_layer,
944                None,
945            );
946            self.paint_contents(app, context, offset);
947        }
948    }
949
950    /// Flutter's `dispose`: drop the clip layer handle, then `super.dispose()`.
951    fn dispose(self: RenderHandle<Self>, app: &mut App) {
952        LayerHandle::set_layer(
953            app,
954            |app| &mut self.viewport_data_mut(app).clip_rect_layer,
955            None,
956        );
957        crate::object::RenderObjectBase::dispose(self, app);
958    }
959
960    /// Flutter's `_paintContents`.
961    fn paint_contents(
962        self: RenderHandle<Self>,
963        app: &mut App,
964        context: &mut PaintingContext,
965        offset: Offset,
966    ) {
967        for child in self.children_in_paint_order(app) {
968            if child.geometry(app).visible {
969                let child_offset = offset + self.paint_offset_of(app, child);
970                context.paint_child(app, child.as_object(), child_offset);
971            }
972        }
973    }
974
975    /// The body of Flutter's `hitTestChildren` override.
976    fn hit_test_children(
977        self: RenderHandle<Self>,
978        app: &mut App,
979        result: &mut BoxHitTestResult<'_>,
980        position: Offset,
981    ) -> bool {
982        let (main_axis_position, cross_axis_position) = match self.axis(app) {
983            Axis::Vertical => (position.dy(), position.dx()),
984            Axis::Horizontal => (position.dx(), position.dy()),
985        };
986        for child in self.children_in_hit_test_order(app) {
987            if !child.geometry(app).visible {
988                continue;
989            }
990            let mut transform = Matrix4::IDENTITY;
991            // must be invertible
992            self.as_object()
993                .apply_paint_transform(app, child.as_object(), &mut transform);
994            let child_main_axis_position =
995                self.compute_child_main_axis_position(app, child, main_axis_position);
996            let is_hit =
997                result.add_with_out_of_band_position(None, Some(transform), None, |result| {
998                    child.hit_test(
999                        app,
1000                        &mut SliverHitTestResult::wrap(result),
1001                        child_main_axis_position,
1002                        cross_axis_position,
1003                    )
1004                });
1005            if is_hit {
1006                return true;
1007            }
1008        }
1009        false
1010    }
1011
1012    /// The body of Flutter's `getOffsetToReveal` override.
1013    fn get_offset_to_reveal(
1014        self: RenderHandle<Self>,
1015        app: &App,
1016        target: AnyRenderObject,
1017        alignment: f64,
1018        rect: Option<Rect>,
1019        _axis: Option<Axis>,
1020    ) -> RevealedOffset {
1021        // One dimensional viewport has only one axis, override if it was provided/may be
1022        // mismatched.
1023        let axis = self.axis(app);
1024        let this = self.as_object();
1025
1026        // Steps to convert `rect` (from a RenderBox coordinate system) to its scroll offset
1027        // within this viewport (not in the exact order):
1028        //
1029        // 1. Pick the outermost RenderBox (between which, and the viewport, there is nothing but
1030        // RenderSlivers) as an intermediate reference frame (the `pivot`), convert `rect` to
1031        // that coordinate space.
1032        //
1033        // 2. Convert `rect` from the `pivot` coordinate space to its sliver parent's sliver
1034        // coordinate system (i.e., to a scroll offset), based on the axis direction and growth
1035        // direction of the parent.
1036        //
1037        // 3. Convert the scroll offset to its sliver parent's coordinate space using
1038        // `child_scroll_offset`, until we reach the viewport.
1039        //
1040        // 4. Make the final conversion from the outmost sliver to the viewport using
1041        // `scroll_offset_of`.
1042
1043        let mut leading_scroll_offset = 0.0;
1044        // Starting at `target` and walking towards the root:
1045        //  - `child` will be the last object before we reach this viewport, and
1046        //  - `pivot` will be the last RenderBox before we reach this viewport.
1047        let mut child = target;
1048        let mut pivot = None;
1049        // ... between viewport and `target` (`target` included).
1050        let mut only_slivers = target.as_sliver().is_some();
1051        let mut rect = rect;
1052        while child.parent(app) != Some(this) {
1053            let parent = child
1054                .parent(app)
1055                .expect("target is a descendant of this viewport");
1056            if let Some(box_child) = child.as_box() {
1057                pivot = Some(box_child);
1058            }
1059            match parent.as_sliver() {
1060                Some(sliver) => {
1061                    leading_scroll_offset += sliver
1062                        .child_scroll_offset(app, child)
1063                        .expect("a sliver parent reports its child's scroll offset");
1064                }
1065                None => {
1066                    only_slivers = false;
1067                    leading_scroll_offset = 0.0;
1068                }
1069            }
1070            child = parent;
1071        }
1072
1073        // `rect` in the new intermediate coordinate system.
1074        let rect_local;
1075        // Our new reference frame render object's main axis extent.
1076        let pivot_extent;
1077        let growth_direction;
1078
1079        // `leading_scroll_offset` is currently the scrollOffset of our new reference frame
1080        // (`pivot` or `target`), within `child`.
1081        if let Some(pivot) = pivot {
1082            debug_assert!(pivot.as_object().parent(app).is_some());
1083            debug_assert_ne!(pivot.as_object().parent(app), Some(this));
1084            debug_assert_ne!(pivot.as_object(), this);
1085            let pivot_parent = pivot
1086                .as_object()
1087                .parent(app)
1088                .and_then(AnyRenderObject::as_sliver)
1089                .expect("only sliver parents are supported between a pivot and the viewport");
1090            growth_direction = pivot_parent.constraints(app).growth_direction;
1091            pivot_extent = match axis {
1092                Axis::Horizontal => pivot.size(app).width(),
1093                Axis::Vertical => pivot.size(app).height(),
1094            };
1095            let rect = *rect.get_or_insert_with(|| target.paint_bounds(app));
1096            rect_local =
1097                transform_rect(&target.get_transform_to(app, Some(pivot.as_object())), rect);
1098        } else if only_slivers {
1099            // `pivot` does not exist. We'll have to make up one from `target`, the innermost
1100            // sliver.
1101            let target_sliver = target.as_sliver().expect("only_slivers");
1102            growth_direction = target_sliver.constraints(app).growth_direction;
1103            pivot_extent = target_sliver.geometry(app).scroll_extent;
1104            rect_local = *rect.get_or_insert_with(|| {
1105                let constraints = target_sliver.constraints(app);
1106                let geometry = target_sliver.geometry(app);
1107                match axis {
1108                    Axis::Horizontal => Rect::from_ltwh(
1109                        0.0,
1110                        0.0,
1111                        geometry.scroll_extent,
1112                        constraints.cross_axis_extent,
1113                    ),
1114                    Axis::Vertical => Rect::from_ltwh(
1115                        0.0,
1116                        0.0,
1117                        constraints.cross_axis_extent,
1118                        geometry.scroll_extent,
1119                    ),
1120                }
1121            });
1122        } else {
1123            let rect = rect.expect("a non-sliver target must be given a rect");
1124            return RevealedOffset::new(self.offset(app).pixels(app), rect);
1125        }
1126
1127        debug_assert_eq!(child.parent(app), Some(this));
1128        let sliver = child
1129            .as_sliver()
1130            .expect("a viewport's children are slivers");
1131
1132        // The scroll offset of `rect` within `child`.
1133        leading_scroll_offset += match apply_growth_direction_to_axis_direction(
1134            self.axis_direction(app),
1135            growth_direction,
1136        ) {
1137            AxisDirection::Up => pivot_extent - rect_local.bottom,
1138            AxisDirection::Left => pivot_extent - rect_local.right,
1139            AxisDirection::Right => rect_local.left,
1140            AxisDirection::Down => rect_local.top,
1141        };
1142
1143        // So far leading_scroll_offset is the scroll offset of `rect` in the `child` sliver's
1144        // sliver coordinate system. The sign of this value indicates whether the `rect`
1145        // protrudes the leading edge of the `child` sliver. When this value is non-negative and
1146        // `child`'s `max_scroll_obstruction_extent` is greater than 0, we assume `rect` can't be
1147        // obstructed by the leading edge of the viewport (i.e. it is pinned to the leading edge).
1148        let is_pinned = sliver.geometry(app).max_scroll_obstruction_extent > 0.0
1149            && leading_scroll_offset >= 0.0;
1150
1151        // The scroll offset in the viewport to `rect`.
1152        leading_scroll_offset = self.scroll_offset_of(app, sliver, leading_scroll_offset);
1153
1154        // This step assumes the viewport's layout is up-to-date, i.e., if offset.pixels is
1155        // changed after the last perform_layout, the new scroll position will not be accounted
1156        // for.
1157        let transform = target.get_transform_to(app, Some(this));
1158        let mut target_rect = transform_rect(&transform, rect.expect("set above"));
1159        let extent_of_pinned_slivers = self.max_scroll_obstruction_extent_before(app, sliver);
1160
1161        match sliver.constraints(app).growth_direction {
1162            GrowthDirection::Forward => {
1163                if is_pinned && alignment <= 0.0 {
1164                    return RevealedOffset::new(f64::INFINITY, target_rect);
1165                }
1166                leading_scroll_offset -= extent_of_pinned_slivers;
1167            }
1168            GrowthDirection::Reverse => {
1169                if is_pinned && alignment >= 1.0 {
1170                    return RevealedOffset::new(f64::NEG_INFINITY, target_rect);
1171                }
1172                // If child's growth direction is reverse, when viewport.offset is
1173                // `leading_scroll_offset`, it is positioned just outside of the leading edge of
1174                // the viewport.
1175                leading_scroll_offset -= match axis {
1176                    Axis::Vertical => target_rect.height(),
1177                    Axis::Horizontal => target_rect.width(),
1178                };
1179            }
1180        }
1181
1182        let size = self.size(app);
1183        let main_axis_extent_difference = match axis {
1184            Axis::Horizontal => size.width() - extent_of_pinned_slivers - rect_local.width(),
1185            Axis::Vertical => size.height() - extent_of_pinned_slivers - rect_local.height(),
1186        };
1187
1188        let target_offset = leading_scroll_offset - main_axis_extent_difference * alignment;
1189        let offset_difference = self.offset(app).pixels(app) - target_offset;
1190
1191        target_rect = match self.axis_direction(app) {
1192            AxisDirection::Up => target_rect.translate(0.0, -offset_difference),
1193            AxisDirection::Down => target_rect.translate(0.0, offset_difference),
1194            AxisDirection::Left => target_rect.translate(-offset_difference, 0.0),
1195            AxisDirection::Right => target_rect.translate(offset_difference, 0.0),
1196        };
1197
1198        RevealedOffset::new(target_offset, target_rect)
1199    }
1200
1201    /// The offset at which the given `child` should be painted.
1202    ///
1203    /// The returned offset is from the top left corner of the inside of the viewport to the top
1204    /// left corner of the paint coordinate system of the `child`.
1205    ///
1206    /// See also:
1207    ///
1208    ///  * [`paint_offset_of`](Self::paint_offset_of), which uses the layout offset and growth
1209    ///    direction computed for the child during layout.
1210    fn compute_absolute_paint_offset(
1211        self: RenderHandle<Self>,
1212        app: &App,
1213        child: AnyRenderSliver,
1214        layout_offset: f64,
1215        growth_direction: GrowthDirection,
1216    ) -> Offset {
1217        // this is only usable once we have a size
1218        debug_assert!(self.has_size(app));
1219        let paint_extent = child.geometry(app).paint_extent;
1220        let size = self.size(app);
1221        match apply_growth_direction_to_axis_direction(self.axis_direction(app), growth_direction) {
1222            AxisDirection::Up => Offset::new(0.0, size.height() - layout_offset - paint_extent),
1223            AxisDirection::Left => Offset::new(size.width() - layout_offset - paint_extent, 0.0),
1224            AxisDirection::Right => Offset::new(layout_offset, 0.0),
1225            AxisDirection::Down => Offset::new(0.0, layout_offset),
1226        }
1227    }
1228
1229    // API TO BE IMPLEMENTED BY SUBCLASSES
1230
1231    /// Whether the contents of this viewport would paint outside the bounds of the viewport if
1232    /// [`paint`](Self::paint) did not clip.
1233    ///
1234    /// This property enables an optimization whereby [`paint`](Self::paint) can skip applying a
1235    /// clip if the contents of the viewport are known to paint entirely within its bounds.
1236    fn has_visual_overflow(self: RenderHandle<Self>, app: &App) -> bool;
1237
1238    /// Called during [`layout_child_sequence`](Self::layout_child_sequence) for each child.
1239    ///
1240    /// Typically used by implementors to update any out-of-band data, such as the max scroll
1241    /// extent, for each child.
1242    fn update_out_of_band_data(
1243        self: RenderHandle<Self>,
1244        app: &mut App,
1245        growth_direction: GrowthDirection,
1246        child_layout_geometry: SliverGeometry,
1247    );
1248
1249    /// Called during [`layout_child_sequence`](Self::layout_child_sequence) to store the layout
1250    /// offset for the given child.
1251    ///
1252    /// Different implementors use different representations for their children's layout offset
1253    /// (e.g., logical or physical coordinates). This function lets them transform the child's
1254    /// layout offset before storing it in the child's parent data.
1255    fn update_child_layout_offset(
1256        self: RenderHandle<Self>,
1257        app: &mut App,
1258        child: AnyRenderSliver,
1259        layout_offset: f64,
1260        growth_direction: GrowthDirection,
1261    );
1262
1263    /// The offset at which the given `child` should be painted.
1264    ///
1265    /// The returned offset is from the top left corner of the inside of the viewport to the top
1266    /// left corner of the paint coordinate system of the `child`.
1267    ///
1268    /// See also:
1269    ///
1270    ///  * [`compute_absolute_paint_offset`](Self::compute_absolute_paint_offset), which computes
1271    ///    the paint offset from an explicit layout offset and growth direction instead of using
1272    ///    the values computed for the child during layout.
1273    fn paint_offset_of(self: RenderHandle<Self>, app: &App, child: AnyRenderSliver) -> Offset;
1274
1275    /// Returns the scroll offset within the viewport for the given `scroll_offset_within_child`
1276    /// within the given `child`.
1277    ///
1278    /// The returned value is an estimate that assumes the slivers within the viewport do not
1279    /// change the layout extent in response to changes in their scroll offset.
1280    fn scroll_offset_of(
1281        self: RenderHandle<Self>,
1282        app: &App,
1283        child: AnyRenderSliver,
1284        scroll_offset_within_child: f64,
1285    ) -> f64;
1286
1287    /// Returns the total scroll obstruction extent of all slivers in the viewport before
1288    /// `child`.
1289    ///
1290    /// This is the extent by which the actual area in which content can scroll is reduced. For
1291    /// example, an app bar that is pinned at the top will reduce the area in which content can
1292    /// actually scroll by the height of the app bar.
1293    fn max_scroll_obstruction_extent_before(
1294        self: RenderHandle<Self>,
1295        app: &App,
1296        child: AnyRenderSliver,
1297    ) -> f64;
1298
1299    /// Converts the `parent_main_axis_position` into the child's coordinate system.
1300    ///
1301    /// The `parent_main_axis_position` is a distance from the top edge (for vertical viewports)
1302    /// or left edge (for horizontal viewports) of the viewport bounds. This describes a line,
1303    /// perpendicular to the viewport's main axis, heretofore known as the target line.
1304    ///
1305    /// The child's coordinate system's origin in the main axis is at the leading edge of the
1306    /// given child, as given by the child's [`SliverConstraints::axis_direction`] and
1307    /// [`SliverConstraints::growth_direction`].
1308    ///
1309    /// This method returns the distance from the leading edge of the given child to the target
1310    /// line described above.
1311    fn compute_child_main_axis_position(
1312        self: RenderHandle<Self>,
1313        app: &App,
1314        child: AnyRenderSliver,
1315        parent_main_axis_position: f64,
1316    ) -> f64;
1317
1318    /// The index of the first child of the viewport relative to the center child.
1319    ///
1320    /// For example, the center child has index zero and the first child in the reverse growth
1321    /// direction has index -1.
1322    fn index_of_first_child(self: RenderHandle<Self>, app: &App) -> i32;
1323
1324    /// A short string to identify the child with the given index.
1325    fn label_for_child(self: RenderHandle<Self>, index: i32) -> String;
1326
1327    /// Dart's `debugFillProperties`: the axis directions and the offset.
1328    fn debug_fill_properties(
1329        self: RenderHandle<Self>,
1330        app: &App,
1331        properties: &mut DiagnosticPropertiesBuilder,
1332    ) {
1333        properties.add(EnumProperty::new("axisDirection", self.axis_direction(app)));
1334        properties.add(EnumProperty::new(
1335            "crossAxisDirection",
1336            self.cross_axis_direction(app),
1337        ));
1338        properties.add(DiagnosticsProperty::<String>::new(
1339            "offset",
1340            Some(self.offset(app).to_string_with_app(app)),
1341        ));
1342    }
1343
1344    /// Dart's `debugDescribeChildren`: every child in paint order, named by
1345    /// [`label_for_child`](Self::label_for_child).
1346    fn debug_describe_children(
1347        self: RenderHandle<Self>,
1348        app: &App,
1349    ) -> Vec<Rc<dyn DiagnosticsNode>> {
1350        let mut children = Vec::new();
1351        let (Some(mut child), Some(last)) = (self.first_child(app), self.last_child(app)) else {
1352            return children;
1353        };
1354        let mut count = self.index_of_first_child(app);
1355        loop {
1356            children.push(Rc::new(
1357                child
1358                    .as_object()
1359                    .to_diagnostics_node(app, self.label_for_child(count)),
1360            ));
1361            if child == last {
1362                break;
1363            }
1364            count += 1;
1365            child = self
1366                .child_after(app, child)
1367                .expect("the last child ends the walk");
1368        }
1369        children
1370    }
1371
1372    /// Walks the children of the viewport, in the order that they should be painted.
1373    ///
1374    /// This is the reverse order of
1375    /// [`children_in_hit_test_order`](Self::children_in_hit_test_order).
1376    fn children_in_paint_order(self: RenderHandle<Self>, app: &App) -> Vec<AnyRenderSliver> {
1377        match self.paint_order(app) {
1378            SliverPaintOrder::FirstIsTop => self.children_last_to_first(app),
1379            SliverPaintOrder::LastIsTop => self.children_as_list(app),
1380        }
1381    }
1382
1383    /// Walks the children of the viewport, in the order that hit-testing should use.
1384    ///
1385    /// This is the reverse order of [`children_in_paint_order`](Self::children_in_paint_order).
1386    fn children_in_hit_test_order(self: RenderHandle<Self>, app: &App) -> Vec<AnyRenderSliver> {
1387        match self.paint_order(app) {
1388            SliverPaintOrder::FirstIsTop => self.children_as_list(app),
1389            SliverPaintOrder::LastIsTop => self.children_last_to_first(app),
1390        }
1391    }
1392
1393    /// Flutter's `_childrenLastToFirst`.
1394    fn children_last_to_first(self: RenderHandle<Self>, app: &App) -> Vec<AnyRenderSliver> {
1395        let mut children = Vec::new();
1396        let mut child = self.last_child(app);
1397        while let Some(current) = child {
1398            children.push(current);
1399            child = self.child_before(app, current);
1400        }
1401        children
1402    }
1403
1404    /// The body of Flutter's `showOnScreen` override.
1405    fn show_on_screen(
1406        self: RenderHandle<Self>,
1407        app: &mut App,
1408        descendant: Option<AnyRenderObject>,
1409        rect: Option<Rect>,
1410        duration: Duration,
1411        curve: Rc<dyn Curve>,
1412    ) {
1413        let offset = self.offset(app);
1414        if !offset.allow_implicit_scrolling(app) {
1415            return crate::object::RenderObjectBase::show_on_screen(
1416                self, app, descendant, rect, duration, curve,
1417            );
1418        }
1419
1420        let new_rect = show_in_viewport(
1421            app,
1422            descendant,
1423            rect,
1424            self.as_abstract_viewport(),
1425            offset,
1426            duration,
1427            Rc::clone(&curve),
1428        );
1429        crate::object::RenderObjectBase::show_on_screen(self, app, None, new_rect, duration, curve);
1430    }
1431}
1432
1433/// Dart's `_offset.addListener(markNeedsLayout)` tear-off body: a named function so that the
1434/// listener added on attach compares equal to the one removed on detach.
1435fn viewport_offset_changed<T: RenderViewportBase>(this: waft_foundation::Handle<T>, app: &mut App) {
1436    RenderHandle::from_handle(this).mark_needs_layout(app);
1437}
1438
1439/// Make (a portion of) the given `descendant` of the given `viewport` fully visible in the
1440/// `viewport` by manipulating the provided [`AnyViewportOffset`] `offset`.
1441///
1442/// The optional `rect` parameter describes which area of the `descendant` should be shown in the
1443/// viewport. If `rect` is `None`, the entire `descendant` will be revealed. The `rect` parameter
1444/// is interpreted relative to the coordinate system of `descendant`.
1445///
1446/// The returned [`Rect`] describes the new location of `descendant` or `rect` in the viewport
1447/// after it has been revealed. See [`RevealedOffset::rect`] for a full definition of this rect.
1448///
1449/// If `descendant` is `None`, this is a no-op and `rect` is returned.
1450///
1451/// The `duration` parameter can be set to a non-zero value to animate the target object into the
1452/// viewport with an animation defined by `curve`.
1453///
1454/// Flutter's `RenderViewportBase.showInViewport` static.
1455pub fn show_in_viewport(
1456    app: &mut App,
1457    descendant: Option<AnyRenderObject>,
1458    rect: Option<Rect>,
1459    viewport: AnyRenderAbstractViewport,
1460    offset: AnyViewportOffset,
1461    duration: Duration,
1462    curve: Rc<dyn Curve>,
1463) -> Option<Rect> {
1464    let Some(descendant) = descendant else {
1465        return rect;
1466    };
1467    let leading_edge_offset = viewport.get_offset_to_reveal(app, descendant, 0.0, rect, None);
1468    let trailing_edge_offset = viewport.get_offset_to_reveal(app, descendant, 1.0, rect, None);
1469    let current_offset = offset.pixels(app);
1470    let target_offset =
1471        RevealedOffset::clamp_offset(leading_edge_offset, trailing_edge_offset, current_offset);
1472    let Some(target_offset) = target_offset else {
1473        // `descendant` is between leading and trailing edge and hence already fully shown on
1474        // screen. No action necessary.
1475        let viewport_object = viewport.as_object(app);
1476        debug_assert!(viewport_object.parent(app).is_some());
1477        let transform = descendant.get_transform_to(app, viewport_object.parent(app));
1478        return Some(transform_rect(
1479            &transform,
1480            rect.unwrap_or_else(|| descendant.paint_bounds(app)),
1481        ));
1482    };
1483
1484    offset.move_to(app, target_offset.offset, Some(duration), Some(curve), None);
1485    Some(target_offset.rect)
1486}
1487
1488/// A render object that is bigger on the inside.
1489///
1490/// [`RenderViewport`] is the visual workhorse of the scrolling machinery. It displays a subset of
1491/// its children according to its own dimensions and the given
1492/// [`offset`](RenderViewportBase::offset). As the offset varies, different children are visible
1493/// through the viewport.
1494///
1495/// [`RenderViewport`] hosts a bidirectional list of slivers in a single shared [`Axis`], anchored
1496/// on a [`center`](Self::center) sliver, which is placed at the zero scroll offset. The center
1497/// widget is displayed in the viewport according to the [`anchor`](Self::anchor) property.
1498///
1499/// Slivers that are earlier in the child list than [`center`](Self::center) are displayed in
1500/// reverse order in the reverse [`RenderViewportBase::axis_direction`] starting from the center.
1501///
1502/// [`RenderViewport`] cannot contain [`RenderBox`] children directly. Instead, use a
1503/// [`crate::RenderSliverList`], [`crate::RenderSliverFixedExtentList`], or a
1504/// [`crate::RenderSliverToBoxAdapter`], for example.
1505pub struct RenderViewport {
1506    render_object: RenderObjectData,
1507    render_box: RenderBoxData,
1508    container: ContainerRenderObjectData<AnyRenderSliver>,
1509    viewport: RenderViewportBaseData,
1510    anchor: f64,
1511    center: Option<AnyRenderSliver>,
1512    // Out-of-band data computed during layout.
1513    min_scroll_extent: f64,
1514    max_scroll_extent: f64,
1515    has_visual_overflow: bool,
1516}
1517
1518impl RenderViewport {
1519    /// Dart's `_maxLayoutCyclesPerChild`.
1520    const MAX_LAYOUT_CYCLES_PER_CHILD: usize = 10;
1521
1522    /// Creates a viewport for [`AnyRenderSliver`] objects.
1523    ///
1524    /// If the `center` is not specified, then the first child in the `children` list, if any, is
1525    /// used.
1526    ///
1527    /// For testing purposes, consider passing a [`crate::FixedViewportOffset`] as the `offset`.
1528    pub fn new(
1529        app: &mut App,
1530        cross_axis_direction: AxisDirection,
1531        offset: ViewportOffsetRef,
1532        children: Option<Vec<AnyRenderSliver>>,
1533        center: Option<AnyRenderSliver>,
1534    ) -> RenderHandle<RenderViewport> {
1535        let this = RenderHandle::new_box(
1536            app,
1537            RenderViewport {
1538                render_object: RenderObjectData::new(),
1539                render_box: RenderBoxData::new(),
1540                container: ContainerRenderObjectData::new(),
1541                viewport: RenderViewportBaseData::new(cross_axis_direction, offset),
1542                anchor: 0.0,
1543                center,
1544                min_scroll_extent: 0.0,
1545                max_scroll_extent: 0.0,
1546                has_visual_overflow: false,
1547            },
1548        );
1549        this.add_all(app, children);
1550        if center.is_none()
1551            && let Some(first_child) = this.first_child(app)
1552        {
1553            this.get_mut(app).center = Some(first_child);
1554        }
1555        this
1556    }
1557
1558    /// The relative position of the zero scroll offset.
1559    ///
1560    /// For example, if the [`RenderViewportBase::axis_direction`] is [`AxisDirection::Down`] or
1561    /// [`AxisDirection::Up`] and the anchor is 0.5, then the zero scroll offset is vertically
1562    /// centered within the viewport. If the anchor is 1.0, and the axis direction is
1563    /// [`AxisDirection::Right`], then the zero scroll offset is on the left edge of the viewport.
1564    pub fn anchor(self: RenderHandle<Self>, app: &App) -> f64 {
1565        self.get(app).anchor
1566    }
1567
1568    /// Sets [`anchor`](Self::anchor).
1569    pub fn set_anchor(self: RenderHandle<Self>, app: &mut App, value: f64) {
1570        debug_assert!((0.0..=1.0).contains(&value));
1571        if value == self.get(app).anchor {
1572            return;
1573        }
1574        self.get_mut(app).anchor = value;
1575        self.mark_needs_layout(app);
1576    }
1577
1578    /// The first child in the [`GrowthDirection::Forward`] growth direction.
1579    ///
1580    /// This child will be at the position defined by [`anchor`](Self::anchor) when the
1581    /// [`crate::ViewportOffset::pixels`] of [`RenderViewportBase::offset`] is `0`.
1582    ///
1583    /// Children after the center will be placed in the [`RenderViewportBase::axis_direction`]
1584    /// relative to the center. Children before it will be placed in the opposite direction, and
1585    /// will have a growth direction of [`GrowthDirection::Reverse`].
1586    ///
1587    /// The center must be a direct child of the viewport.
1588    pub fn center(self: RenderHandle<Self>, app: &App) -> Option<AnyRenderSliver> {
1589        self.get(app).center
1590    }
1591
1592    /// Sets [`center`](Self::center).
1593    pub fn set_center(self: RenderHandle<Self>, app: &mut App, value: Option<AnyRenderSliver>) {
1594        if value == self.get(app).center {
1595            return;
1596        }
1597        self.get_mut(app).center = value;
1598        self.mark_needs_layout(app);
1599    }
1600
1601    /// Flutter's `_attemptLayout`.
1602    fn attempt_layout(
1603        self: RenderHandle<Self>,
1604        app: &mut App,
1605        main_axis_extent: f64,
1606        cross_axis_extent: f64,
1607        corrected_offset: f64,
1608    ) -> f64 {
1609        debug_assert!(!main_axis_extent.is_nan());
1610        debug_assert!(main_axis_extent >= 0.0);
1611        debug_assert!(main_axis_extent.is_finite());
1612        debug_assert!(cross_axis_extent.is_finite());
1613        debug_assert!(cross_axis_extent >= 0.0);
1614        debug_assert!(corrected_offset.is_finite());
1615        let this = self.get_mut(app);
1616        this.min_scroll_extent = 0.0;
1617        this.max_scroll_extent = 0.0;
1618        this.has_visual_overflow = false;
1619
1620        // center_offset is the offset from the leading edge of the viewport to the zero scroll
1621        // offset (the line between the forward slivers and the reverse slivers).
1622        let anchor = self.get(app).anchor;
1623        let center_offset = main_axis_extent * anchor - corrected_offset;
1624        let reverse_direction_remaining_paint_extent =
1625            clamp_double(center_offset, 0.0, main_axis_extent);
1626        let forward_direction_remaining_paint_extent =
1627            clamp_double(main_axis_extent - center_offset, 0.0, main_axis_extent);
1628
1629        let calculated_cache_extent = self
1630            .scroll_cache_extent(app)
1631            .calculate_cache_offset(main_axis_extent);
1632        self.viewport_data_mut(app).calculated_cache_extent = Some(calculated_cache_extent);
1633
1634        let full_cache_extent = main_axis_extent + 2.0 * calculated_cache_extent;
1635        let center_cache_offset = center_offset + calculated_cache_extent;
1636        let reverse_direction_remaining_cache_extent =
1637            clamp_double(center_cache_offset, 0.0, full_cache_extent);
1638        let forward_direction_remaining_cache_extent = clamp_double(
1639            full_cache_extent - center_cache_offset,
1640            0.0,
1641            full_cache_extent,
1642        );
1643
1644        let center = self.center(app).expect("checked by perform_layout");
1645        let leading_negative_child = self.child_before(app, center);
1646
1647        if let Some(leading_negative_child) = leading_negative_child {
1648            // negative scroll offsets
1649            let result = self.layout_child_sequence(
1650                app,
1651                Some(leading_negative_child),
1652                main_axis_extent.max(center_offset) - main_axis_extent,
1653                0.0,
1654                forward_direction_remaining_paint_extent,
1655                reverse_direction_remaining_paint_extent,
1656                main_axis_extent,
1657                cross_axis_extent,
1658                GrowthDirection::Reverse,
1659                &|this, app, child| this.child_before(app, child),
1660                reverse_direction_remaining_cache_extent,
1661                clamp_double(
1662                    main_axis_extent - center_offset,
1663                    -calculated_cache_extent,
1664                    0.0,
1665                ),
1666            );
1667            if result != 0.0 {
1668                return -result;
1669            }
1670        }
1671
1672        // positive scroll offsets
1673        self.layout_child_sequence(
1674            app,
1675            Some(center),
1676            (-center_offset).max(0.0),
1677            if leading_negative_child.is_none() {
1678                (-center_offset).min(0.0)
1679            } else {
1680                0.0
1681            },
1682            if center_offset >= main_axis_extent {
1683                center_offset
1684            } else {
1685                reverse_direction_remaining_paint_extent
1686            },
1687            forward_direction_remaining_paint_extent,
1688            main_axis_extent,
1689            cross_axis_extent,
1690            GrowthDirection::Forward,
1691            &|this, app, child| this.child_after(app, child),
1692            forward_direction_remaining_cache_extent,
1693            clamp_double(center_offset, -calculated_cache_extent, 0.0),
1694        )
1695    }
1696}
1697
1698impl ContainerRenderObjectMixin for RenderViewport {
1699    type ChildType = AnyRenderSliver;
1700    type ParentDataType = SliverPhysicalContainerParentData;
1701
1702    fn container_data(
1703        self: RenderHandle<Self>,
1704        app: &App,
1705    ) -> &ContainerRenderObjectData<AnyRenderSliver> {
1706        &self.get(app).container
1707    }
1708
1709    fn container_data_mut(
1710        self: RenderHandle<Self>,
1711        app: &mut App,
1712    ) -> &mut ContainerRenderObjectData<AnyRenderSliver> {
1713        &mut self.get_mut(app).container
1714    }
1715}
1716
1717impl RenderViewportBase for RenderViewport {
1718    crate::render_viewport_base_accessors!();
1719
1720    fn has_visual_overflow(self: RenderHandle<Self>, app: &App) -> bool {
1721        self.get(app).has_visual_overflow
1722    }
1723
1724    fn update_out_of_band_data(
1725        self: RenderHandle<Self>,
1726        app: &mut App,
1727        growth_direction: GrowthDirection,
1728        child_layout_geometry: SliverGeometry,
1729    ) {
1730        let this = self.get_mut(app);
1731        match growth_direction {
1732            GrowthDirection::Forward => {
1733                this.max_scroll_extent += child_layout_geometry.scroll_extent
1734            }
1735            GrowthDirection::Reverse => {
1736                this.min_scroll_extent -= child_layout_geometry.scroll_extent
1737            }
1738        }
1739        if child_layout_geometry.has_visual_overflow {
1740            this.has_visual_overflow = true;
1741        }
1742    }
1743
1744    fn update_child_layout_offset(
1745        self: RenderHandle<Self>,
1746        app: &mut App,
1747        child: AnyRenderSliver,
1748        layout_offset: f64,
1749        growth_direction: GrowthDirection,
1750    ) {
1751        let paint_offset =
1752            self.compute_absolute_paint_offset(app, child, layout_offset, growth_direction);
1753        child
1754            .as_object()
1755            .parent_data_of_mut::<SliverPhysicalContainerParentData>(app)
1756            .set_paint_offset(paint_offset);
1757    }
1758
1759    fn paint_offset_of(self: RenderHandle<Self>, app: &App, child: AnyRenderSliver) -> Offset {
1760        child
1761            .as_object()
1762            .parent_data_of::<SliverPhysicalContainerParentData>(app)
1763            .paint_offset()
1764    }
1765
1766    fn scroll_offset_of(
1767        self: RenderHandle<Self>,
1768        app: &App,
1769        child: AnyRenderSliver,
1770        scroll_offset_within_child: f64,
1771    ) -> f64 {
1772        debug_assert_eq!(child.as_object().parent(app), Some(self.as_object()));
1773        match child.constraints(app).growth_direction {
1774            GrowthDirection::Forward => {
1775                let mut scroll_offset_to_child = 0.0;
1776                let mut current = self.center(app);
1777                while current != Some(child) {
1778                    let sliver = current.expect("the center precedes a forward child");
1779                    scroll_offset_to_child += sliver.geometry(app).scroll_extent;
1780                    current = self.child_after(app, sliver);
1781                }
1782                scroll_offset_to_child + scroll_offset_within_child
1783            }
1784            GrowthDirection::Reverse => {
1785                let mut scroll_offset_to_child = 0.0;
1786                let center = self.center(app).expect("a laid-out viewport has a center");
1787                let mut current = self.child_before(app, center);
1788                while current != Some(child) {
1789                    let sliver = current.expect("a reverse child precedes the center");
1790                    scroll_offset_to_child -= sliver.geometry(app).scroll_extent;
1791                    current = self.child_before(app, sliver);
1792                }
1793                scroll_offset_to_child - scroll_offset_within_child
1794            }
1795        }
1796    }
1797
1798    fn max_scroll_obstruction_extent_before(
1799        self: RenderHandle<Self>,
1800        app: &App,
1801        child: AnyRenderSliver,
1802    ) -> f64 {
1803        debug_assert_eq!(child.as_object().parent(app), Some(self.as_object()));
1804        let mut pinned_extent = 0.0;
1805        match child.constraints(app).growth_direction {
1806            GrowthDirection::Forward => {
1807                let mut current = self.center(app);
1808                while current != Some(child) {
1809                    let sliver = current.expect("the center precedes a forward child");
1810                    pinned_extent += sliver.geometry(app).max_scroll_obstruction_extent;
1811                    current = self.child_after(app, sliver);
1812                }
1813            }
1814            GrowthDirection::Reverse => {
1815                let center = self.center(app).expect("a laid-out viewport has a center");
1816                let mut current = self.child_before(app, center);
1817                while current != Some(child) {
1818                    let sliver = current.expect("a reverse child precedes the center");
1819                    pinned_extent += sliver.geometry(app).max_scroll_obstruction_extent;
1820                    current = self.child_before(app, sliver);
1821                }
1822            }
1823        }
1824        pinned_extent
1825    }
1826
1827    fn compute_child_main_axis_position(
1828        self: RenderHandle<Self>,
1829        app: &App,
1830        child: AnyRenderSliver,
1831        parent_main_axis_position: f64,
1832    ) -> f64 {
1833        let paint_offset = child
1834            .as_object()
1835            .parent_data_of::<SliverPhysicalContainerParentData>(app)
1836            .paint_offset();
1837        let constraints = child.constraints(app);
1838        let paint_extent = child.geometry(app).paint_extent;
1839        match apply_growth_direction_to_axis_direction(
1840            constraints.axis_direction,
1841            constraints.growth_direction,
1842        ) {
1843            AxisDirection::Down => parent_main_axis_position - paint_offset.dy(),
1844            AxisDirection::Right => parent_main_axis_position - paint_offset.dx(),
1845            AxisDirection::Up => paint_extent - (parent_main_axis_position - paint_offset.dy()),
1846            AxisDirection::Left => paint_extent - (parent_main_axis_position - paint_offset.dx()),
1847        }
1848    }
1849
1850    fn index_of_first_child(self: RenderHandle<Self>, app: &App) -> i32 {
1851        let center = self.center(app).expect("a laid-out viewport has a center");
1852        debug_assert_eq!(center.as_object().parent(app), Some(self.as_object()));
1853        debug_assert!(self.first_child(app).is_some());
1854        let mut count = 0;
1855        let mut child = Some(center);
1856        while child != self.first_child(app) {
1857            count -= 1;
1858            child = self.child_before(app, child.expect("the first child terminates the walk"));
1859        }
1860        count
1861    }
1862
1863    fn label_for_child(self: RenderHandle<Self>, index: i32) -> String {
1864        if index == 0 {
1865            "center child".to_owned()
1866        } else {
1867            format!("child {index}")
1868        }
1869    }
1870}
1871
1872impl RenderAbstractViewport for RenderViewport {
1873    fn get_offset_to_reveal(
1874        self: RenderHandle<Self>,
1875        app: &App,
1876        target: AnyRenderObject,
1877        alignment: f64,
1878        rect: Option<Rect>,
1879        axis: Option<Axis>,
1880    ) -> RevealedOffset {
1881        RenderViewportBase::get_offset_to_reveal(self, app, target, alignment, rect, axis)
1882    }
1883}
1884
1885impl RenderObject for RenderViewport {
1886    crate::render_object_accessors!();
1887
1888    fn visit_children(
1889        self: RenderHandle<Self>,
1890        app: &App,
1891        visitor: &mut dyn FnMut(AnyRenderObject),
1892    ) {
1893        ContainerRenderObjectMixin::visit_children(self, app, visitor)
1894    }
1895
1896    fn did_attach(
1897        self: RenderHandle<Self>,
1898        app: &mut App,
1899        owner: waft_foundation::Handle<PipelineOwner>,
1900    ) {
1901        RenderViewportBase::did_attach(self, app, owner)
1902    }
1903
1904    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
1905        RenderViewportBase::did_detach(self, app)
1906    }
1907
1908    fn redepth_children(self: RenderHandle<Self>, app: &mut App) {
1909        ContainerRenderObjectMixin::redepth_children(self, app)
1910    }
1911
1912    fn is_repaint_boundary(self: RenderHandle<Self>, _app: &App) -> bool {
1913        let _ = self;
1914        true
1915    }
1916
1917    fn interface(self: RenderHandle<Self>, id: TypeId) -> Option<Box<dyn Any>> {
1918        (id == TypeId::of::<AnyRenderAbstractViewport>())
1919            .then(|| Box::new(self.as_abstract_viewport()) as Box<dyn Any>)
1920    }
1921
1922    fn sized_by_parent(self: RenderHandle<Self>, _app: &App) -> bool {
1923        let _ = self;
1924        true
1925    }
1926
1927    fn debug_fill_properties(
1928        self: RenderHandle<Self>,
1929        app: &App,
1930        properties: &mut DiagnosticPropertiesBuilder,
1931    ) {
1932        RenderViewportBase::debug_fill_properties(self, app, properties);
1933        properties.add(DoubleProperty::new("anchor", self.anchor(app)));
1934    }
1935
1936    fn debug_describe_children(
1937        self: RenderHandle<Self>,
1938        app: &App,
1939    ) -> Vec<Rc<dyn DiagnosticsNode>> {
1940        RenderViewportBase::debug_describe_children(self, app)
1941    }
1942
1943    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
1944        // Ignore the return value of apply_viewport_dimension because we are doing a layout
1945        // regardless.
1946        let offset = self.offset(app);
1947        let size = self.size(app);
1948        match self.axis(app) {
1949            Axis::Vertical => offset.apply_viewport_dimension(app, size.height()),
1950            Axis::Horizontal => offset.apply_viewport_dimension(app, size.width()),
1951        };
1952
1953        let Some(center) = self.center(app) else {
1954            debug_assert!(self.first_child(app).is_none());
1955            let this = self.get_mut(app);
1956            this.min_scroll_extent = 0.0;
1957            this.max_scroll_extent = 0.0;
1958            this.has_visual_overflow = false;
1959            offset.apply_content_dimensions(app, 0.0, 0.0);
1960            return;
1961        };
1962        debug_assert_eq!(center.as_object().parent(app), Some(self.as_object()));
1963
1964        let (main_axis_extent, cross_axis_extent) = match self.axis(app) {
1965            Axis::Vertical => (size.height(), size.width()),
1966            Axis::Horizontal => (size.width(), size.height()),
1967        };
1968
1969        let center_offset_adjustment = center.center_offset_adjustment(app);
1970        let max_layout_cycles = RenderViewport::MAX_LAYOUT_CYCLES_PER_CHILD * self.child_count(app);
1971
1972        let anchor = self.get(app).anchor;
1973        let mut count = 0;
1974        loop {
1975            let correction = self.attempt_layout(
1976                app,
1977                main_axis_extent,
1978                cross_axis_extent,
1979                offset.pixels(app) + center_offset_adjustment,
1980            );
1981            if correction != 0.0 {
1982                offset.correct_by(app, correction);
1983            } else {
1984                let min_scroll_extent = self.get(app).min_scroll_extent;
1985                let max_scroll_extent = self.get(app).max_scroll_extent;
1986                if offset.apply_content_dimensions(
1987                    app,
1988                    (min_scroll_extent + main_axis_extent * anchor).min(0.0),
1989                    (max_scroll_extent - main_axis_extent * (1.0 - anchor)).max(0.0),
1990                ) {
1991                    break;
1992                }
1993            }
1994            count += 1;
1995            if count >= max_layout_cycles {
1996                break;
1997            }
1998        }
1999        debug_assert!(
2000            count < max_layout_cycles,
2001            "A RenderViewport exceeded its maximum number of layout cycles.\n\
2002             RenderViewport render objects, during layout, can retry if either their slivers or \
2003             their ViewportOffset decide that the offset should be corrected to take into \
2004             account information collected during that layout.\n\
2005             In the case of this RenderViewport object, however, this happened {count} times and \
2006             still there was no consensus on the scroll offset. This usually indicates a bug."
2007        );
2008    }
2009
2010    fn paint(
2011        self: RenderHandle<Self>,
2012        app: &mut App,
2013        context: &mut PaintingContext,
2014        offset: Offset,
2015    ) {
2016        RenderViewportBase::paint(self, app, context, offset)
2017    }
2018
2019    fn dispose(self: RenderHandle<Self>, app: &mut App) {
2020        RenderViewportBase::dispose(self, app)
2021    }
2022
2023    fn describe_approximate_paint_clip(
2024        self: RenderHandle<Self>,
2025        app: &App,
2026        child: AnyRenderObject,
2027    ) -> Option<Rect> {
2028        RenderViewportBase::describe_approximate_paint_clip(
2029            self,
2030            app,
2031            child
2032                .as_sliver()
2033                .expect("a viewport's children are slivers"),
2034        )
2035    }
2036
2037    fn show_on_screen(
2038        self: RenderHandle<Self>,
2039        app: &mut App,
2040        descendant: Option<AnyRenderObject>,
2041        rect: Option<Rect>,
2042        duration: Duration,
2043        curve: Rc<dyn Curve>,
2044    ) {
2045        RenderViewportBase::show_on_screen(self, app, descendant, rect, duration, curve)
2046    }
2047}
2048
2049impl RenderBox for RenderViewport {
2050    crate::render_box_accessors!();
2051
2052    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
2053        if !child.parent_data_is::<SliverPhysicalContainerParentData>(app) {
2054            child.set_parent_data(app, SliverPhysicalContainerParentData::new());
2055        }
2056    }
2057
2058    fn apply_paint_transform(
2059        self: RenderHandle<Self>,
2060        app: &App,
2061        child: AnyRenderObject,
2062        transform: &mut Matrix4,
2063    ) {
2064        // Hit test logic relies on this always providing an invertible matrix.
2065        child
2066            .parent_data_of::<SliverPhysicalContainerParentData>(app)
2067            .apply_paint_transform(transform);
2068    }
2069
2070    fn hit_test_children(
2071        self: RenderHandle<Self>,
2072        app: &mut App,
2073        result: &mut BoxHitTestResult<'_>,
2074        position: Offset,
2075    ) -> bool {
2076        RenderViewportBase::hit_test_children(self, app, result, position)
2077    }
2078
2079    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
2080        RenderViewportBase::compute_min_intrinsic_width(self, app, height)
2081    }
2082
2083    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
2084        RenderViewportBase::compute_max_intrinsic_width(self, app, height)
2085    }
2086
2087    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
2088        RenderViewportBase::compute_min_intrinsic_height(self, app, width)
2089    }
2090
2091    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
2092        RenderViewportBase::compute_max_intrinsic_height(self, app, width)
2093    }
2094
2095    fn compute_dry_layout(
2096        self: RenderHandle<Self>,
2097        app: &mut App,
2098        constraints: BoxConstraints,
2099    ) -> Size {
2100        debug_assert!(debug_check_has_bounded_axis(self.axis(app), constraints));
2101        constraints.biggest()
2102    }
2103}
2104
2105/// A render object that is bigger on the inside and shrink wraps its children in the main axis.
2106///
2107/// [`RenderShrinkWrappingViewport`] displays a subset of its children according to its own
2108/// dimensions and the given [`RenderViewportBase::offset`]. As the offset varies, different
2109/// children are visible through the viewport.
2110///
2111/// It differs from [`RenderViewport`] in that [`RenderViewport`] expands to fill the main axis
2112/// whereas this shrink-wraps itself to match its children in the main axis. This shrink wrapping
2113/// behavior is expensive because the children, and hence the viewport, could potentially change
2114/// size whenever the offset changes (e.g., because of a collapsing header).
2115///
2116/// [`RenderShrinkWrappingViewport`] cannot contain [`RenderBox`] children directly. Instead, use
2117/// a [`crate::RenderSliverList`], [`crate::RenderSliverFixedExtentList`], or a
2118/// [`crate::RenderSliverToBoxAdapter`], for example.
2119pub struct RenderShrinkWrappingViewport {
2120    render_object: RenderObjectData,
2121    render_box: RenderBoxData,
2122    container: ContainerRenderObjectData<AnyRenderSliver>,
2123    viewport: RenderViewportBaseData,
2124    // Out-of-band data computed during layout.
2125    max_scroll_extent: f64,
2126    shrink_wrap_extent: f64,
2127    has_visual_overflow: bool,
2128}
2129
2130impl RenderShrinkWrappingViewport {
2131    /// Creates a viewport (for [`AnyRenderSliver`] objects) that shrink-wraps its contents.
2132    ///
2133    /// For testing purposes, consider passing a [`crate::FixedViewportOffset`] as the `offset`.
2134    pub fn new(
2135        app: &mut App,
2136        cross_axis_direction: AxisDirection,
2137        offset: ViewportOffsetRef,
2138        children: Option<Vec<AnyRenderSliver>>,
2139    ) -> RenderHandle<RenderShrinkWrappingViewport> {
2140        let this = RenderHandle::new_box(
2141            app,
2142            RenderShrinkWrappingViewport {
2143                render_object: RenderObjectData::new(),
2144                render_box: RenderBoxData::new(),
2145                container: ContainerRenderObjectData::new(),
2146                viewport: RenderViewportBaseData::new(cross_axis_direction, offset),
2147                max_scroll_extent: 0.0,
2148                shrink_wrap_extent: 0.0,
2149                has_visual_overflow: false,
2150            },
2151        );
2152        this.add_all(app, children);
2153        this
2154    }
2155
2156    /// Flutter's `_debugCheckHasBoundedCrossAxis`.
2157    fn debug_check_has_bounded_cross_axis(self: RenderHandle<Self>, app: &App) -> bool {
2158        let constraints = self.constraints(app);
2159        match self.axis(app) {
2160            Axis::Vertical => debug_assert!(
2161                constraints.has_bounded_width(),
2162                "Vertical viewport was given unbounded width.\n\
2163                 Viewports expand in the cross axis to fill their container and constrain their \
2164                 children to match their extent in the cross axis. In this case, a vertical \
2165                 shrinkwrapping viewport was given an unlimited amount of horizontal space in \
2166                 which to expand."
2167            ),
2168            Axis::Horizontal => debug_assert!(
2169                constraints.has_bounded_height(),
2170                "Horizontal viewport was given unbounded height.\n\
2171                 Viewports expand in the cross axis to fill their container and constrain their \
2172                 children to match their extent in the cross axis. In this case, a horizontal \
2173                 shrinkwrapping viewport was given an unlimited amount of vertical space in \
2174                 which to expand."
2175            ),
2176        }
2177        true
2178    }
2179
2180    /// Flutter's `_attemptLayout`.
2181    fn attempt_layout(
2182        self: RenderHandle<Self>,
2183        app: &mut App,
2184        main_axis_extent: f64,
2185        cross_axis_extent: f64,
2186        corrected_offset: f64,
2187    ) -> f64 {
2188        // We can't assert main_axis_extent is finite, because it could be infinite if it is
2189        // within a column or row for example. In such a case, there's not even any scrolling to
2190        // do, although some scroll physics could still temporarily scroll the content in a
2191        // simulation.
2192        debug_assert!(!main_axis_extent.is_nan());
2193        debug_assert!(main_axis_extent >= 0.0);
2194        debug_assert!(cross_axis_extent.is_finite());
2195        debug_assert!(cross_axis_extent >= 0.0);
2196        debug_assert!(corrected_offset.is_finite());
2197        let this = self.get_mut(app);
2198        this.max_scroll_extent = 0.0;
2199        this.shrink_wrap_extent = 0.0;
2200        // Since the viewport is shrinkwrapped, we know that any negative overscroll into the
2201        // potentially infinite main_axis_extent will overflow the end of the viewport.
2202        this.has_visual_overflow = corrected_offset < 0.0;
2203        let calculated_cache_extent = if main_axis_extent.is_finite() {
2204            self.scroll_cache_extent(app)
2205                .calculate_cache_offset(main_axis_extent)
2206        } else {
2207            // If main_axis_extent is infinite, it builds everything anyway, so we don't need any
2208            // extra cache.
2209            0.0
2210        };
2211        self.viewport_data_mut(app).calculated_cache_extent = Some(calculated_cache_extent);
2212
2213        let first_child = self.first_child(app);
2214        self.layout_child_sequence(
2215            app,
2216            first_child,
2217            corrected_offset.max(0.0),
2218            corrected_offset.min(0.0),
2219            (-corrected_offset).max(0.0),
2220            main_axis_extent + corrected_offset.min(0.0),
2221            main_axis_extent,
2222            cross_axis_extent,
2223            GrowthDirection::Forward,
2224            &|this, app, child| this.child_after(app, child),
2225            main_axis_extent + 2.0 * calculated_cache_extent,
2226            -calculated_cache_extent,
2227        )
2228    }
2229}
2230
2231impl ContainerRenderObjectMixin for RenderShrinkWrappingViewport {
2232    type ChildType = AnyRenderSliver;
2233    type ParentDataType = SliverLogicalContainerParentData;
2234
2235    fn container_data(
2236        self: RenderHandle<Self>,
2237        app: &App,
2238    ) -> &ContainerRenderObjectData<AnyRenderSliver> {
2239        &self.get(app).container
2240    }
2241
2242    fn container_data_mut(
2243        self: RenderHandle<Self>,
2244        app: &mut App,
2245    ) -> &mut ContainerRenderObjectData<AnyRenderSliver> {
2246        &mut self.get_mut(app).container
2247    }
2248}
2249
2250impl RenderViewportBase for RenderShrinkWrappingViewport {
2251    crate::render_viewport_base_accessors!();
2252
2253    fn debug_throw_if_not_checking_intrinsics(self: RenderHandle<Self>) -> bool {
2254        let _ = self;
2255        debug_assert!(
2256            debug_checking_intrinsics(),
2257            "{} does not support returning intrinsic dimensions.\n\
2258             Calculating the intrinsic dimensions would require instantiating every child of \
2259             the viewport, which defeats the point of viewports being lazy.\n\
2260             If you are merely trying to shrink-wrap the viewport in the main axis direction, \
2261             you should be able to achieve that effect by just giving the viewport loose \
2262             constraints, without needing to measure its intrinsic dimensions.",
2263            std::any::type_name::<Self>()
2264        );
2265        true
2266    }
2267
2268    fn has_visual_overflow(self: RenderHandle<Self>, app: &App) -> bool {
2269        self.get(app).has_visual_overflow
2270    }
2271
2272    fn update_out_of_band_data(
2273        self: RenderHandle<Self>,
2274        app: &mut App,
2275        growth_direction: GrowthDirection,
2276        child_layout_geometry: SliverGeometry,
2277    ) {
2278        debug_assert_eq!(growth_direction, GrowthDirection::Forward);
2279        let this = self.get_mut(app);
2280        this.max_scroll_extent += child_layout_geometry.scroll_extent;
2281        if child_layout_geometry.has_visual_overflow {
2282            this.has_visual_overflow = true;
2283        }
2284        this.shrink_wrap_extent += child_layout_geometry.max_paint_extent;
2285    }
2286
2287    fn update_child_layout_offset(
2288        self: RenderHandle<Self>,
2289        app: &mut App,
2290        child: AnyRenderSliver,
2291        layout_offset: f64,
2292        growth_direction: GrowthDirection,
2293    ) {
2294        debug_assert_eq!(growth_direction, GrowthDirection::Forward);
2295        child
2296            .as_object()
2297            .parent_data_of_mut::<SliverLogicalContainerParentData>(app)
2298            .set_layout_offset(Some(layout_offset));
2299    }
2300
2301    fn paint_offset_of(self: RenderHandle<Self>, app: &App, child: AnyRenderSliver) -> Offset {
2302        let layout_offset = child
2303            .as_object()
2304            .parent_data_of::<SliverLogicalContainerParentData>(app)
2305            .layout_offset()
2306            .expect("a laid-out child has a layout offset");
2307        self.compute_absolute_paint_offset(app, child, layout_offset, GrowthDirection::Forward)
2308    }
2309
2310    fn scroll_offset_of(
2311        self: RenderHandle<Self>,
2312        app: &App,
2313        child: AnyRenderSliver,
2314        scroll_offset_within_child: f64,
2315    ) -> f64 {
2316        debug_assert_eq!(child.as_object().parent(app), Some(self.as_object()));
2317        debug_assert_eq!(
2318            child.constraints(app).growth_direction,
2319            GrowthDirection::Forward
2320        );
2321        let mut scroll_offset_to_child = 0.0;
2322        let mut current = self.first_child(app);
2323        while current != Some(child) {
2324            let sliver = current.expect("child is in the child list");
2325            scroll_offset_to_child += sliver.geometry(app).scroll_extent;
2326            current = self.child_after(app, sliver);
2327        }
2328        scroll_offset_to_child + scroll_offset_within_child
2329    }
2330
2331    fn max_scroll_obstruction_extent_before(
2332        self: RenderHandle<Self>,
2333        app: &App,
2334        child: AnyRenderSliver,
2335    ) -> f64 {
2336        debug_assert_eq!(child.as_object().parent(app), Some(self.as_object()));
2337        debug_assert_eq!(
2338            child.constraints(app).growth_direction,
2339            GrowthDirection::Forward
2340        );
2341        let mut pinned_extent = 0.0;
2342        let mut current = self.first_child(app);
2343        while current != Some(child) {
2344            let sliver = current.expect("child is in the child list");
2345            pinned_extent += sliver.geometry(app).max_scroll_obstruction_extent;
2346            current = self.child_after(app, sliver);
2347        }
2348        pinned_extent
2349    }
2350
2351    fn compute_child_main_axis_position(
2352        self: RenderHandle<Self>,
2353        app: &App,
2354        child: AnyRenderSliver,
2355        parent_main_axis_position: f64,
2356    ) -> f64 {
2357        debug_assert!(self.has_size(app));
2358        let layout_offset = child
2359            .as_object()
2360            .parent_data_of::<SliverLogicalContainerParentData>(app)
2361            .layout_offset()
2362            .expect("a laid-out child has a layout offset");
2363        let constraints = child.constraints(app);
2364        let size = self.size(app);
2365        match apply_growth_direction_to_axis_direction(
2366            constraints.axis_direction,
2367            constraints.growth_direction,
2368        ) {
2369            AxisDirection::Down | AxisDirection::Right => parent_main_axis_position - layout_offset,
2370            AxisDirection::Up => size.height() - parent_main_axis_position - layout_offset,
2371            AxisDirection::Left => size.width() - parent_main_axis_position - layout_offset,
2372        }
2373    }
2374
2375    fn index_of_first_child(self: RenderHandle<Self>, _app: &App) -> i32 {
2376        let _ = self;
2377        0
2378    }
2379
2380    fn label_for_child(self: RenderHandle<Self>, index: i32) -> String {
2381        let _ = self;
2382        format!("child {index}")
2383    }
2384}
2385
2386impl RenderAbstractViewport for RenderShrinkWrappingViewport {
2387    fn get_offset_to_reveal(
2388        self: RenderHandle<Self>,
2389        app: &App,
2390        target: AnyRenderObject,
2391        alignment: f64,
2392        rect: Option<Rect>,
2393        axis: Option<Axis>,
2394    ) -> RevealedOffset {
2395        RenderViewportBase::get_offset_to_reveal(self, app, target, alignment, rect, axis)
2396    }
2397}
2398
2399impl RenderObject for RenderShrinkWrappingViewport {
2400    crate::render_object_accessors!();
2401
2402    fn visit_children(
2403        self: RenderHandle<Self>,
2404        app: &App,
2405        visitor: &mut dyn FnMut(AnyRenderObject),
2406    ) {
2407        ContainerRenderObjectMixin::visit_children(self, app, visitor)
2408    }
2409
2410    fn did_attach(
2411        self: RenderHandle<Self>,
2412        app: &mut App,
2413        owner: waft_foundation::Handle<PipelineOwner>,
2414    ) {
2415        RenderViewportBase::did_attach(self, app, owner)
2416    }
2417
2418    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
2419        RenderViewportBase::did_detach(self, app)
2420    }
2421
2422    fn redepth_children(self: RenderHandle<Self>, app: &mut App) {
2423        ContainerRenderObjectMixin::redepth_children(self, app)
2424    }
2425
2426    fn is_repaint_boundary(self: RenderHandle<Self>, _app: &App) -> bool {
2427        let _ = self;
2428        true
2429    }
2430
2431    fn interface(self: RenderHandle<Self>, id: TypeId) -> Option<Box<dyn Any>> {
2432        (id == TypeId::of::<AnyRenderAbstractViewport>())
2433            .then(|| Box::new(self.as_abstract_viewport()) as Box<dyn Any>)
2434    }
2435
2436    fn debug_fill_properties(
2437        self: RenderHandle<Self>,
2438        app: &App,
2439        properties: &mut DiagnosticPropertiesBuilder,
2440    ) {
2441        RenderViewportBase::debug_fill_properties(self, app, properties);
2442    }
2443
2444    fn debug_describe_children(
2445        self: RenderHandle<Self>,
2446        app: &App,
2447    ) -> Vec<Rc<dyn DiagnosticsNode>> {
2448        RenderViewportBase::debug_describe_children(self, app)
2449    }
2450
2451    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
2452        let constraints = self.constraints(app);
2453        let offset = self.offset(app);
2454        if self.first_child(app).is_none() {
2455            // Shrinkwrapping viewport only requires the cross axis to be bounded.
2456            debug_assert!(self.debug_check_has_bounded_cross_axis(app));
2457            let size = match self.axis(app) {
2458                Axis::Vertical => Size::new(constraints.max_width, constraints.min_height),
2459                Axis::Horizontal => Size::new(constraints.min_width, constraints.max_height),
2460            };
2461            self.set_size(app, size);
2462            offset.apply_viewport_dimension(app, 0.0);
2463            let this = self.get_mut(app);
2464            this.max_scroll_extent = 0.0;
2465            this.shrink_wrap_extent = 0.0;
2466            this.has_visual_overflow = false;
2467            offset.apply_content_dimensions(app, 0.0, 0.0);
2468            return;
2469        }
2470
2471        // Shrinkwrapping viewport only requires the cross axis to be bounded.
2472        debug_assert!(self.debug_check_has_bounded_cross_axis(app));
2473        let (main_axis_extent, cross_axis_extent) = match self.axis(app) {
2474            Axis::Vertical => (constraints.max_height, constraints.max_width),
2475            Axis::Horizontal => (constraints.max_width, constraints.max_height),
2476        };
2477
2478        let effective_extent;
2479        loop {
2480            let corrected_offset = offset.pixels(app);
2481            let correction =
2482                self.attempt_layout(app, main_axis_extent, cross_axis_extent, corrected_offset);
2483            if correction != 0.0 {
2484                offset.correct_by(app, correction);
2485                continue;
2486            }
2487            let shrink_wrap_extent = self.get(app).shrink_wrap_extent;
2488            let extent = match self.axis(app) {
2489                Axis::Vertical => constraints.constrain_height(shrink_wrap_extent),
2490                Axis::Horizontal => constraints.constrain_width(shrink_wrap_extent),
2491            };
2492            let did_accept_viewport_dimension = offset.apply_viewport_dimension(app, extent);
2493            let max_scroll_extent = self.get(app).max_scroll_extent;
2494            let did_accept_content_dimension =
2495                offset.apply_content_dimensions(app, 0.0, (max_scroll_extent - extent).max(0.0));
2496            if did_accept_viewport_dimension && did_accept_content_dimension {
2497                effective_extent = extent;
2498                break;
2499            }
2500        }
2501        let size = match self.axis(app) {
2502            Axis::Vertical => constraints.constrain_dimensions(cross_axis_extent, effective_extent),
2503            Axis::Horizontal => {
2504                constraints.constrain_dimensions(effective_extent, cross_axis_extent)
2505            }
2506        };
2507        self.set_size(app, size);
2508    }
2509
2510    fn paint(
2511        self: RenderHandle<Self>,
2512        app: &mut App,
2513        context: &mut PaintingContext,
2514        offset: Offset,
2515    ) {
2516        RenderViewportBase::paint(self, app, context, offset)
2517    }
2518
2519    fn dispose(self: RenderHandle<Self>, app: &mut App) {
2520        RenderViewportBase::dispose(self, app)
2521    }
2522
2523    fn describe_approximate_paint_clip(
2524        self: RenderHandle<Self>,
2525        app: &App,
2526        child: AnyRenderObject,
2527    ) -> Option<Rect> {
2528        RenderViewportBase::describe_approximate_paint_clip(
2529            self,
2530            app,
2531            child
2532                .as_sliver()
2533                .expect("a viewport's children are slivers"),
2534        )
2535    }
2536
2537    fn show_on_screen(
2538        self: RenderHandle<Self>,
2539        app: &mut App,
2540        descendant: Option<AnyRenderObject>,
2541        rect: Option<Rect>,
2542        duration: Duration,
2543        curve: Rc<dyn Curve>,
2544    ) {
2545        RenderViewportBase::show_on_screen(self, app, descendant, rect, duration, curve)
2546    }
2547}
2548
2549impl RenderBox for RenderShrinkWrappingViewport {
2550    crate::render_box_accessors!();
2551
2552    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
2553        if !child.parent_data_is::<SliverLogicalContainerParentData>(app) {
2554            child.set_parent_data(app, SliverLogicalContainerParentData::new());
2555        }
2556    }
2557
2558    fn apply_paint_transform(
2559        self: RenderHandle<Self>,
2560        app: &App,
2561        child: AnyRenderObject,
2562        transform: &mut Matrix4,
2563    ) {
2564        // Hit test logic relies on this always providing an invertible matrix.
2565        let offset = self.paint_offset_of(
2566            app,
2567            child
2568                .as_sliver()
2569                .expect("a viewport's children are slivers"),
2570        );
2571        translate(transform, offset.dx(), offset.dy());
2572    }
2573
2574    fn hit_test_children(
2575        self: RenderHandle<Self>,
2576        app: &mut App,
2577        result: &mut BoxHitTestResult<'_>,
2578        position: Offset,
2579    ) -> bool {
2580        RenderViewportBase::hit_test_children(self, app, result, position)
2581    }
2582
2583    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
2584        RenderViewportBase::compute_min_intrinsic_width(self, app, height)
2585    }
2586
2587    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
2588        RenderViewportBase::compute_max_intrinsic_width(self, app, height)
2589    }
2590
2591    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
2592        RenderViewportBase::compute_min_intrinsic_height(self, app, width)
2593    }
2594
2595    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
2596        RenderViewportBase::compute_max_intrinsic_height(self, app, width)
2597    }
2598}
2599
2600#[cfg(test)]
2601mod tests {
2602    use std::cell::Cell;
2603    use std::rc::Rc;
2604    use waft_foundation::AppCell;
2605    use waft_foundation::Ref;
2606
2607    use waft_gestures::HitTestResult;
2608    use waft_painting::AlignmentGeometry;
2609
2610    use super::*;
2611    use crate::box_::BoxConstraints;
2612    use crate::proxy_box::RenderConstrainedBox;
2613    use crate::sliver::{RenderSliver, RenderSliverToBoxAdapter};
2614    use crate::testing::{EnginePhase, layout_with, pump_frame};
2615    use crate::viewport_offset::FixedViewportOffset;
2616    use waft_foundation::DiagnosticLevel;
2617
2618    /// Dart's `equalsIgnoringHashCodes`: every `#` and five hex digits read as `#00000`.
2619    fn ignoring_hash_codes(text: &str) -> String {
2620        let mut out = String::with_capacity(text.len());
2621        let mut rest = text;
2622        while let Some(at) = rest.find('#') {
2623            out.push_str(&rest[..at]);
2624            let hash = &rest[at + 1..];
2625            let digits = hash.chars().take_while(char::is_ascii_hexdigit).count();
2626            if digits == 5 {
2627                out.push_str("#00000");
2628                rest = &hash[5..];
2629            } else {
2630                out.push('#');
2631                rest = hash;
2632            }
2633        }
2634        out.push_str(rest);
2635        out
2636    }
2637
2638    /// A sliver of a fixed scroll extent that records the offsets it was painted at.
2639    struct TestSliver {
2640        render_object: RenderObjectData,
2641        render_sliver: crate::sliver::RenderSliverData,
2642        extent: f64,
2643        paint_offsets: Rc<Cell<Vec<Offset>>>,
2644    }
2645
2646    impl RenderObject for TestSliver {
2647        crate::render_object_accessors!();
2648
2649        fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
2650            let constraints = self.constraints(app);
2651            let extent = self.get(app).extent;
2652            let painted = self.calculate_paint_offset(app, constraints, 0.0, extent);
2653            let cached = self.calculate_cache_offset(app, constraints, 0.0, extent);
2654            self.set_geometry(
2655                app,
2656                SliverGeometry::builder()
2657                    .scroll_extent(extent)
2658                    .paint_extent(painted)
2659                    .cache_extent(cached)
2660                    .max_paint_extent(extent)
2661                    .build(),
2662            );
2663        }
2664
2665        fn paint(
2666            self: RenderHandle<Self>,
2667            app: &mut App,
2668            _context: &mut PaintingContext,
2669            offset: Offset,
2670        ) {
2671            let recorded = self.get(app).paint_offsets.clone();
2672            let mut offsets = recorded.take();
2673            offsets.push(offset);
2674            recorded.set(offsets);
2675        }
2676    }
2677
2678    impl RenderSliver for TestSliver {
2679        crate::render_sliver_accessors!();
2680
2681        fn hit_test_self(
2682            self: RenderHandle<Self>,
2683            _app: &App,
2684            _main_axis_position: f64,
2685            _cross_axis_position: f64,
2686        ) -> bool {
2687            let _ = self;
2688            true
2689        }
2690    }
2691
2692    fn test_sliver(app: &mut App, extent: f64) -> (AnyRenderSliver, Rc<Cell<Vec<Offset>>>) {
2693        let paint_offsets = Rc::new(Cell::new(Vec::new()));
2694        let sliver = RenderHandle::new_sliver(
2695            app,
2696            TestSliver {
2697                render_object: RenderObjectData::new(),
2698                render_sliver: crate::sliver::RenderSliverData::new(),
2699                extent,
2700                paint_offsets: paint_offsets.clone(),
2701            },
2702        )
2703        .as_sliver();
2704        (sliver, paint_offsets)
2705    }
2706
2707    fn vertical_viewport(
2708        app: &mut App,
2709        offset: &Ref<FixedViewportOffset>,
2710        children: Vec<AnyRenderSliver>,
2711    ) -> RenderHandle<RenderViewport> {
2712        RenderViewport::new(
2713            app,
2714            AxisDirection::Right,
2715            offset.erase(),
2716            Some(children),
2717            None,
2718        )
2719    }
2720
2721    /// `slivers_test.dart`'s 'RenderViewport basic test - no children': before layout the
2722    /// viewport prints its axis directions, its offset and its anchor. Waft's fixed offset is
2723    /// `FixedViewportOffset`, where Dart's private class prints `_FixedViewportOffset`.
2724    #[test]
2725    fn a_viewport_dump_shows_its_axis_directions_offset_and_anchor() {
2726        let cell = AppCell::new();
2727        let mut app = cell.borrow_mut();
2728        let offset = FixedViewportOffset::zero(&mut app);
2729        let viewport =
2730            RenderViewport::new(&mut app, AxisDirection::Right, offset.erase(), None, None);
2731
2732        assert_eq!(
2733            ignoring_hash_codes(
2734                &viewport
2735                    .as_object()
2736                    .to_string_deep_with(&app, DiagnosticLevel::Info)
2737            ),
2738            ignoring_hash_codes(concat!(
2739                "RenderViewport#00002 NEEDS-LAYOUT NEEDS-PAINT DETACHED\n",
2740                "   needs compositing\n",
2741                "   parentData: MISSING\n",
2742                "   constraints: MISSING\n",
2743                "   size: MISSING\n",
2744                "   axisDirection: down\n",
2745                "   crossAxisDirection: right\n",
2746                "   offset: FixedViewportOffset#00001(offset: 0.0)\n",
2747                "   anchor: 0.0\n"
2748            )),
2749        );
2750
2751        layout_with(
2752            &mut app,
2753            viewport.as_box(),
2754            Some(BoxConstraints::tight(Size::new(800.0, 600.0))),
2755            AlignmentGeometry::CENTER,
2756            EnginePhase::Paint,
2757        );
2758        let new_offset = FixedViewportOffset::new(&mut app, 900.0);
2759        viewport.set_offset(&mut app, new_offset.erase());
2760
2761        // `slivers_test.dart` expects `NEEDS-LAYOUT NEEDS-PAINT` and no `layer` line; Waft's
2762        // viewport paints a layer in the layout helper and setting the offset marks layout only.
2763        assert_eq!(
2764            ignoring_hash_codes(
2765                &viewport
2766                    .as_object()
2767                    .to_string_deep_with(&app, DiagnosticLevel::Info)
2768            ),
2769            ignoring_hash_codes(concat!(
2770                "RenderViewport#00002 NEEDS-LAYOUT\n",
2771                "   needs compositing\n",
2772                "   parentData: <none> (can use size)\n",
2773                "   constraints: BoxConstraints(w=800.0, h=600.0)\n",
2774                "   layer: OffsetLayer#0000c\n",
2775                "   size: Size(800.0, 600.0)\n",
2776                "   axisDirection: down\n",
2777                "   crossAxisDirection: right\n",
2778                "   offset: FixedViewportOffset#0000d(offset: 900.0)\n",
2779                "   anchor: 0.0\n"
2780            )),
2781        );
2782    }
2783
2784    /// `slivers_test.dart`'s 'RenderViewport basic test - down': the viewport names its center
2785    /// child and numbers the others from it, and each sliver prints its geometry in full.
2786    #[test]
2787    fn a_viewport_dump_names_its_center_child_and_numbers_the_others() {
2788        let cell = AppCell::new();
2789        let mut app = cell.borrow_mut();
2790        let (first, _) = test_sliver(&mut app, 400.0);
2791        let (second, _) = test_sliver(&mut app, 400.0);
2792        let offset = FixedViewportOffset::zero(&mut app);
2793        let viewport = vertical_viewport(&mut app, &offset, vec![first, second]);
2794        layout_with(
2795            &mut app,
2796            viewport.as_box(),
2797            Some(BoxConstraints::tight(Size::new(800.0, 600.0))),
2798            AlignmentGeometry::CENTER,
2799            EnginePhase::Paint,
2800        );
2801
2802        let dump = viewport
2803            .as_object()
2804            .to_string_deep_with(&app, DiagnosticLevel::Info);
2805        assert!(
2806            dump.lines()
2807                .any(|line| line.contains("center child: TestSliver#")),
2808            "{dump}"
2809        );
2810        assert!(
2811            dump.lines()
2812                .any(|line| line.contains("child 1: TestSliver#")),
2813            "{dump}"
2814        );
2815        assert!(
2816            dump.contains("geometry: SliverGeometry(scrollExtent: 400.0, paintExtent: 400.0,"),
2817            "{dump}"
2818        );
2819        assert!(
2820            dump.contains("geometry: SliverGeometry(scrollExtent: 400.0, paintExtent: 200.0,"),
2821            "{dump}"
2822        );
2823    }
2824
2825    /// `viewport_test.dart`: a viewport does not support intrinsics, because answering would
2826    /// mean instantiating every child.
2827    #[test]
2828    #[should_panic(expected = "does not support returning intrinsic dimensions")]
2829    fn a_viewport_has_no_intrinsic_dimensions() {
2830        let cell = AppCell::new();
2831        let mut app = cell.borrow_mut();
2832        let offset = FixedViewportOffset::zero(&mut app);
2833        let viewport = vertical_viewport(&mut app, &offset, vec![]);
2834        viewport.as_box().get_min_intrinsic_width(&mut app, 0.0);
2835    }
2836
2837    /// While the framework is checking intrinsics, a viewport answers zero instead of panicking.
2838    #[test]
2839    fn a_viewport_reports_zero_intrinsics_while_checking_them() {
2840        let cell = AppCell::new();
2841        let mut app = cell.borrow_mut();
2842        let offset = FixedViewportOffset::zero(&mut app);
2843        let viewport = vertical_viewport(&mut app, &offset, vec![]);
2844        crate::object::set_debug_checking_intrinsics(true);
2845        let width = viewport.as_box().get_min_intrinsic_width(&mut app, 0.0);
2846        let height = viewport.as_box().get_max_intrinsic_height(&mut app, 0.0);
2847        crate::object::set_debug_checking_intrinsics(false);
2848        assert_eq!((width, height), (0.0, 0.0));
2849    }
2850
2851    /// A viewport is sized by its parent: its dry layout is the biggest size the constraints
2852    /// allow, and that is the size it takes.
2853    #[test]
2854    fn a_viewport_dry_layout_is_the_biggest_size() {
2855        let cell = AppCell::new();
2856        let mut app = cell.borrow_mut();
2857        let (sliver, _paints) = test_sliver(&mut app, 100.0);
2858        let offset = FixedViewportOffset::zero(&mut app);
2859        let viewport = vertical_viewport(&mut app, &offset, vec![sliver]);
2860        let constraints = BoxConstraints::new().max_width(200.0).max_height(400.0);
2861        let dry = viewport.as_box().get_dry_layout(&mut app, constraints);
2862        layout_with(
2863            &mut app,
2864            viewport.as_box(),
2865            Some(constraints),
2866            AlignmentGeometry::CENTER,
2867            EnginePhase::Paint,
2868        );
2869        assert_eq!(dry, Size::new(200.0, 400.0));
2870        assert_eq!(dry, viewport.size(&app));
2871    }
2872
2873    /// `viewport_test.dart`: the slivers are laid out one after the other from the leading edge,
2874    /// and the viewport reports the total scroll extent to its offset.
2875    #[test]
2876    fn a_viewport_lays_its_slivers_out_in_order() {
2877        let cell = AppCell::new();
2878        let mut app = cell.borrow_mut();
2879        let (first, first_paints) = test_sliver(&mut app, 100.0);
2880        let (second, second_paints) = test_sliver(&mut app, 300.0);
2881        let offset = FixedViewportOffset::zero(&mut app);
2882        let viewport = vertical_viewport(&mut app, &offset, vec![first, second]);
2883
2884        layout_with(
2885            &mut app,
2886            viewport.as_box(),
2887            Some(BoxConstraints::tight(Size::new(200.0, 400.0))),
2888            AlignmentGeometry::CENTER,
2889            EnginePhase::Paint,
2890        );
2891
2892        assert_eq!(viewport.size(&app), Size::new(200.0, 400.0));
2893        assert_eq!(viewport.center(&app), Some(first));
2894        assert_eq!(first.geometry(&app).paint_extent, 100.0);
2895        assert_eq!(second.geometry(&app).paint_extent, 300.0);
2896        assert_eq!(viewport.paint_offset_of(&app, first), Offset::ZERO);
2897        assert_eq!(
2898            viewport.paint_offset_of(&app, second),
2899            Offset::new(0.0, 100.0)
2900        );
2901        assert_eq!(first_paints.take(), vec![Offset::ZERO]);
2902        assert_eq!(second_paints.take(), vec![Offset::new(0.0, 100.0)]);
2903    }
2904
2905    /// A non-zero offset scrolls the content: the first sliver is partly scrolled off and the
2906    /// second moves up by the same amount.
2907    #[test]
2908    fn a_scrolled_viewport_moves_its_slivers() {
2909        let cell = AppCell::new();
2910        let mut app = cell.borrow_mut();
2911        let (first, _) = test_sliver(&mut app, 100.0);
2912        let (second, _) = test_sliver(&mut app, 300.0);
2913        let offset = FixedViewportOffset::new(&mut app, 60.0);
2914        let viewport = vertical_viewport(&mut app, &offset, vec![first, second]);
2915
2916        layout_with(
2917            &mut app,
2918            viewport.as_box(),
2919            Some(BoxConstraints::tight(Size::new(200.0, 400.0))),
2920            AlignmentGeometry::CENTER,
2921            EnginePhase::Paint,
2922        );
2923
2924        assert_eq!(first.constraints(&app).scroll_offset, 60.0);
2925        assert_eq!(first.geometry(&app).paint_extent, 40.0);
2926        assert_eq!(viewport.paint_offset_of(&app, first), Offset::ZERO);
2927        assert_eq!(
2928            viewport.paint_offset_of(&app, second),
2929            Offset::new(0.0, 40.0)
2930        );
2931        assert_eq!(viewport.scroll_offset_of(&app, second, 0.0), 100.0);
2932    }
2933
2934    /// A hit lands on the sliver that covers the position, in the viewport's coordinate system.
2935    #[test]
2936    fn a_viewport_hit_tests_the_sliver_under_the_position() {
2937        let cell = AppCell::new();
2938        let mut app = cell.borrow_mut();
2939        let (first, _) = test_sliver(&mut app, 100.0);
2940        let (second, _) = test_sliver(&mut app, 300.0);
2941        let offset = FixedViewportOffset::zero(&mut app);
2942        let viewport = vertical_viewport(&mut app, &offset, vec![first, second]);
2943        layout_with(
2944            &mut app,
2945            viewport.as_box(),
2946            Some(BoxConstraints::tight(Size::new(200.0, 400.0))),
2947            AlignmentGeometry::CENTER,
2948            EnginePhase::Paint,
2949        );
2950
2951        let mut result = HitTestResult::new();
2952        let hit = viewport.hit_test(
2953            &mut app,
2954            &mut BoxHitTestResult::wrap(&mut result),
2955            Offset::new(20.0, 150.0),
2956        );
2957
2958        assert!(hit);
2959        assert_eq!(result.path().len(), 2);
2960        // The viewport and the second sliver, which starts at 100.
2961        assert_eq!(
2962            viewport.compute_child_main_axis_position(&app, second, 150.0),
2963            50.0
2964        );
2965    }
2966
2967    /// A sliver's hit test entry carries the viewport's paint transform, so pointer events
2968    /// reach it in its own coordinates.
2969    #[test]
2970    fn a_sliver_hit_entry_maps_into_the_sliver() {
2971        let cell = AppCell::new();
2972        let mut app = cell.borrow_mut();
2973        let (first, _) = test_sliver(&mut app, 100.0);
2974        let (second, _) = test_sliver(&mut app, 300.0);
2975        let offset = FixedViewportOffset::zero(&mut app);
2976        let viewport = vertical_viewport(&mut app, &offset, vec![first, second]);
2977        layout_with(
2978            &mut app,
2979            viewport.as_box(),
2980            Some(BoxConstraints::tight(Size::new(200.0, 400.0))),
2981            AlignmentGeometry::CENTER,
2982            EnginePhase::Paint,
2983        );
2984
2985        let mut result = HitTestResult::new();
2986        viewport.hit_test(
2987            &mut app,
2988            &mut BoxHitTestResult::wrap(&mut result),
2989            Offset::new(20.0, 150.0),
2990        );
2991
2992        let transform = result.path()[0].transform().unwrap();
2993        assert_eq!(
2994            waft_painting::transform_point(&transform, Offset::new(20.0, 150.0)),
2995            Offset::new(20.0, 50.0)
2996        );
2997    }
2998
2999    /// The cache extent widens the region slivers are asked to lay out for.
3000    #[test]
3001    fn the_cache_extent_widens_the_laid_out_region() {
3002        let cell = AppCell::new();
3003        let mut app = cell.borrow_mut();
3004        let (sliver, _) = test_sliver(&mut app, 1000.0);
3005        let offset = FixedViewportOffset::zero(&mut app);
3006        let viewport = vertical_viewport(&mut app, &offset, vec![sliver]);
3007        viewport.set_scroll_cache_extent(&mut app, Some(ScrollCacheExtent::Pixels(100.0)));
3008
3009        layout_with(
3010            &mut app,
3011            viewport.as_box(),
3012            Some(BoxConstraints::tight(Size::new(200.0, 400.0))),
3013            AlignmentGeometry::CENTER,
3014            EnginePhase::Paint,
3015        );
3016
3017        assert_eq!(sliver.constraints(&app).remaining_cache_extent, 500.0);
3018        assert_eq!(sliver.geometry(&app).cache_extent, 500.0);
3019        assert_eq!(sliver.geometry(&app).paint_extent, 400.0);
3020
3021        viewport.set_scroll_cache_extent(&mut app, Some(ScrollCacheExtent::Viewport(0.5)));
3022        pump_frame(&mut app, EnginePhase::Layout);
3023        assert_eq!(sliver.constraints(&app).remaining_cache_extent, 600.0);
3024    }
3025
3026    /// `RenderShrinkWrappingViewport` sizes itself to the total extent of its slivers, up to the
3027    /// incoming constraints.
3028    #[test]
3029    fn a_shrink_wrapping_viewport_sizes_itself_to_its_slivers() {
3030        let cell = AppCell::new();
3031        let mut app = cell.borrow_mut();
3032        let (first, _) = test_sliver(&mut app, 60.0);
3033        let (second, _) = test_sliver(&mut app, 90.0);
3034        let offset = FixedViewportOffset::zero(&mut app);
3035        let viewport = RenderShrinkWrappingViewport::new(
3036            &mut app,
3037            AxisDirection::Right,
3038            offset.erase(),
3039            Some(vec![first, second]),
3040        );
3041
3042        layout_with(
3043            &mut app,
3044            viewport.as_box(),
3045            Some(
3046                BoxConstraints::new()
3047                    .max_width(200.0)
3048                    .min_width(200.0)
3049                    .max_height(400.0),
3050            ),
3051            AlignmentGeometry::CENTER,
3052            EnginePhase::Paint,
3053        );
3054
3055        assert_eq!(viewport.size(&app), Size::new(200.0, 150.0));
3056        assert_eq!(
3057            viewport.paint_offset_of(&app, second),
3058            Offset::new(0.0, 60.0)
3059        );
3060        assert_eq!(viewport.index_of_first_child(&app), 0);
3061        assert_eq!(viewport.label_for_child(1), "child 1");
3062    }
3063
3064    /// A box adapter inside a viewport reaches the box protocol: the box is laid out with the
3065    /// viewport's cross axis extent and painted at the sliver's paint offset.
3066    #[test]
3067    fn a_viewport_hosts_a_box_through_the_adapter() {
3068        let cell = AppCell::new();
3069        let mut app = cell.borrow_mut();
3070        let child =
3071            RenderConstrainedBox::new(&mut app, BoxConstraints::tight_for(None, Some(80.0)), None);
3072        let adapter = RenderSliverToBoxAdapter::new(&mut app, Some(child.as_box()));
3073        let offset = FixedViewportOffset::zero(&mut app);
3074        let viewport = vertical_viewport(&mut app, &offset, vec![adapter.as_sliver()]);
3075
3076        layout_with(
3077            &mut app,
3078            viewport.as_box(),
3079            Some(BoxConstraints::tight(Size::new(200.0, 400.0))),
3080            AlignmentGeometry::CENTER,
3081            EnginePhase::Paint,
3082        );
3083
3084        assert_eq!(child.size(&app), Size::new(200.0, 80.0));
3085        assert_eq!(adapter.geometry(&app).scroll_extent, 80.0);
3086        assert_eq!(
3087            child
3088                .as_box()
3089                .local_to_global(&app, Offset::ZERO, Some(viewport.as_object())),
3090            Offset::ZERO
3091        );
3092    }
3093
3094    /// The viewport is the `RenderAbstractViewport` that `maybe_of` finds from a descendant.
3095    #[test]
3096    fn maybe_of_finds_the_enclosing_viewport() {
3097        let cell = AppCell::new();
3098        let mut app = cell.borrow_mut();
3099        let child =
3100            RenderConstrainedBox::new(&mut app, BoxConstraints::tight_for(None, Some(80.0)), None);
3101        let adapter = RenderSliverToBoxAdapter::new(&mut app, Some(child.as_box()));
3102        let offset = FixedViewportOffset::zero(&mut app);
3103        let viewport = vertical_viewport(&mut app, &offset, vec![adapter.as_sliver()]);
3104        layout_with(
3105            &mut app,
3106            viewport.as_box(),
3107            Some(BoxConstraints::tight(Size::new(200.0, 400.0))),
3108            AlignmentGeometry::CENTER,
3109            EnginePhase::Paint,
3110        );
3111
3112        let found = AnyRenderAbstractViewport::maybe_of(&app, Some(child.as_object()));
3113        assert_eq!(found, Some(viewport.as_abstract_viewport()));
3114        assert!(AnyRenderAbstractViewport::maybe_of(&app, None).is_none());
3115    }
3116
3117    /// `get_offset_to_reveal` reports the offset that brings a descendant box to the leading edge.
3118    #[test]
3119    fn get_offset_to_reveal_reports_the_leading_edge_offset() {
3120        let cell = AppCell::new();
3121        let mut app = cell.borrow_mut();
3122        let leading =
3123            RenderConstrainedBox::new(&mut app, BoxConstraints::tight_for(None, Some(100.0)), None);
3124        let first = RenderSliverToBoxAdapter::new(&mut app, Some(leading.as_box()));
3125        let target =
3126            RenderConstrainedBox::new(&mut app, BoxConstraints::tight_for(None, Some(50.0)), None);
3127        let second = RenderSliverToBoxAdapter::new(&mut app, Some(target.as_box()));
3128        let offset = FixedViewportOffset::zero(&mut app);
3129        let viewport = vertical_viewport(
3130            &mut app,
3131            &offset,
3132            vec![first.as_sliver(), second.as_sliver()],
3133        );
3134        layout_with(
3135            &mut app,
3136            viewport.as_box(),
3137            Some(BoxConstraints::tight(Size::new(200.0, 400.0))),
3138            AlignmentGeometry::CENTER,
3139            EnginePhase::Paint,
3140        );
3141
3142        let revealed = RenderAbstractViewport::get_offset_to_reveal(
3143            viewport,
3144            &app,
3145            target.as_object(),
3146            0.0,
3147            None,
3148            None,
3149        );
3150        assert_eq!(revealed.offset, 100.0);
3151        // At that offset the target sits at the leading edge of the viewport.
3152        assert_eq!(revealed.rect.top, 0.0);
3153        assert_eq!(revealed.rect.bottom, 50.0);
3154    }
3155
3156    /// `RevealedOffset::clamp_offset` picks the nearer edge, and `None` when already visible.
3157    #[test]
3158    fn clamp_offset_picks_the_nearer_edge() {
3159        let leading = RevealedOffset::new(100.0, Rect::ZERO);
3160        let trailing = RevealedOffset::new(20.0, Rect::ZERO);
3161        assert_eq!(
3162            RevealedOffset::clamp_offset(leading, trailing, 200.0).map(|offset| offset.offset),
3163            Some(100.0)
3164        );
3165        assert_eq!(
3166            RevealedOffset::clamp_offset(leading, trailing, 0.0).map(|offset| offset.offset),
3167            Some(20.0)
3168        );
3169        assert!(RevealedOffset::clamp_offset(leading, trailing, 50.0).is_none());
3170    }
3171
3172    /// The paint order decides which sliver paints last and which is hit-tested first.
3173    #[test]
3174    fn the_paint_order_reverses_the_hit_test_order() {
3175        let cell = AppCell::new();
3176        let mut app = cell.borrow_mut();
3177        let (first, _) = test_sliver(&mut app, 100.0);
3178        let (second, _) = test_sliver(&mut app, 300.0);
3179        let offset = FixedViewportOffset::zero(&mut app);
3180        let viewport = vertical_viewport(&mut app, &offset, vec![first, second]);
3181        layout_with(
3182            &mut app,
3183            viewport.as_box(),
3184            Some(BoxConstraints::tight(Size::new(200.0, 400.0))),
3185            AlignmentGeometry::CENTER,
3186            EnginePhase::Paint,
3187        );
3188
3189        assert_eq!(viewport.children_in_paint_order(&app), vec![second, first]);
3190        assert_eq!(
3191            viewport.children_in_hit_test_order(&app),
3192            vec![first, second]
3193        );
3194
3195        viewport.set_paint_order(&mut app, SliverPaintOrder::LastIsTop);
3196        assert_eq!(viewport.children_in_paint_order(&app), vec![first, second]);
3197        assert_eq!(
3198            viewport.children_in_hit_test_order(&app),
3199            vec![second, first]
3200        );
3201    }
3202
3203    /// `viewport_test.dart`: the viewport's clip behavior decides what it says it clips a
3204    /// sliver to.
3205    #[test]
3206    fn a_viewport_describes_its_clip_respecting_clip_behavior() {
3207        let cell = AppCell::new();
3208        let mut app = cell.borrow_mut();
3209        let (sliver, _) = test_sliver(&mut app, 20.0);
3210        let offset = FixedViewportOffset::zero(&mut app);
3211        let viewport = vertical_viewport(&mut app, &offset, vec![sliver]);
3212        viewport.set_clip_behavior(&mut app, Clip::None);
3213        layout_with(
3214            &mut app,
3215            viewport.as_box(),
3216            Some(BoxConstraints::tight(Size::new(800.0, 600.0))),
3217            AlignmentGeometry::CENTER,
3218            EnginePhase::Paint,
3219        );
3220
3221        assert_eq!(viewport.clip_behavior(&app), Clip::None);
3222        assert_eq!(
3223            viewport
3224                .as_object()
3225                .describe_approximate_paint_clip(&app, sliver.as_object()),
3226            None
3227        );
3228
3229        viewport.set_clip_behavior(&mut app, Clip::HardEdge);
3230        assert_eq!(viewport.clip_behavior(&app), Clip::HardEdge);
3231        assert_eq!(
3232            viewport
3233                .as_object()
3234                .describe_approximate_paint_clip(&app, sliver.as_object()),
3235            Some(Offset::ZERO & viewport.size(&app))
3236        );
3237    }
3238
3239    /// A sliver that reports the constraints it was handed, whatever the viewport laid it out
3240    /// with: Dart's `CustomConstraintsRenderSliver`.
3241    struct CustomConstraintsRenderSliver {
3242        render_object: RenderObjectData,
3243        render_sliver: crate::sliver::RenderSliverData,
3244        constraints: SliverConstraints,
3245    }
3246
3247    impl RenderObject for CustomConstraintsRenderSliver {
3248        crate::render_object_accessors!();
3249
3250        fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
3251            self.set_geometry(app, SliverGeometry::ZERO);
3252        }
3253    }
3254
3255    impl RenderSliver for CustomConstraintsRenderSliver {
3256        crate::render_sliver_accessors!();
3257
3258        fn constraints(self: RenderHandle<Self>, app: &App) -> SliverConstraints {
3259            self.get(app).constraints
3260        }
3261
3262        fn hit_test_self(
3263            self: RenderHandle<Self>,
3264            _app: &App,
3265            _main_axis_position: f64,
3266            _cross_axis_position: f64,
3267        ) -> bool {
3268            let _ = self;
3269            false
3270        }
3271    }
3272
3273    /// `viewport_caching_test.dart`: a shrink wrapping viewport with an infinite main axis
3274    /// extent answers a finite clip.
3275    #[test]
3276    fn a_shrink_wrapping_viewport_answers_a_finite_clip_for_an_infinite_extent() {
3277        let cell = AppCell::new();
3278        let mut app = cell.borrow_mut();
3279        let constraints = SliverConstraints {
3280            axis_direction: AxisDirection::Down,
3281            growth_direction: GrowthDirection::Forward,
3282            user_scroll_direction: crate::viewport_offset::ScrollDirection::Idle,
3283            scroll_offset: 0.0,
3284            preceding_scroll_extent: 0.0,
3285            overlap: 1.0,
3286            remaining_paint_extent: f64::INFINITY,
3287            cross_axis_extent: 400.0,
3288            cross_axis_direction: AxisDirection::Left,
3289            viewport_main_axis_extent: f64::INFINITY,
3290            remaining_cache_extent: 0.0,
3291            cache_origin: 0.0,
3292        };
3293        let child = RenderHandle::new_sliver(
3294            &mut app,
3295            CustomConstraintsRenderSliver {
3296                render_object: RenderObjectData::new(),
3297                render_sliver: crate::sliver::RenderSliverData::new(),
3298                constraints,
3299            },
3300        );
3301        let offset = FixedViewportOffset::zero(&mut app);
3302        let viewport = RenderShrinkWrappingViewport::new(
3303            &mut app,
3304            AxisDirection::Left,
3305            offset.erase(),
3306            Some(vec![child.as_sliver()]),
3307        );
3308        layout_with(
3309            &mut app,
3310            viewport.as_box(),
3311            Some(BoxConstraints::tight(Size::new(800.0, 600.0))),
3312            AlignmentGeometry::CENTER,
3313            EnginePhase::Paint,
3314        );
3315
3316        assert_eq!(
3317            viewport
3318                .as_object()
3319                .describe_approximate_paint_clip(&app, child.as_object()),
3320            Some(Rect::from_ltrb(0.0, 0.0, 800.0, 600.0))
3321        );
3322    }
3323}