viewport.dart 78.8 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:math' as math;

7
import 'package:flutter/animation.dart';
8
import 'package:flutter/foundation.dart';
9
import 'package:flutter/semantics.dart';
10 11
import 'package:vector_math/vector_math_64.dart';

12
import 'box.dart';
13
import 'layer.dart';
14 15 16 17
import 'object.dart';
import 'sliver.dart';
import 'viewport_offset.dart';

18 19 20 21 22 23 24 25
/// The unit of measurement for a [Viewport.cacheExtent].
enum CacheExtentStyle {
  /// Treat the [Viewport.cacheExtent] as logical pixels.
  pixel,
  /// Treat the [Viewport.cacheExtent] as a multiplier of the main axis extent.
  viewport,
}

26 27 28 29 30 31
/// An interface for render objects that are bigger on the inside.
///
/// Some render objects, such as [RenderViewport], present a portion of their
/// content, which can be controlled by a [ViewportOffset]. This interface lets
/// the framework recognize such render objects and interact with them without
/// having specific knowledge of all the various types of viewports.
32
abstract class RenderAbstractViewport extends RenderObject {
33 34
  // This class is intended to be used as an interface, and should not be
  // extended directly; this constructor prevents instantiation and extension.
35
  RenderAbstractViewport._();
36

Adam Barth's avatar
Adam Barth committed
37
  /// Returns the [RenderAbstractViewport] that most tightly encloses the given
38 39 40 41
  /// render object.
  ///
  /// If the object does not have a [RenderAbstractViewport] as an ancestor,
  /// this function returns null.
42
  static RenderAbstractViewport? of(RenderObject? object) {
43 44 45
    while (object != null) {
      if (object is RenderAbstractViewport)
        return object;
46
      object = object.parent as RenderObject?;
47 48 49 50
    }
    return null;
  }

51 52 53
  /// Returns the offset that would be needed to reveal the `target`
  /// [RenderObject].
  ///
54 55 56 57 58
  /// This is used by [RenderViewportBase.showInViewport], which is
  /// itself used by [RenderObject.showOnScreen] for
  /// [RenderViewportBase], which is in turn used by the semantics
  /// system to implement scrolling for accessibility tools.
  ///
59 60 61 62 63
  /// The optional `rect` parameter describes which area of that `target` object
  /// should be revealed in the viewport. If `rect` is null, the entire
  /// `target` [RenderObject] (as defined by its [RenderObject.paintBounds])
  /// will be revealed. If `rect` is provided it has to be given in the
  /// coordinate system of the `target` object.
64 65 66 67 68 69 70 71
  ///
  /// The `alignment` argument describes where the target should be positioned
  /// after applying the returned offset. If `alignment` is 0.0, the child must
  /// be positioned as close to the leading edge of the viewport as possible. If
  /// `alignment` is 1.0, the child must be positioned as close to the trailing
  /// edge of the viewport as possible. If `alignment` is 0.5, the child must be
  /// positioned as close to the center of the viewport as possible.
  ///
72 73 74
  /// The `target` might not be a direct child of this viewport but it must be a
  /// descendant of the viewport. Other viewports in between this viewport and
  /// the `target` will not be adjusted.
75 76 77 78 79 80 81 82
  ///
  /// This method assumes that the content of the viewport moves linearly, i.e.
  /// when the offset of the viewport is changed by x then `target` also moves
  /// by x within the viewport.
  ///
  /// See also:
  ///
  ///  * [RevealedOffset], which describes the return value of this method.
83
  RevealedOffset getOffsetToReveal(RenderObject target, double alignment, { Rect? rect });
84 85 86

  /// The default value for the cache extent of the viewport.
  ///
87 88
  /// This default assumes [CacheExtentStyle.pixel].
  ///
89 90 91 92
  /// See also:
  ///
  ///  * [RenderViewportBase.cacheExtent] for a definition of the cache extent.
  static const double defaultCacheExtent = 250.0;
93 94
}

95 96 97 98 99 100 101 102
/// Return value for [RenderAbstractViewport.getOffsetToReveal].
///
/// It indicates the [offset] required to reveal an element in a viewport and
/// the [rect] position said element would have in the viewport at that
/// [offset].
class RevealedOffset {
  /// Instantiates a return value for [RenderAbstractViewport.getOffsetToReveal].
  const RevealedOffset({
103 104
    required this.offset,
    required this.rect,
105 106
  }) : assert(offset != null),
       assert(rect != null);
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143

  /// Offset for the viewport to reveal a specific element in the viewport.
  ///
  /// See also:
  ///
  ///  * [RenderAbstractViewport.getOffsetToReveal], which calculates this
  ///    value for a specific element.
  final double offset;

  /// The [Rect] in the outer coordinate system of the viewport at which the
  /// to-be-revealed element would be located if the viewport's offset is set
  /// to [offset].
  ///
  /// A viewport usually has two coordinate systems and works as an adapter
  /// between the two:
  ///
  /// The inner coordinate system has its origin at the top left corner of the
  /// content that moves inside the viewport. The origin of this coordinate
  /// system usually moves around relative to the leading edge of the viewport
  /// when the viewport offset changes.
  ///
  /// The outer coordinate system has its origin at the top left corner of the
  /// visible part of the viewport. This origin stays at the same position
  /// regardless of the current viewport offset.
  ///
  /// In other words: [rect] describes where the revealed element would be
  /// located relative to the top left corner of the visible part of the
  /// viewport if the viewport's offset is set to [offset].
  ///
  /// See also:
  ///
  ///  * [RenderAbstractViewport.getOffsetToReveal], which calculates this
  ///    value for a specific element.
  final Rect rect;

  @override
  String toString() {
144
    return '${objectRuntimeType(this, 'RevealedOffset')}(offset: $offset, rect: $rect)';
145 146 147
  }
}

148 149 150 151 152
/// A base class for render objects that are bigger on the inside.
///
/// This render object provides the shared code for render objects that host
/// [RenderSliver] render objects inside a [RenderBox]. The viewport establishes
/// an [axisDirection], which orients the sliver's coordinate system, which is
153
/// based on scroll offsets rather than Cartesian coordinates.
154 155 156 157 158 159 160 161 162 163 164 165 166
///
/// The viewport also listens to an [offset], which determines the
/// [SliverConstraints.scrollOffset] input to the sliver layout protocol.
///
/// Subclasses typically override [performLayout] and call
/// [layoutChildSequence], perhaps multiple times.
///
/// See also:
///
///  * [RenderSliver], which explains more about the Sliver protocol.
///  * [RenderBox], which explains more about the Box protocol.
///  * [RenderSliverToBoxAdapter], which allows a [RenderBox] object to be
///    placed inside a [RenderSliver] (the opposite of this class).
167 168 169
abstract class RenderViewportBase<ParentDataClass extends ContainerParentDataMixin<RenderSliver>>
    extends RenderBox with ContainerRenderObjectMixin<RenderSliver, ParentDataClass>
    implements RenderAbstractViewport {
170
  /// Initializes fields for subclasses.
171 172 173 174
  ///
  /// The [cacheExtent], if null, defaults to [RenderAbstractViewport.defaultCacheExtent].
  ///
  /// The [cacheExtent] must be specified if [cacheExtentStyle] is not [CacheExtentStyle.pixel].
175
  RenderViewportBase({
176
    AxisDirection axisDirection = AxisDirection.down,
177 178 179
    required AxisDirection crossAxisDirection,
    required ViewportOffset offset,
    double? cacheExtent,
180
    CacheExtentStyle cacheExtentStyle = CacheExtentStyle.pixel,
181
    Clip clipBehavior = Clip.hardEdge,
182
  }) : assert(axisDirection != null),
183
       assert(crossAxisDirection != null),
184
       assert(offset != null),
185
       assert(axisDirectionToAxis(axisDirection) != axisDirectionToAxis(crossAxisDirection)),
186 187
       assert(cacheExtentStyle != null),
       assert(cacheExtent != null || cacheExtentStyle == CacheExtentStyle.pixel),
188
       assert(clipBehavior != null),
189
       _axisDirection = axisDirection,
190
       _crossAxisDirection = crossAxisDirection,
191
       _offset = offset,
192
       _cacheExtent = cacheExtent ?? RenderAbstractViewport.defaultCacheExtent,
193 194
       _cacheExtentStyle = cacheExtentStyle,
       _clipBehavior = clipBehavior;
195

196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
  /// Report the semantics of this node, for example for accessibility purposes.
  ///
  /// [RenderViewportBase] adds [RenderViewport.useTwoPaneSemantics] to the
  /// provided [SemanticsConfiguration] to support children using
  /// [RenderViewport.excludeFromScrolling].
  ///
  /// This method should be overridden by subclasses that have interesting
  /// semantic information. Overriding subclasses should call
  /// `super.describeSemanticsConfiguration(config)` to ensure
  /// [RenderViewport.useTwoPaneSemantics] is still added to `config`.
  ///
  /// See also:
  ///
  /// * [RenderObject.describeSemanticsConfiguration], for important
  ///   details about not mutating a [SemanticsConfiguration] out of context.
211
  @override
212 213
  void describeSemanticsConfiguration(SemanticsConfiguration config) {
    super.describeSemanticsConfiguration(config);
214

215
    config.addTagForChildren(RenderViewport.useTwoPaneSemantics);
216 217
  }

218 219
  @override
  void visitChildrenForSemantics(RenderObjectVisitor visitor) {
220
    childrenInPaintOrder
221
        .where((RenderSliver sliver) => sliver.geometry!.visible || sliver.geometry!.cacheExtent > 0.0)
222
        .forEach(visitor);
223 224
  }

225
  /// The direction in which the [SliverConstraints.scrollOffset] increases.
226 227 228 229
  ///
  /// For example, if the [axisDirection] is [AxisDirection.down], a scroll
  /// offset of zero is at the top of the viewport and increases towards the
  /// bottom of the viewport.
230 231 232 233 234 235 236 237 238 239
  AxisDirection get axisDirection => _axisDirection;
  AxisDirection _axisDirection;
  set axisDirection(AxisDirection value) {
    assert(value != null);
    if (value == _axisDirection)
      return;
    _axisDirection = value;
    markNeedsLayout();
  }

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
  /// The direction in which child should be laid out in the cross axis.
  ///
  /// For example, if the [axisDirection] is [AxisDirection.down], this property
  /// is typically [AxisDirection.left] if the ambient [TextDirection] is
  /// [TextDirection.rtl] and [AxisDirection.right] if the ambient
  /// [TextDirection] is [TextDirection.ltr].
  AxisDirection get crossAxisDirection => _crossAxisDirection;
  AxisDirection _crossAxisDirection;
  set crossAxisDirection(AxisDirection value) {
    assert(value != null);
    if (value == _crossAxisDirection)
      return;
    _crossAxisDirection = value;
    markNeedsLayout();
  }

256 257 258 259
  /// The axis along which the viewport scrolls.
  ///
  /// For example, if the [axisDirection] is [AxisDirection.down], then the
  /// [axis] is [Axis.vertical] and the viewport scrolls vertically.
260 261
  Axis get axis => axisDirectionToAxis(axisDirection);

262 263 264 265 266 267
  /// Which part of the content inside the viewport should be visible.
  ///
  /// The [ViewportOffset.pixels] value determines the scroll offset that the
  /// viewport uses to select which part of its content to display. As the user
  /// scrolls the viewport, this value changes, which changes the content that
  /// is displayed.
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
  ViewportOffset get offset => _offset;
  ViewportOffset _offset;
  set offset(ViewportOffset value) {
    assert(value != null);
    if (value == _offset)
      return;
    if (attached)
      _offset.removeListener(markNeedsLayout);
    _offset = value;
    if (attached)
      _offset.addListener(markNeedsLayout);
    // We need to go through layout even if the new offset has the same pixels
    // value as the old offset so that we will apply our viewport and content
    // dimensions.
    markNeedsLayout();
  }

285 286 287 288 289
  // TODO(ianh): cacheExtent/cacheExtentStyle should be a single
  // object that specifies both the scalar value and the unit, not a
  // pair of independent setters. Changing that would allow a more
  // rational API and would let us make the getter non-nullable.

290
  /// {@template flutter.rendering.RenderViewportBase.cacheExtent}
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
  /// The viewport has an area before and after the visible area to cache items
  /// that are about to become visible when the user scrolls.
  ///
  /// Items that fall in this cache area are laid out even though they are not
  /// (yet) visible on screen. The [cacheExtent] describes how many pixels
  /// the cache area extends before the leading edge and after the trailing edge
  /// of the viewport.
  ///
  /// The total extent, which the viewport will try to cover with children, is
  /// [cacheExtent] before the leading edge + extent of the main axis +
  /// [cacheExtent] after the trailing edge.
  ///
  /// The cache area is also used to implement implicit accessibility scrolling
  /// on iOS: When the accessibility focus moves from an item in the visible
  /// viewport to an invisible item in the cache area, the framework will bring
  /// that item into view with an (implicit) scroll action.
  /// {@endtemplate}
308 309 310 311 312 313 314 315 316 317
  ///
  /// The getter can never return null, but the field is nullable
  /// because the setter can be set to null to reset the value to
  /// [RenderAbstractViewport.defaultCacheExtent] (in which case
  /// [cacheExtentStyle] must be [CacheExtentStyle.pixel]).
  ///
  /// See also:
  ///
  ///  * [cacheExtentStyle], which controls the units of the [cacheExtent].
  double? get cacheExtent => _cacheExtent;
318
  double _cacheExtent;
319 320
  set cacheExtent(double? value) {
    value ??= RenderAbstractViewport.defaultCacheExtent;
321 322 323 324 325 326 327
    assert(value != null);
    if (value == _cacheExtent)
      return;
    _cacheExtent = value;
    markNeedsLayout();
  }

328 329 330 331 332
  /// This value is set during layout based on the [CacheExtentStyle].
  ///
  /// When the style is [CacheExtentStyle.viewport], it is the main axis extent
  /// of the viewport multiplied by the requested cache extent, which is still
  /// expressed in pixels.
333
  double? _calculatedCacheExtent;
334

335
  /// {@template flutter.rendering.RenderViewportBase.cacheExtentStyle}
336 337
  /// Controls how the [cacheExtent] is interpreted.
  ///
338 339 340
  /// If set to [CacheExtentStyle.pixel], the [cacheExtent] will be
  /// treated as a logical pixels, and the default [cacheExtent] is
  /// [RenderAbstractViewport.defaultCacheExtent].
341
  ///
342 343 344 345
  /// If set to [CacheExtentStyle.viewport], the [cacheExtent] will be
  /// treated as a multiplier for the main axis extent of the
  /// viewport. In this case there is no default [cacheExtent]; it
  /// must be explicitly specified.
346
  /// {@endtemplate}
347 348 349
  ///
  /// Changing the [cacheExtentStyle] without also changing the [cacheExtent]
  /// is rarely the correct choice.
350 351 352 353 354 355 356 357 358 359 360
  CacheExtentStyle get cacheExtentStyle => _cacheExtentStyle;
  CacheExtentStyle _cacheExtentStyle;
  set cacheExtentStyle(CacheExtentStyle value) {
    assert(value != null);
    if (value == _cacheExtentStyle) {
      return;
    }
    _cacheExtentStyle = value;
    markNeedsLayout();
  }

361
  /// {@macro flutter.material.Material.clipBehavior}
362 363 364 365 366 367 368 369 370 371 372 373 374
  ///
  /// Defaults to [Clip.hardEdge], and must not be null.
  Clip get clipBehavior => _clipBehavior;
  Clip _clipBehavior = Clip.hardEdge;
  set clipBehavior(Clip value) {
    assert(value != null);
    if (value != _clipBehavior) {
      _clipBehavior = value;
      markNeedsPaint();
      markNeedsSemanticsUpdate();
    }
  }

375 376 377 378 379 380 381 382 383 384 385 386
  @override
  void attach(PipelineOwner owner) {
    super.attach(owner);
    _offset.addListener(markNeedsLayout);
  }

  @override
  void detach() {
    _offset.removeListener(markNeedsLayout);
    super.detach();
  }

387
  /// Throws an exception saying that the object does not support returning
388
  /// intrinsic dimensions if, in debug mode, we are not in the
389 390 391 392 393 394 395 396 397 398
  /// [RenderObject.debugCheckingIntrinsics] mode.
  ///
  /// This is used by [computeMinIntrinsicWidth] et al because viewports do not
  /// generally support returning intrinsic dimensions. See the discussion at
  /// [computeMinIntrinsicWidth].
  @protected
  bool debugThrowIfNotCheckingIntrinsics() {
    assert(() {
      if (!RenderObject.debugCheckingIntrinsics) {
        assert(this is! RenderShrinkWrappingViewport); // it has its own message
399 400 401 402 403 404 405 406 407
        throw FlutterError.fromParts(<DiagnosticsNode>[
          ErrorSummary('$runtimeType does not support returning intrinsic dimensions.'),
          ErrorDescription(
            'Calculating the intrinsic dimensions would require instantiating every child of '
            'the viewport, which defeats the point of viewports being lazy.',
          ),
          ErrorHint(
            'If you are merely trying to shrink-wrap the viewport in the main axis direction, '
            'consider a RenderShrinkWrappingViewport render object (ShrinkWrappingViewport widget), '
408
            'which achieves that effect without implementing the intrinsic dimension API.',
409 410
          ),
        ]);
411 412
      }
      return true;
413
    }());
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
    return true;
  }

  @override
  double computeMinIntrinsicWidth(double height) {
    assert(debugThrowIfNotCheckingIntrinsics());
    return 0.0;
  }

  @override
  double computeMaxIntrinsicWidth(double height) {
    assert(debugThrowIfNotCheckingIntrinsics());
    return 0.0;
  }

  @override
  double computeMinIntrinsicHeight(double width) {
    assert(debugThrowIfNotCheckingIntrinsics());
    return 0.0;
  }

  @override
  double computeMaxIntrinsicHeight(double width) {
    assert(debugThrowIfNotCheckingIntrinsics());
    return 0.0;
  }

441 442 443
  @override
  bool get isRepaintBoundary => true;

444 445 446 447 448 449 450 451 452
  /// Determines the size and position of some of the children of the viewport.
  ///
  /// This function is the workhorse of `performLayout` implementations in
  /// subclasses.
  ///
  /// Layout starts with `child`, proceeds according to the `advance` callback,
  /// and stops once `advance` returns null.
  ///
  ///  * `scrollOffset` is the [SliverConstraints.scrollOffset] to pass the
453
  ///    first child. The scroll offset is adjusted by
454 455 456 457 458 459 460 461 462 463
  ///    [SliverGeometry.scrollExtent] for subsequent children.
  ///  * `overlap` is the [SliverConstraints.overlap] to pass the first child.
  ///    The overlay is adjusted by the [SliverGeometry.paintOrigin] and
  ///    [SliverGeometry.paintExtent] for subsequent children.
  ///  * `layoutOffset` is the layout offset at which to place the first child.
  ///    The layout offset is updated by the [SliverGeometry.layoutExtent] for
  ///    subsequent children.
  ///  * `remainingPaintExtent` is [SliverConstraints.remainingPaintExtent] to
  ///    pass the first child. The remaining paint extent is updated by the
  ///    [SliverGeometry.layoutExtent] for subsequent children.
464 465
  ///  * `mainAxisExtent` is the [SliverConstraints.viewportMainAxisExtent] to
  ///    pass to each child.
466 467 468 469 470 471 472 473
  ///  * `crossAxisExtent` is the [SliverConstraints.crossAxisExtent] to pass to
  ///    each child.
  ///  * `growthDirection` is the [SliverConstraints.growthDirection] to pass to
  ///    each child.
  ///
  /// Returns the first non-zero [SliverGeometry.scrollOffsetCorrection]
  /// encountered, if any. Otherwise returns 0.0. Typical callers will call this
  /// function repeatedly until it returns 0.0.
474
  @protected
475
  double layoutChildSequence({
476 477 478 479 480 481 482 483 484 485 486
    required RenderSliver? child,
    required double scrollOffset,
    required double overlap,
    required double layoutOffset,
    required double remainingPaintExtent,
    required double mainAxisExtent,
    required double crossAxisExtent,
    required GrowthDirection growthDirection,
    required RenderSliver? Function(RenderSliver child) advance,
    required double remainingCacheExtent,
    required double cacheOrigin,
487
  }) {
488 489
    assert(scrollOffset.isFinite);
    assert(scrollOffset >= 0.0);
490
    final double initialLayoutOffset = layoutOffset;
491
    final ScrollDirection adjustedUserScrollDirection =
Josh Soref's avatar
Josh Soref committed
492
        applyGrowthDirectionToScrollDirection(offset.userScrollDirection, growthDirection);
493
    assert(adjustedUserScrollDirection != null);
494
    double maxPaintOffset = layoutOffset + overlap;
495
    double precedingScrollExtent = 0.0;
496

497
    while (child != null) {
498 499 500 501
      final double sliverScrollOffset = scrollOffset <= 0.0 ? 0.0 : scrollOffset;
      // If the scrollOffset is too small we adjust the paddedOrigin because it
      // doesn't make sense to ask a sliver for content before its scroll
      // offset.
502 503
      final double correctedCacheOrigin = math.max(cacheOrigin, -sliverScrollOffset);
      final double cacheExtentCorrection = cacheOrigin - correctedCacheOrigin;
504

505 506
      assert(sliverScrollOffset >= correctedCacheOrigin.abs());
      assert(correctedCacheOrigin <= 0.0);
507 508 509
      assert(sliverScrollOffset >= 0.0);
      assert(cacheExtentCorrection <= 0.0);

510
      child.layout(SliverConstraints(
511 512 513
        axisDirection: axisDirection,
        growthDirection: growthDirection,
        userScrollDirection: adjustedUserScrollDirection,
514
        scrollOffset: sliverScrollOffset,
515
        precedingScrollExtent: precedingScrollExtent,
516 517 518
        overlap: maxPaintOffset - layoutOffset,
        remainingPaintExtent: math.max(0.0, remainingPaintExtent - layoutOffset + initialLayoutOffset),
        crossAxisExtent: crossAxisExtent,
519
        crossAxisDirection: crossAxisDirection,
520
        viewportMainAxisExtent: mainAxisExtent,
521
        remainingCacheExtent: math.max(0.0, remainingCacheExtent + cacheExtentCorrection),
522
        cacheOrigin: correctedCacheOrigin,
523 524
      ), parentUsesSize: true);

525
      final SliverGeometry childLayoutGeometry = child.geometry!;
526
      assert(childLayoutGeometry.debugAssertIsValid());
527

528
      // If there is a correction to apply, we'll have to start over.
529
      if (childLayoutGeometry.scrollOffsetCorrection != null)
530
        return childLayoutGeometry.scrollOffsetCorrection!;
531

532 533 534
      // We use the child's paint origin in our coordinate system as the
      // layoutOffset we store in the child's parent data.
      final double effectiveLayoutOffset = layoutOffset + childLayoutGeometry.paintOrigin;
535 536 537 538 539 540 541 542 543 544

      // `effectiveLayoutOffset` becomes meaningless once we moved past the trailing edge
      // because `childLayoutGeometry.layoutExtent` is zero. Using the still increasing
      // 'scrollOffset` to roughly position these invisible slivers in the right order.
      if (childLayoutGeometry.visible || scrollOffset > 0) {
        updateChildLayoutOffset(child, effectiveLayoutOffset, growthDirection);
      } else {
        updateChildLayoutOffset(child, -scrollOffset + initialLayoutOffset, growthDirection);
      }

545
      maxPaintOffset = math.max(effectiveLayoutOffset + childLayoutGeometry.paintExtent, maxPaintOffset);
546
      scrollOffset -= childLayoutGeometry.scrollExtent;
547
      precedingScrollExtent += childLayoutGeometry.scrollExtent;
548
      layoutOffset += childLayoutGeometry.layoutExtent;
549 550
      if (childLayoutGeometry.cacheExtent != 0.0) {
        remainingCacheExtent -= childLayoutGeometry.cacheExtent - cacheExtentCorrection;
551
        cacheOrigin = math.min(correctedCacheOrigin + childLayoutGeometry.cacheExtent, 0.0);
552
      }
553

554
      updateOutOfBandData(growthDirection, childLayoutGeometry);
555 556 557 558 559 560 561 562 563

      // move on to the next child
      child = advance(child);
    }

    // we made it without a correction, whee!
    return 0.0;
  }

564 565 566
  @override
  Rect describeApproximatePaintClip(RenderSliver child) {
    final Rect viewportClip = Offset.zero & size;
567 568 569 570 571 572 573 574 575 576
    // The child's viewportMainAxisExtent can be infinite when a
    // RenderShrinkWrappingViewport is given infinite constraints, such as when
    // it is the child of a Row or Column (depending on orientation).
    //
    // For example, a shrink wrapping render sliver may have infinite
    // constraints along the viewport's main axis but may also have bouncing
    // scroll physics, which will allow for some scrolling effect to occur.
    // We should just use the viewportClip - the start of the overlap is at
    // double.infinity and so it is effectively meaningless.
    if (child.constraints.overlap == 0 || !child.constraints.viewportMainAxisExtent.isFinite) {
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
      return viewportClip;
    }

    // Adjust the clip rect for this sliver by the overlap from the previous sliver.
    double left = viewportClip.left;
    double right = viewportClip.right;
    double top = viewportClip.top;
    double bottom = viewportClip.bottom;
    final double startOfOverlap = child.constraints.viewportMainAxisExtent - child.constraints.remainingPaintExtent;
    final double overlapCorrection = startOfOverlap + child.constraints.overlap;
    switch (applyGrowthDirectionToAxisDirection(axisDirection, child.constraints.growthDirection)) {
      case AxisDirection.down:
        top += overlapCorrection;
        break;
      case AxisDirection.up:
        bottom -= overlapCorrection;
        break;
      case AxisDirection.right:
        left += overlapCorrection;
        break;
      case AxisDirection.left:
        right -= overlapCorrection;
        break;
    }
601
    return Rect.fromLTRB(left, top, right, bottom);
602 603 604
  }

  @override
605
  Rect describeSemanticsClip(RenderSliver? child) {
606 607 608 609 610 611
    assert(axis != null);

    if (_calculatedCacheExtent == null) {
      return semanticBounds;
    }

612 613
    switch (axis) {
      case Axis.vertical:
614
        return Rect.fromLTRB(
615
          semanticBounds.left,
616
          semanticBounds.top - _calculatedCacheExtent!,
617
          semanticBounds.right,
618
          semanticBounds.bottom + _calculatedCacheExtent!,
619 620
        );
      case Axis.horizontal:
621
        return Rect.fromLTRB(
622
          semanticBounds.left - _calculatedCacheExtent!,
623
          semanticBounds.top,
624
          semanticBounds.right + _calculatedCacheExtent!,
625 626 627 628 629
          semanticBounds.bottom,
        );
    }
  }

630 631 632 633
  @override
  void paint(PaintingContext context, Offset offset) {
    if (firstChild == null)
      return;
634
    if (hasVisualOverflow && clipBehavior != Clip.none) {
635
      _clipRectLayer.layer = context.pushClipRect(
636 637 638 639 640
        needsCompositing,
        offset,
        Offset.zero & size,
        _paintContents,
        clipBehavior: clipBehavior,
641
        oldLayer: _clipRectLayer.layer,
642
      );
643
    } else {
644
      _clipRectLayer.layer = null;
645
      _paintContents(context, offset);
646 647 648
    }
  }

649 650 651 652 653 654 655
  final LayerHandle<ClipRectLayer> _clipRectLayer = LayerHandle<ClipRectLayer>();

  @override
  void dispose() {
    _clipRectLayer.layer = null;
    super.dispose();
  }
656

657
  void _paintContents(PaintingContext context, Offset offset) {
658
    for (final RenderSliver child in childrenInPaintOrder) {
659
      if (child.geometry!.visible)
660 661 662 663 664 665 666 667
        context.paintChild(child, offset + paintOffsetOf(child));
    }
  }

  @override
  void debugPaintSize(PaintingContext context, Offset offset) {
    assert(() {
      super.debugPaintSize(context, offset);
668
      final Paint paint = Paint()
669 670 671 672
        ..style = PaintingStyle.stroke
        ..strokeWidth = 1.0
        ..color = const Color(0xFF00FF00);
      final Canvas canvas = context.canvas;
673
      RenderSliver? child = firstChild;
674
      while (child != null) {
675
        final Size size;
676 677
        switch (axis) {
          case Axis.vertical:
678
            size = Size(child.constraints.crossAxisExtent, child.geometry!.layoutExtent);
679 680
            break;
          case Axis.horizontal:
681
            size = Size(child.geometry!.layoutExtent, child.constraints.crossAxisExtent);
682 683 684 685 686 687 688
            break;
        }
        assert(size != null);
        canvas.drawRect(((offset + paintOffsetOf(child)) & size).deflate(0.5), paint);
        child = childAfter(child);
      }
      return true;
689
    }());
690 691 692
  }

  @override
693
  bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
694 695 696
    double mainAxisPosition, crossAxisPosition;
    switch (axis) {
      case Axis.vertical:
697 698
        mainAxisPosition = position.dy;
        crossAxisPosition = position.dx;
699 700
        break;
      case Axis.horizontal:
701 702
        mainAxisPosition = position.dx;
        crossAxisPosition = position.dy;
703 704 705 706
        break;
    }
    assert(mainAxisPosition != null);
    assert(crossAxisPosition != null);
707
    final SliverHitTestResult sliverResult = SliverHitTestResult.wrap(result);
708
    for (final RenderSliver child in childrenInHitTestOrder) {
709
      if (!child.geometry!.visible) {
710 711 712
        continue;
      }
      final Matrix4 transform = Matrix4.identity();
713 714 715 716
      applyPaintTransform(child, transform); // must be invertible
      final bool isHit = result.addWithOutOfBandPosition(
        paintTransform: transform,
        hitTest: (BoxHitTestResult result) {
717 718 719 720 721 722 723 724
          return child.hitTest(
            sliverResult,
            mainAxisPosition: computeChildMainAxisPosition(child, mainAxisPosition),
            crossAxisPosition: crossAxisPosition,
          );
        },
      );
      if (isHit) {
725 726 727 728 729 730 731
        return true;
      }
    }
    return false;
  }

  @override
732
  RevealedOffset getOffsetToReveal(RenderObject target, double alignment, { Rect? rect }) {
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
    // Steps to convert `rect` (from a RenderBox coordinate system) to its
    // scroll offset within this viewport (not in the exact order):
    //
    // 1. Pick the outmost RenderBox (between which, and the viewport, there is
    // nothing but RenderSlivers) as an intermediate reference frame
    // (the `pivot`), convert `rect` to that coordinate space.
    //
    // 2. Convert `rect` from the `pivot` coordinate space to its sliver
    // parent's sliver coordinate system (i.e., to a scroll offset), based on
    // the axis direction and growth direction of the parent.
    //
    // 3. Convert the scroll offset to its sliver parent's coordinate space
    // using `childScrollOffset`, until we reach the viewport.
    //
    // 4. Make the final conversion from the outmost sliver to the viewport
    // using `scrollOffsetOf`.
749

750
    double leadingScrollOffset = 0.0;
751 752 753 754
    // Starting at `target` and walking towards the root:
    //  - `child` will be the last object before we reach this viewport, and
    //  - `pivot` will be the last RenderBox before we reach this viewport.
    RenderObject child = target;
755
    RenderBox? pivot;
756 757
    bool onlySlivers = target is RenderSliver; // ... between viewport and `target` (`target` included).
    while (child.parent != this) {
758
      final RenderObject parent = child.parent! as RenderObject;
759
      assert(parent != null, '$target must be a descendant of $this');
760 761 762
      if (child is RenderBox) {
        pivot = child;
      }
763
      if (parent is RenderSliver) {
764
        leadingScrollOffset += parent.childScrollOffset(child)!;
765 766 767 768
      } else {
        onlySlivers = false;
        leadingScrollOffset = 0.0;
      }
769
      child = parent;
770
    }
771

772
    // `rect` in the new intermediate coordinate system.
773
    final Rect rectLocal;
774
    // Our new reference frame render object's main axis extent.
775 776
    final double pivotExtent;
    final GrowthDirection growthDirection;
777 778 779

    // `leadingScrollOffset` is currently the scrollOffset of our new reference
    // frame (`pivot` or `target`), within `child`.
780
    if (pivot != null) {
781 782 783
      assert(pivot.parent != null);
      assert(pivot.parent != this);
      assert(pivot != this);
784
      assert(pivot.parent is RenderSliver);  // TODO(abarth): Support other kinds of render objects besides slivers.
785
      final RenderSliver pivotParent = pivot.parent! as RenderSliver;
786 787 788 789
      growthDirection = pivotParent.constraints.growthDirection;
      switch (axis) {
        case Axis.horizontal:
          pivotExtent = pivot.size.width;
790
          break;
791 792
        case Axis.vertical:
          pivotExtent = pivot.size.height;
793 794
          break;
      }
795 796
      rect ??= target.paintBounds;
      rectLocal = MatrixUtils.transformRect(target.getTransformTo(pivot), rect);
797
    } else if (onlySlivers) {
798 799
      // `pivot` does not exist. We'll have to make up one from `target`, the
      // innermost sliver.
800
      final RenderSliver targetSliver = target as RenderSliver;
801 802 803
      growthDirection = targetSliver.constraints.growthDirection;
      // TODO(LongCatIsLooong): make sure this works if `targetSliver` is a
      // persistent header, when #56413 relands.
804
      pivotExtent = targetSliver.geometry!.scrollExtent;
805 806 807 808 809
      if (rect == null) {
        switch (axis) {
          case Axis.horizontal:
            rect = Rect.fromLTWH(
              0, 0,
810
              targetSliver.geometry!.scrollExtent,
811 812 813 814 815 816 817
              targetSliver.constraints.crossAxisExtent,
            );
            break;
          case Axis.vertical:
            rect = Rect.fromLTWH(
              0, 0,
              targetSliver.constraints.crossAxisExtent,
818
              targetSliver.geometry!.scrollExtent,
819 820 821 822 823
            );
            break;
        }
      }
      rectLocal = rect;
824
    } else {
825 826
      assert(rect != null);
      return RevealedOffset(offset: offset.pixels, rect: rect!);
827 828
    }

829 830 831 832
    assert(pivotExtent != null);
    assert(rect != null);
    assert(rectLocal != null);
    assert(growthDirection != null);
833 834
    assert(child.parent == this);
    assert(child is RenderSliver);
835
    final RenderSliver sliver = child as RenderSliver;
836

837
    final double targetMainAxisExtent;
838
    // The scroll offset of `rect` within `child`.
839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
    switch (applyGrowthDirectionToAxisDirection(axisDirection, growthDirection)) {
      case AxisDirection.up:
        leadingScrollOffset += pivotExtent - rectLocal.bottom;
        targetMainAxisExtent = rectLocal.height;
        break;
      case AxisDirection.right:
        leadingScrollOffset += rectLocal.left;
        targetMainAxisExtent = rectLocal.width;
        break;
      case AxisDirection.down:
        leadingScrollOffset += rectLocal.top;
        targetMainAxisExtent = rectLocal.height;
        break;
      case AxisDirection.left:
        leadingScrollOffset += pivotExtent - rectLocal.right;
        targetMainAxisExtent = rectLocal.width;
        break;
    }

858 859 860 861 862 863 864 865
    // So far leadingScrollOffset is the scroll offset of `rect` in the `child`
    // sliver's sliver coordinate system. The sign of this value indicates
    // whether the `rect` protrudes the leading edge of the `child` sliver. When
    // this value is non-negative and `child`'s `maxScrollObstructionExtent` is
    // greater than 0, we assume `rect` can't be obstructed by the leading edge
    // of the viewport (i.e. its pinned to the leading edge).
    final bool isPinned = sliver.geometry!.maxScrollObstructionExtent > 0 && leadingScrollOffset >= 0;

866
    // The scroll offset in the viewport to `rect`.
867
    leadingScrollOffset = scrollOffsetOf(sliver, leadingScrollOffset);
868 869 870 871 872 873 874

    // This step assumes the viewport's layout is up-to-date, i.e., if
    // offset.pixels is changed after the last performLayout, the new scroll
    // position will not be accounted for.
    final Matrix4 transform = target.getTransformTo(this);
    Rect targetRect = MatrixUtils.transformRect(transform, rect);
    final double extentOfPinnedSlivers = maxScrollObstructionExtentBefore(sliver);
875

876 877
    switch (sliver.constraints.growthDirection) {
      case GrowthDirection.forward:
878 879
        if (isPinned && alignment <= 0)
          return RevealedOffset(offset: double.infinity, rect: targetRect);
880 881 882
        leadingScrollOffset -= extentOfPinnedSlivers;
        break;
      case GrowthDirection.reverse:
883 884
        if (isPinned && alignment >= 1)
          return RevealedOffset(offset: double.negativeInfinity, rect: targetRect);
885 886 887 888 889 890 891 892 893 894 895
        // If child's growth direction is reverse, when viewport.offset is
        // `leadingScrollOffset`, it is positioned just outside of the leading
        // edge of the viewport.
        switch (axis) {
          case Axis.vertical:
            leadingScrollOffset -= targetRect.height;
            break;
          case Axis.horizontal:
            leadingScrollOffset -= targetRect.width;
            break;
        }
896 897
        break;
    }
898

899
    final double mainAxisExtent;
900 901
    switch (axis) {
      case Axis.horizontal:
902
        mainAxisExtent = size.width - extentOfPinnedSlivers;
903 904
        break;
      case Axis.vertical:
905
        mainAxisExtent = size.height - extentOfPinnedSlivers;
906 907 908
        break;
    }

909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
    final double targetOffset = leadingScrollOffset - (mainAxisExtent - targetMainAxisExtent) * alignment;
    final double offsetDifference = offset.pixels - targetOffset;

    switch (axisDirection) {
      case AxisDirection.down:
        targetRect = targetRect.translate(0.0, offsetDifference);
        break;
      case AxisDirection.right:
        targetRect = targetRect.translate(offsetDifference, 0.0);
        break;
      case AxisDirection.up:
        targetRect = targetRect.translate(0.0, -offsetDifference);
        break;
      case AxisDirection.left:
        targetRect = targetRect.translate(-offsetDifference, 0.0);
        break;
    }

927
    return RevealedOffset(offset: targetOffset, rect: targetRect);
928 929
  }

930 931 932 933 934 935
  /// The offset at which the given `child` should be painted.
  ///
  /// The returned offset is from the top left corner of the inside of the
  /// viewport to the top left corner of the paint coordinate system of the
  /// `child`.
  ///
936 937 938 939
  /// See also:
  ///
  ///  * [paintOffsetOf], which uses the layout offset and growth direction
  ///    computed for the child during layout.
940 941 942 943 944 945 946 947 948
  @protected
  Offset computeAbsolutePaintOffset(RenderSliver child, double layoutOffset, GrowthDirection growthDirection) {
    assert(hasSize); // this is only usable once we have a size
    assert(axisDirection != null);
    assert(growthDirection != null);
    assert(child != null);
    assert(child.geometry != null);
    switch (applyGrowthDirectionToAxisDirection(axisDirection, growthDirection)) {
      case AxisDirection.up:
949
        return Offset(0.0, size.height - (layoutOffset + child.geometry!.paintExtent));
950
      case AxisDirection.right:
951
        return Offset(layoutOffset, 0.0);
952
      case AxisDirection.down:
953
        return Offset(0.0, layoutOffset);
954
      case AxisDirection.left:
955
        return Offset(size.width - (layoutOffset + child.geometry!.paintExtent), 0.0);
956 957 958 959
    }
  }

  @override
960 961
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
962 963 964
    properties.add(EnumProperty<AxisDirection>('axisDirection', axisDirection));
    properties.add(EnumProperty<AxisDirection>('crossAxisDirection', crossAxisDirection));
    properties.add(DiagnosticsProperty<ViewportOffset>('offset', offset));
965 966 967
  }

  @override
968 969
  List<DiagnosticsNode> debugDescribeChildren() {
    final List<DiagnosticsNode> children = <DiagnosticsNode>[];
970
    RenderSliver? child = firstChild;
971 972 973 974 975
    if (child == null)
      return children;

    int count = indexOfFirstChild;
    while (true) {
976
      children.add(child!.toDiagnosticsNode(name: labelForChild(count)));
977 978
      if (child == lastChild)
        break;
979 980 981
      count += 1;
      child = childAfter(child);
    }
982
    return children;
983 984 985 986 987 988 989 990
  }

  // API TO BE IMPLEMENTED BY SUBCLASSES

  // setupParentData

  // performLayout (and optionally sizedByParent and performResize)

991 992 993 994 995 996
  /// Whether the contents of this viewport would paint outside the bounds of
  /// the viewport if [paint] did not clip.
  ///
  /// This property enables an optimization whereby [paint] can skip apply a
  /// clip of the contents of the viewport are known to paint entirely within
  /// the bounds of the viewport.
997 998 999
  @protected
  bool get hasVisualOverflow;

1000 1001 1002 1003
  /// Called during [layoutChildSequence] for each child.
  ///
  /// Typically used by subclasses to update any out-of-band data, such as the
  /// max scroll extent, for each child.
1004
  @protected
1005
  void updateOutOfBandData(GrowthDirection growthDirection, SliverGeometry childLayoutGeometry);
1006

1007 1008 1009 1010 1011 1012 1013
  /// Called during [layoutChildSequence] to store the layout offset for the
  /// given child.
  ///
  /// Different subclasses using different representations for their children's
  /// layout offset (e.g., logical or physical coordinates). This function lets
  /// subclasses transform the child's layout offset before storing it in the
  /// child's parent data.
1014 1015 1016
  @protected
  void updateChildLayoutOffset(RenderSliver child, double layoutOffset, GrowthDirection growthDirection);

1017 1018 1019 1020 1021 1022
  /// The offset at which the given `child` should be painted.
  ///
  /// The returned offset is from the top left corner of the inside of the
  /// viewport to the top left corner of the paint coordinate system of the
  /// `child`.
  ///
1023 1024 1025 1026 1027
  /// See also:
  ///
  ///  * [computeAbsolutePaintOffset], which computes the paint offset from an
  ///    explicit layout offset and growth direction instead of using the values
  ///    computed for the child during layout.
1028 1029 1030
  @protected
  Offset paintOffsetOf(RenderSliver child);

1031 1032 1033 1034 1035 1036
  /// Returns the scroll offset within the viewport for the given
  /// `scrollOffsetWithinChild` within the given `child`.
  ///
  /// The returned value is an estimate that assumes the slivers within the
  /// viewport do not change the layout extent in response to changes in their
  /// scroll offset.
1037
  @protected
1038
  double scrollOffsetOf(RenderSliver child, double scrollOffsetWithinChild);
1039

1040 1041
  /// Returns the total scroll obstruction extent of all slivers in the viewport
  /// before [child].
1042 1043 1044
  ///
  /// This is the extent by which the actual area in which content can scroll
  /// is reduced. For example, an app bar that is pinned at the top will reduce
1045
  /// the area in which content can actually scroll by the height of the app bar.
1046 1047 1048
  @protected
  double maxScrollObstructionExtentBefore(RenderSliver child);

1049 1050 1051 1052
  /// Converts the `parentMainAxisPosition` into the child's coordinate system.
  ///
  /// The `parentMainAxisPosition` is a distance from the top edge (for vertical
  /// viewports) or left edge (for horizontal viewports) of the viewport bounds.
1053
  /// This describes a line, perpendicular to the viewport's main axis, heretofore
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
  /// known as the target line.
  ///
  /// The child's coordinate system's origin in the main axis is at the leading
  /// edge of the given child, as given by the child's
  /// [SliverConstraints.axisDirection] and [SliverConstraints.growthDirection].
  ///
  /// This method returns the distance from the leading edge of the given child to
  /// the target line described above.
  ///
  /// (The `parentMainAxisPosition` is not from the leading edge of the
  /// viewport, it's always the top or left edge.)
  @protected
  double computeChildMainAxisPosition(RenderSliver child, double parentMainAxisPosition);

1068 1069 1070 1071
  /// The index of the first child of the viewport relative to the center child.
  ///
  /// For example, the center child has index zero and the first child in the
  /// reverse growth direction has index -1.
1072
  @protected
1073
  int get indexOfFirstChild;
1074

1075 1076 1077
  /// A short string to identify the child with the given index.
  ///
  /// Used by [debugDescribeChildren] to label the children.
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
  @protected
  String labelForChild(int index);

  /// Provides an iterable that walks the children of the viewport, in the order
  /// that they should be painted.
  ///
  /// This should be the reverse order of [childrenInHitTestOrder].
  @protected
  Iterable<RenderSliver> get childrenInPaintOrder;

  /// Provides an iterable that walks the children of the viewport, in the order
  /// that hit-testing should use.
  ///
  /// This should be the reverse order of [childrenInPaintOrder].
  @protected
  Iterable<RenderSliver> get childrenInHitTestOrder;
1094 1095

  @override
1096
  void showOnScreen({
1097 1098
    RenderObject? descendant,
    Rect? rect,
1099 1100 1101
    Duration duration = Duration.zero,
    Curve curve = Curves.ease,
  }) {
1102 1103 1104 1105 1106 1107 1108 1109 1110
    if (!offset.allowImplicitScrolling) {
      return super.showOnScreen(
        descendant: descendant,
        rect: rect,
        duration: duration,
        curve: curve,
      );
    }

1111
    final Rect? newRect = RenderViewportBase.showInViewport(
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
      descendant: descendant,
      viewport: this,
      offset: offset,
      rect: rect,
      duration: duration,
      curve: curve,
    );
    super.showOnScreen(
      rect: newRect,
      duration: duration,
      curve: curve,
    );
1124
  }
1125

1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
  /// Make (a portion of) the given `descendant` of the given `viewport` fully
  /// visible in the `viewport` by manipulating the provided [ViewportOffset]
  /// `offset`.
  ///
  /// The optional `rect` parameter describes which area of the `descendant`
  /// should be shown in the viewport. If `rect` is null, the entire
  /// `descendant` will be revealed. The `rect` parameter is interpreted
  /// relative to the coordinate system of `descendant`.
  ///
  /// The returned [Rect] describes the new location of `descendant` or `rect`
  /// in the viewport after it has been revealed. See [RevealedOffset.rect]
  /// for a full definition of this [Rect].
1138 1139
  ///
  /// The parameters `viewport` and `offset` are required and cannot be null.
1140 1141
  /// If `descendant` is null, this is a no-op and `rect` is returned.
  ///
1142
  /// If both `descendant` and `rect` are null, null is returned because there is
1143 1144 1145 1146
  /// nothing to be shown in the viewport.
  ///
  /// The `duration` parameter can be set to a non-zero value to animate the
  /// target object into the viewport with an animation defined by `curve`.
1147 1148 1149 1150 1151
  ///
  /// See also:
  ///
  /// * [RenderObject.showOnScreen], overridden by [RenderViewportBase] and the
  ///   renderer for [SingleChildScrollView] to delegate to this method.
1152 1153 1154 1155 1156
  static Rect? showInViewport({
    RenderObject? descendant,
    Rect? rect,
    required RenderAbstractViewport viewport,
    required ViewportOffset offset,
1157 1158
    Duration duration = Duration.zero,
    Curve curve = Curves.ease,
1159 1160 1161
  }) {
    assert(viewport != null);
    assert(offset != null);
1162 1163
    if (descendant == null) {
      return rect;
1164
    }
1165 1166
    final RevealedOffset leadingEdgeOffset = viewport.getOffsetToReveal(descendant, 0.0, rect: rect);
    final RevealedOffset trailingEdgeOffset = viewport.getOffsetToReveal(descendant, 1.0, rect: rect);
1167 1168
    final double currentOffset = offset.pixels;

1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
    //           scrollOffset
    //                       0 +---------+
    //                         |         |
    //                       _ |         |
    //    viewport position |  |         |
    // with `descendant` at |  |         | _
    //        trailing edge |_ | xxxxxxx |  | viewport position
    //                         |         |  | with `descendant` at
    //                         |         | _| leading edge
    //                         |         |
    //                     800 +---------+
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
    //
    // `trailingEdgeOffset`: Distance from scrollOffset 0 to the start of the
    //                       viewport on the left in image above.
    // `leadingEdgeOffset`: Distance from scrollOffset 0 to the start of the
    //                      viewport on the right in image above.
    //
    // The viewport position on the left is achieved by setting `offset.pixels`
    // to `trailingEdgeOffset`, the one on the right by setting it to
    // `leadingEdgeOffset`.

1190
    final RevealedOffset targetOffset;
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
    if (leadingEdgeOffset.offset < trailingEdgeOffset.offset) {
      // `descendant` is too big to be visible on screen in its entirety. Let's
      // align it with the edge that requires the least amount of scrolling.
      final double leadingEdgeDiff = (offset.pixels - leadingEdgeOffset.offset).abs();
      final double trailingEdgeDiff = (offset.pixels - trailingEdgeOffset.offset).abs();
      targetOffset = leadingEdgeDiff < trailingEdgeDiff ? leadingEdgeOffset : trailingEdgeOffset;
    } else if (currentOffset > leadingEdgeOffset.offset) {
      // `descendant` currently starts above the leading edge and can be shown
      // fully on screen by scrolling down (which means: moving viewport up).
      targetOffset = leadingEdgeOffset;
    } else if (currentOffset < trailingEdgeOffset.offset) {
      // `descendant currently ends below the trailing edge and can be shown
      // fully on screen by scrolling up (which means: moving viewport down)
      targetOffset = trailingEdgeOffset;
    } else {
      // `descendant` is between leading and trailing edge and hence already
      //  fully shown on screen. No action necessary.
1208
      final Matrix4 transform = descendant.getTransformTo(viewport.parent! as RenderObject);
1209 1210 1211 1212
      return MatrixUtils.transformRect(transform, rect ?? descendant.paintBounds);
    }

    assert(targetOffset != null);
1213

1214
    offset.moveTo(targetOffset.offset, duration: duration, curve: curve);
1215
    return targetOffset.rect;
1216
  }
1217 1218
}

1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
/// A render object that is bigger on the inside.
///
/// [RenderViewport] is the visual workhorse of the scrolling machinery. It
/// displays a subset of its children according to its own dimensions and the
/// given [offset]. As the offset varies, different children are visible through
/// the viewport.
///
/// [RenderViewport] hosts a bidirectional list of slivers, anchored on a
/// [center] sliver, which is placed at the zero scroll offset. The center
/// widget is displayed in the viewport according to the [anchor] property.
///
/// Slivers that are earlier in the child list than [center] are displayed in
/// reverse order in the reverse [axisDirection] starting from the [center]. For
/// example, if the [axisDirection] is [AxisDirection.down], the first sliver
/// before [center] is placed above the [center]. The slivers that are later in
/// the child list than [center] are placed in order in the [axisDirection]. For
1235
/// example, in the preceding scenario, the first sliver after [center] is
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
/// placed below the [center].
///
/// [RenderViewport] cannot contain [RenderBox] children directly. Instead, use
/// a [RenderSliverList], [RenderSliverFixedExtentList], [RenderSliverGrid], or
/// a [RenderSliverToBoxAdapter], for example.
///
/// See also:
///
///  * [RenderSliver], which explains more about the Sliver protocol.
///  * [RenderBox], which explains more about the Box protocol.
///  * [RenderSliverToBoxAdapter], which allows a [RenderBox] object to be
///    placed inside a [RenderSliver] (the opposite of this class).
///  * [RenderShrinkWrappingViewport], a variant of [RenderViewport] that
///    shrink-wraps its contents along the main axis.
1250 1251 1252 1253 1254 1255 1256
class RenderViewport extends RenderViewportBase<SliverPhysicalContainerParentData> {
  /// Creates a viewport for [RenderSliver] objects.
  ///
  /// If the [center] is not specified, then the first child in the `children`
  /// list, if any, is used.
  ///
  /// The [offset] must be specified. For testing purposes, consider passing a
1257
  /// [ViewportOffset.zero] or [ViewportOffset.fixed].
1258
  RenderViewport({
1259 1260 1261
    super.axisDirection,
    required super.crossAxisDirection,
    required super.offset,
1262
    double anchor = 0.0,
1263 1264
    List<RenderSliver>? children,
    RenderSliver? center,
1265 1266 1267
    super.cacheExtent,
    super.cacheExtentStyle,
    super.clipBehavior,
1268 1269
  }) : assert(anchor != null),
       assert(anchor >= 0.0 && anchor <= 1.0),
1270
       assert(cacheExtentStyle != CacheExtentStyle.viewport || cacheExtent != null),
1271
       assert(clipBehavior != null),
1272
       _anchor = anchor,
1273
       _center = center {
1274 1275 1276 1277 1278
    addAll(children);
    if (center == null && firstChild != null)
      _center = firstChild;
  }

1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
  /// If a [RenderAbstractViewport] overrides
  /// [RenderObject.describeSemanticsConfiguration] to add the [SemanticsTag]
  /// [useTwoPaneSemantics] to its [SemanticsConfiguration], two semantics nodes
  /// will be used to represent the viewport with its associated scrolling
  /// actions in the semantics tree.
  ///
  /// Two semantics nodes (an inner and an outer node) are necessary to exclude
  /// certain child nodes (via the [excludeFromScrolling] tag) from the
  /// scrollable area for semantic purposes: The [SemanticsNode]s of children
  /// that should be excluded from scrolling will be attached to the outer node.
  /// The semantic scrolling actions and the [SemanticsNode]s of scrollable
  /// children will be attached to the inner node, which itself is a child of
  /// the outer node.
1292 1293 1294 1295 1296
  ///
  /// See also:
  ///
  /// * [RenderViewportBase.describeSemanticsConfiguration], which adds this
  ///   tag to its [SemanticsConfiguration].
1297
  static const SemanticsTag useTwoPaneSemantics = SemanticsTag('RenderViewport.twoPane');
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311

  /// When a top-level [SemanticsNode] below a [RenderAbstractViewport] is
  /// tagged with [excludeFromScrolling] it will not be part of the scrolling
  /// area for semantic purposes.
  ///
  /// This behavior is only active if the [RenderAbstractViewport]
  /// tagged its [SemanticsConfiguration] with [useTwoPaneSemantics].
  /// Otherwise, the [excludeFromScrolling] tag is ignored.
  ///
  /// As an example, a [RenderSliver] that stays on the screen within a
  /// [Scrollable] even though the user has scrolled past it (e.g. a pinned app
  /// bar) can tag its [SemanticsNode] with [excludeFromScrolling] to indicate
  /// that it should no longer be considered for semantic actions related to
  /// scrolling.
1312
  static const SemanticsTag excludeFromScrolling = SemanticsTag('RenderViewport.excludeFromScrolling');
1313

1314 1315 1316
  @override
  void setupParentData(RenderObject child) {
    if (child.parentData is! SliverPhysicalContainerParentData)
1317
      child.parentData = SliverPhysicalContainerParentData();
1318 1319
  }

1320 1321 1322 1323 1324 1325 1326
  /// The relative position of the zero scroll offset.
  ///
  /// For example, if [anchor] is 0.5 and the [axisDirection] is
  /// [AxisDirection.down] or [AxisDirection.up], then the zero scroll offset is
  /// vertically centered within the viewport. If the [anchor] is 1.0, and the
  /// [axisDirection] is [AxisDirection.right], then the zero scroll offset is
  /// on the left edge of the viewport.
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
  double get anchor => _anchor;
  double _anchor;
  set anchor(double value) {
    assert(value != null);
    assert(value >= 0.0 && value <= 1.0);
    if (value == _anchor)
      return;
    _anchor = value;
    markNeedsLayout();
  }

1338 1339
  /// The first child in the [GrowthDirection.forward] growth direction.
  ///
1340
  /// This child that will be at the position defined by [anchor] when the
1341
  /// [ViewportOffset.pixels] of [offset] is `0`.
1342
  ///
1343 1344 1345 1346 1347
  /// Children after [center] will be placed in the [axisDirection] relative to
  /// the [center]. Children before [center] will be placed in the opposite of
  /// the [axisDirection] relative to the [center].
  ///
  /// The [center] must be a child of the viewport.
1348 1349 1350
  RenderSliver? get center => _center;
  RenderSliver? _center;
  set center(RenderSliver? value) {
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
    if (value == _center)
      return;
    _center = value;
    markNeedsLayout();
  }

  @override
  bool get sizedByParent => true;

  @override
1361
  Size computeDryLayout(BoxConstraints constraints) {
1362 1363 1364 1365 1366
    assert(() {
      if (!constraints.hasBoundedHeight || !constraints.hasBoundedWidth) {
        switch (axis) {
          case Axis.vertical:
            if (!constraints.hasBoundedHeight) {
1367 1368 1369 1370 1371 1372
              throw FlutterError.fromParts(<DiagnosticsNode>[
                ErrorSummary('Vertical viewport was given unbounded height.'),
                ErrorDescription(
                  'Viewports expand in the scrolling direction to fill their container. '
                  'In this case, a vertical viewport was given an unlimited amount of '
                  'vertical space in which to expand. This situation typically happens '
1373
                  'when a scrollable widget is nested inside another scrollable widget.',
1374 1375 1376 1377 1378 1379 1380
                ),
                ErrorHint(
                  'If this widget is always nested in a scrollable widget there '
                  'is no need to use a viewport because there will always be enough '
                  'vertical space for the children. In this case, consider using a '
                  'Column instead. Otherwise, consider using the "shrinkWrap" property '
                  '(or a ShrinkWrappingViewport) to size the height of the viewport '
1381 1382
                  'to the sum of the heights of its children.',
                ),
1383
              ]);
1384 1385
            }
            if (!constraints.hasBoundedWidth) {
1386
              throw FlutterError(
1387 1388 1389 1390
                'Vertical viewport was given unbounded width.\n'
                'Viewports expand in the cross axis to fill their container and '
                'constrain their children to match their extent in the cross axis. '
                'In this case, a vertical viewport was given an unlimited amount of '
1391
                'horizontal space in which to expand.',
1392 1393 1394 1395 1396
              );
            }
            break;
          case Axis.horizontal:
            if (!constraints.hasBoundedWidth) {
1397 1398 1399
              throw FlutterError.fromParts(<DiagnosticsNode>[
                ErrorSummary('Horizontal viewport was given unbounded width.'),
                ErrorDescription(
1400
                  'Viewports expand in the scrolling direction to fill their container. '
1401 1402
                  'In this case, a horizontal viewport was given an unlimited amount of '
                  'horizontal space in which to expand. This situation typically happens '
1403
                  'when a scrollable widget is nested inside another scrollable widget.',
1404 1405 1406 1407 1408 1409 1410
                ),
                ErrorHint(
                  'If this widget is always nested in a scrollable widget there '
                  'is no need to use a viewport because there will always be enough '
                  'horizontal space for the children. In this case, consider using a '
                  'Row instead. Otherwise, consider using the "shrinkWrap" property '
                  '(or a ShrinkWrappingViewport) to size the width of the viewport '
1411 1412
                  'to the sum of the widths of its children.',
                ),
1413
              ]);
1414 1415
            }
            if (!constraints.hasBoundedHeight) {
1416
              throw FlutterError(
1417 1418 1419 1420
                'Horizontal viewport was given unbounded height.\n'
                'Viewports expand in the cross axis to fill their container and '
                'constrain their children to match their extent in the cross axis. '
                'In this case, a horizontal viewport was given an unlimited amount of '
1421
                'vertical space in which to expand.',
1422 1423 1424 1425 1426 1427
              );
            }
            break;
        }
      }
      return true;
1428
    }());
1429
    return constraints.biggest;
1430 1431
  }

1432
  static const int _maxLayoutCycles = 10;
1433 1434

  // Out-of-band data computed during layout.
1435 1436
  late double _minScrollExtent;
  late double _maxScrollExtent;
1437 1438 1439 1440
  bool _hasVisualOverflow = false;

  @override
  void performLayout() {
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451
    // Ignore the return value of applyViewportDimension because we are
    // doing a layout regardless.
    switch (axis) {
      case Axis.vertical:
        offset.applyViewportDimension(size.height);
        break;
      case Axis.horizontal:
        offset.applyViewportDimension(size.width);
        break;
    }

1452 1453 1454 1455 1456 1457 1458 1459
    if (center == null) {
      assert(firstChild == null);
      _minScrollExtent = 0.0;
      _maxScrollExtent = 0.0;
      _hasVisualOverflow = false;
      offset.applyContentDimensions(0.0, 0.0);
      return;
    }
1460
    assert(center!.parent == this);
1461

1462 1463
    final double mainAxisExtent;
    final double crossAxisExtent;
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474
    switch (axis) {
      case Axis.vertical:
        mainAxisExtent = size.height;
        crossAxisExtent = size.width;
        break;
      case Axis.horizontal:
        mainAxisExtent = size.width;
        crossAxisExtent = size.height;
        break;
    }

1475
    final double centerOffsetAdjustment = center!.centerOffsetAdjustment;
1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491

    double correction;
    int count = 0;
    do {
      assert(offset.pixels != null);
      correction = _attemptLayout(mainAxisExtent, crossAxisExtent, offset.pixels + centerOffsetAdjustment);
      if (correction != 0.0) {
        offset.correctBy(correction);
      } else {
        if (offset.applyContentDimensions(
              math.min(0.0, _minScrollExtent + mainAxisExtent * anchor),
              math.max(0.0, _maxScrollExtent - mainAxisExtent * (1.0 - anchor)),
           ))
          break;
      }
      count += 1;
1492
    } while (count < _maxLayoutCycles);
1493
    assert(() {
1494
      if (count >= _maxLayoutCycles) {
1495
        assert(count != 1);
1496
        throw FlutterError(
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511
          'A RenderViewport exceeded its maximum number of layout cycles.\n'
          'RenderViewport render objects, during layout, can retry if either their '
          'slivers or their ViewportOffset decide that the offset should be corrected '
          'to take into account information collected during that layout.\n'
          'In the case of this RenderViewport object, however, this happened $count '
          'times and still there was no consensus on the scroll offset. This usually '
          'indicates a bug. Specifically, it means that one of the following three '
          'problems is being experienced by the RenderViewport object:\n'
          ' * One of the RenderSliver children or the ViewportOffset have a bug such'
          ' that they always think that they need to correct the offset regardless.\n'
          ' * Some combination of the RenderSliver children and the ViewportOffset'
          ' have a bad interaction such that one applies a correction then another'
          ' applies a reverse correction, leading to an infinite loop of corrections.\n'
          ' * There is a pathological case that would eventually resolve, but it is'
          ' so complicated that it cannot be resolved in any reasonable number of'
1512
          ' layout passes.',
1513 1514 1515
        );
      }
      return true;
1516
    }());
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
  }

  double _attemptLayout(double mainAxisExtent, double crossAxisExtent, double correctedOffset) {
    assert(!mainAxisExtent.isNaN);
    assert(mainAxisExtent >= 0.0);
    assert(crossAxisExtent.isFinite);
    assert(crossAxisExtent >= 0.0);
    assert(correctedOffset.isFinite);
    _minScrollExtent = 0.0;
    _maxScrollExtent = 0.0;
    _hasVisualOverflow = false;

    // centerOffset is the offset from the leading edge of the RenderViewport
    // to the zero scroll offset (the line between the forward slivers and the
1531
    // reverse slivers).
1532
    final double centerOffset = mainAxisExtent * anchor - correctedOffset;
1533 1534
    final double reverseDirectionRemainingPaintExtent = centerOffset.clamp(0.0, mainAxisExtent);
    final double forwardDirectionRemainingPaintExtent = (mainAxisExtent - centerOffset).clamp(0.0, mainAxisExtent);
1535

1536 1537 1538 1539 1540
    switch (cacheExtentStyle) {
      case CacheExtentStyle.pixel:
        _calculatedCacheExtent = cacheExtent;
        break;
      case CacheExtentStyle.viewport:
1541
        _calculatedCacheExtent = mainAxisExtent * _cacheExtent;
1542 1543 1544
        break;
    }

1545 1546 1547 1548
    final double fullCacheExtent = mainAxisExtent + 2 * _calculatedCacheExtent!;
    final double centerCacheOffset = centerOffset + _calculatedCacheExtent!;
    final double reverseDirectionRemainingCacheExtent = centerCacheOffset.clamp(0.0, fullCacheExtent);
    final double forwardDirectionRemainingCacheExtent = (fullCacheExtent - centerCacheOffset).clamp(0.0, fullCacheExtent);
1549

1550
    final RenderSliver? leadingNegativeChild = childBefore(center!);
1551 1552 1553

    if (leadingNegativeChild != null) {
      // negative scroll offsets
1554
      final double result = layoutChildSequence(
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564
        child: leadingNegativeChild,
        scrollOffset: math.max(mainAxisExtent, centerOffset) - mainAxisExtent,
        overlap: 0.0,
        layoutOffset: forwardDirectionRemainingPaintExtent,
        remainingPaintExtent: reverseDirectionRemainingPaintExtent,
        mainAxisExtent: mainAxisExtent,
        crossAxisExtent: crossAxisExtent,
        growthDirection: GrowthDirection.reverse,
        advance: childBefore,
        remainingCacheExtent: reverseDirectionRemainingCacheExtent,
1565
        cacheOrigin: (mainAxisExtent - centerOffset).clamp(-_calculatedCacheExtent!, 0.0),
1566 1567 1568 1569
      );
      if (result != 0.0)
        return -result;
    }
1570 1571

    // positive scroll offsets
1572
    return layoutChildSequence(
1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
      child: center,
      scrollOffset: math.max(0.0, -centerOffset),
      overlap: leadingNegativeChild == null ? math.min(0.0, -centerOffset) : 0.0,
      layoutOffset: centerOffset >= mainAxisExtent ? centerOffset: reverseDirectionRemainingPaintExtent,
      remainingPaintExtent: forwardDirectionRemainingPaintExtent,
      mainAxisExtent: mainAxisExtent,
      crossAxisExtent: crossAxisExtent,
      growthDirection: GrowthDirection.forward,
      advance: childAfter,
      remainingCacheExtent: forwardDirectionRemainingCacheExtent,
1583
      cacheOrigin: centerOffset.clamp(-_calculatedCacheExtent!, 0.0),
1584 1585 1586 1587 1588 1589 1590
    );
  }

  @override
  bool get hasVisualOverflow => _hasVisualOverflow;

  @override
1591
  void updateOutOfBandData(GrowthDirection growthDirection, SliverGeometry childLayoutGeometry) {
1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605
    switch (growthDirection) {
      case GrowthDirection.forward:
        _maxScrollExtent += childLayoutGeometry.scrollExtent;
        break;
      case GrowthDirection.reverse:
        _minScrollExtent -= childLayoutGeometry.scrollExtent;
        break;
    }
    if (childLayoutGeometry.hasVisualOverflow)
      _hasVisualOverflow = true;
  }

  @override
  void updateChildLayoutOffset(RenderSliver child, double layoutOffset, GrowthDirection growthDirection) {
1606
    final SliverPhysicalParentData childParentData = child.parentData! as SliverPhysicalParentData;
1607 1608 1609 1610 1611
    childParentData.paintOffset = computeAbsolutePaintOffset(child, layoutOffset, growthDirection);
  }

  @override
  Offset paintOffsetOf(RenderSliver child) {
1612
    final SliverPhysicalParentData childParentData = child.parentData! as SliverPhysicalParentData;
1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
    return childParentData.paintOffset;
  }

  @override
  double scrollOffsetOf(RenderSliver child, double scrollOffsetWithinChild) {
    assert(child.parent == this);
    final GrowthDirection growthDirection = child.constraints.growthDirection;
    assert(growthDirection != null);
    switch (growthDirection) {
      case GrowthDirection.forward:
        double scrollOffsetToChild = 0.0;
1624
        RenderSliver? current = center;
1625
        while (current != child) {
1626
          scrollOffsetToChild += current!.geometry!.scrollExtent;
1627 1628 1629 1630 1631
          current = childAfter(current);
        }
        return scrollOffsetToChild + scrollOffsetWithinChild;
      case GrowthDirection.reverse:
        double scrollOffsetToChild = 0.0;
1632
        RenderSliver? current = childBefore(center!);
1633
        while (current != child) {
1634
          scrollOffsetToChild -= current!.geometry!.scrollExtent;
1635 1636 1637 1638 1639 1640
          current = childBefore(current);
        }
        return scrollOffsetToChild - scrollOffsetWithinChild;
    }
  }

1641 1642 1643 1644 1645 1646 1647 1648
  @override
  double maxScrollObstructionExtentBefore(RenderSliver child) {
    assert(child.parent == this);
    final GrowthDirection growthDirection = child.constraints.growthDirection;
    assert(growthDirection != null);
    switch (growthDirection) {
      case GrowthDirection.forward:
        double pinnedExtent = 0.0;
1649
        RenderSliver? current = center;
1650
        while (current != child) {
1651
          pinnedExtent += current!.geometry!.maxScrollObstructionExtent;
1652 1653 1654 1655 1656
          current = childAfter(current);
        }
        return pinnedExtent;
      case GrowthDirection.reverse:
        double pinnedExtent = 0.0;
1657
        RenderSliver? current = childBefore(center!);
1658
        while (current != child) {
1659
          pinnedExtent += current!.geometry!.maxScrollObstructionExtent;
1660 1661 1662 1663 1664 1665
          current = childBefore(current);
        }
        return pinnedExtent;
    }
  }

1666 1667
  @override
  void applyPaintTransform(RenderObject child, Matrix4 transform) {
1668
    // Hit test logic relies on this always providing an invertible matrix.
1669
    assert(child != null);
1670
    final SliverPhysicalParentData childParentData = child.parentData! as SliverPhysicalParentData;
1671 1672 1673 1674 1675 1676 1677
    childParentData.applyPaintTransform(transform);
  }

  @override
  double computeChildMainAxisPosition(RenderSliver child, double parentMainAxisPosition) {
    assert(child != null);
    assert(child.constraints != null);
1678
    final SliverPhysicalParentData childParentData = child.parentData! as SliverPhysicalParentData;
1679 1680 1681 1682 1683 1684
    switch (applyGrowthDirectionToAxisDirection(child.constraints.axisDirection, child.constraints.growthDirection)) {
      case AxisDirection.down:
        return parentMainAxisPosition - childParentData.paintOffset.dy;
      case AxisDirection.right:
        return parentMainAxisPosition - childParentData.paintOffset.dx;
      case AxisDirection.up:
1685
        return child.geometry!.paintExtent - (parentMainAxisPosition - childParentData.paintOffset.dy);
1686
      case AxisDirection.left:
1687
        return child.geometry!.paintExtent - (parentMainAxisPosition - childParentData.paintOffset.dx);
1688 1689 1690 1691
    }
  }

  @override
1692
  int get indexOfFirstChild {
1693
    assert(center != null);
1694
    assert(center!.parent == this);
1695 1696
    assert(firstChild != null);
    int count = 0;
1697
    RenderSliver? child = center;
1698 1699
    while (child != firstChild) {
      count -= 1;
1700
      child = childBefore(child!);
1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712
    }
    return count;
  }

  @override
  String labelForChild(int index) {
    if (index == 0)
      return 'center child';
    return 'child $index';
  }

  @override
1713 1714
  Iterable<RenderSliver> get childrenInPaintOrder {
    final List<RenderSliver> children = <RenderSliver>[];
1715
    if (firstChild == null)
1716
      return children;
1717
    RenderSliver? child = firstChild;
1718
    while (child != center) {
1719
      children.add(child!);
1720 1721 1722 1723
      child = childAfter(child);
    }
    child = lastChild;
    while (true) {
1724
      children.add(child!);
1725
      if (child == center)
1726
        return children;
1727 1728 1729 1730 1731
      child = childBefore(child);
    }
  }

  @override
1732 1733
  Iterable<RenderSliver> get childrenInHitTestOrder {
    final List<RenderSliver> children = <RenderSliver>[];
1734
    if (firstChild == null)
1735
      return children;
1736
    RenderSliver? child = center;
1737
    while (child != null) {
1738
      children.add(child);
1739 1740
      child = childAfter(child);
    }
1741
    child = childBefore(center!);
1742
    while (child != null) {
1743
      children.add(child);
1744 1745
      child = childBefore(child);
    }
1746
    return children;
1747 1748 1749
  }

  @override
1750 1751
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
1752
    properties.add(DoubleProperty('anchor', anchor));
1753 1754 1755
  }
}

1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775
/// A render object that is bigger on the inside and shrink wraps its children
/// in the main axis.
///
/// [RenderShrinkWrappingViewport] displays a subset of its children according
/// to its own dimensions and the given [offset]. As the offset varies, different
/// children are visible through the viewport.
///
/// [RenderShrinkWrappingViewport] differs from [RenderViewport] in that
/// [RenderViewport] expands to fill the main axis whereas
/// [RenderShrinkWrappingViewport] sizes itself to match its children in the
/// main axis. This shrink wrapping behavior is expensive because the children,
/// and hence the viewport, could potentially change size whenever the [offset]
/// changes (e.g., because of a collapsing header).
///
/// [RenderShrinkWrappingViewport] cannot contain [RenderBox] children directly.
/// Instead, use a [RenderSliverList], [RenderSliverFixedExtentList],
/// [RenderSliverGrid], or a [RenderSliverToBoxAdapter], for example.
///
/// See also:
///
1776
///  * [RenderViewport], a viewport that does not shrink-wrap its contents.
1777 1778 1779 1780
///  * [RenderSliver], which explains more about the Sliver protocol.
///  * [RenderBox], which explains more about the Box protocol.
///  * [RenderSliverToBoxAdapter], which allows a [RenderBox] object to be
///    placed inside a [RenderSliver] (the opposite of this class).
1781 1782 1783 1784 1785
class RenderShrinkWrappingViewport extends RenderViewportBase<SliverLogicalContainerParentData> {
  /// Creates a viewport (for [RenderSliver] objects) that shrink-wraps its
  /// contents.
  ///
  /// The [offset] must be specified. For testing purposes, consider passing a
1786
  /// [ViewportOffset.zero] or [ViewportOffset.fixed].
1787
  RenderShrinkWrappingViewport({
1788 1789 1790 1791
    super.axisDirection,
    required super.crossAxisDirection,
    required super.offset,
    super.clipBehavior,
1792
    List<RenderSliver>? children,
1793
  }) {
1794 1795 1796 1797 1798 1799
    addAll(children);
  }

  @override
  void setupParentData(RenderObject child) {
    if (child.parentData is! SliverLogicalContainerParentData)
1800
      child.parentData = SliverLogicalContainerParentData();
1801 1802
  }

1803 1804 1805 1806
  @override
  bool debugThrowIfNotCheckingIntrinsics() {
    assert(() {
      if (!RenderObject.debugCheckingIntrinsics) {
1807 1808 1809 1810
        throw FlutterError.fromParts(<DiagnosticsNode>[
          ErrorSummary('$runtimeType does not support returning intrinsic dimensions.'),
          ErrorDescription(
           'Calculating the intrinsic dimensions would require instantiating every child of '
1811
           'the viewport, which defeats the point of viewports being lazy.',
1812 1813 1814 1815
          ),
          ErrorHint(
            'If you are merely trying to shrink-wrap the viewport in the main axis direction, '
            'you should be able to achieve that effect by just giving the viewport loose '
1816 1817
            'constraints, without needing to measure its intrinsic dimensions.',
          ),
1818
        ]);
1819 1820
      }
      return true;
1821
    }());
1822 1823 1824
    return true;
  }

1825
  // Out-of-band data computed during layout.
1826 1827
  late double _maxScrollExtent;
  late double _shrinkWrapExtent;
1828 1829 1830 1831
  bool _hasVisualOverflow = false;

  @override
  void performLayout() {
1832
    final BoxConstraints constraints = this.constraints;
1833 1834 1835 1836
    if (firstChild == null) {
      switch (axis) {
        case Axis.vertical:
          assert(constraints.hasBoundedWidth);
1837
          size = Size(constraints.maxWidth, constraints.minHeight);
1838 1839 1840
          break;
        case Axis.horizontal:
          assert(constraints.hasBoundedHeight);
1841
          size = Size(constraints.minWidth, constraints.maxHeight);
1842 1843 1844 1845 1846 1847 1848 1849 1850 1851
          break;
      }
      offset.applyViewportDimension(0.0);
      _maxScrollExtent = 0.0;
      _shrinkWrapExtent = 0.0;
      _hasVisualOverflow = false;
      offset.applyContentDimensions(0.0, 0.0);
      return;
    }

1852 1853
    final double mainAxisExtent;
    final double crossAxisExtent;
1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899
    switch (axis) {
      case Axis.vertical:
        assert(constraints.hasBoundedWidth);
        mainAxisExtent = constraints.maxHeight;
        crossAxisExtent = constraints.maxWidth;
        break;
      case Axis.horizontal:
        assert(constraints.hasBoundedHeight);
        mainAxisExtent = constraints.maxWidth;
        crossAxisExtent = constraints.maxHeight;
        break;
    }

    double correction;
    double effectiveExtent;
    do {
      assert(offset.pixels != null);
      correction = _attemptLayout(mainAxisExtent, crossAxisExtent, offset.pixels);
      if (correction != 0.0) {
        offset.correctBy(correction);
      } else {
        switch (axis) {
          case Axis.vertical:
            effectiveExtent = constraints.constrainHeight(_shrinkWrapExtent);
            break;
          case Axis.horizontal:
            effectiveExtent = constraints.constrainWidth(_shrinkWrapExtent);
            break;
        }
        final bool didAcceptViewportDimension = offset.applyViewportDimension(effectiveExtent);
        final bool didAcceptContentDimension = offset.applyContentDimensions(0.0, math.max(0.0, _maxScrollExtent - effectiveExtent));
        if (didAcceptViewportDimension && didAcceptContentDimension)
          break;
      }
    } while (true);
    switch (axis) {
      case Axis.vertical:
        size = constraints.constrainDimensions(crossAxisExtent, effectiveExtent);
        break;
      case Axis.horizontal:
        size = constraints.constrainDimensions(effectiveExtent, crossAxisExtent);
        break;
    }
  }

  double _attemptLayout(double mainAxisExtent, double crossAxisExtent, double correctedOffset) {
1900 1901 1902 1903 1904
    // We can't assert mainAxisExtent is finite, because it could be infinite if
    // it is within a column or row for example. In such a case, there's not
    // even any scrolling to do, although some scroll physics (i.e.
    // BouncingScrollPhysics) could still temporarily scroll the content in a
    // simulation.
1905 1906 1907 1908 1909 1910 1911
    assert(!mainAxisExtent.isNaN);
    assert(mainAxisExtent >= 0.0);
    assert(crossAxisExtent.isFinite);
    assert(crossAxisExtent >= 0.0);
    assert(correctedOffset.isFinite);
    _maxScrollExtent = 0.0;
    _shrinkWrapExtent = 0.0;
1912 1913 1914 1915
    // Since the viewport is shrinkwrapped, we know that any negative overscroll
    // into the potentially infinite mainAxisExtent will overflow the end of
    // the viewport.
    _hasVisualOverflow = correctedOffset < 0.0;
1916 1917 1918 1919 1920 1921 1922 1923
    switch (cacheExtentStyle) {
      case CacheExtentStyle.pixel:
        _calculatedCacheExtent = cacheExtent;
        break;
      case CacheExtentStyle.viewport:
        _calculatedCacheExtent = mainAxisExtent * _cacheExtent;
        break;
    }
1924

1925
    return layoutChildSequence(
1926 1927 1928
      child: firstChild,
      scrollOffset: math.max(0.0, correctedOffset),
      overlap: math.min(0.0, correctedOffset),
1929
      layoutOffset: math.max(0.0, -correctedOffset),
1930
      remainingPaintExtent: mainAxisExtent + math.min(0.0, correctedOffset),
1931 1932 1933 1934
      mainAxisExtent: mainAxisExtent,
      crossAxisExtent: crossAxisExtent,
      growthDirection: GrowthDirection.forward,
      advance: childAfter,
1935 1936
      remainingCacheExtent: mainAxisExtent + 2 * _calculatedCacheExtent!,
      cacheOrigin: -_calculatedCacheExtent!,
1937 1938 1939 1940 1941 1942 1943
    );
  }

  @override
  bool get hasVisualOverflow => _hasVisualOverflow;

  @override
1944
  void updateOutOfBandData(GrowthDirection growthDirection, SliverGeometry childLayoutGeometry) {
1945 1946 1947 1948 1949 1950 1951 1952 1953 1954
    assert(growthDirection == GrowthDirection.forward);
    _maxScrollExtent += childLayoutGeometry.scrollExtent;
    if (childLayoutGeometry.hasVisualOverflow)
      _hasVisualOverflow = true;
    _shrinkWrapExtent += childLayoutGeometry.maxPaintExtent;
  }

  @override
  void updateChildLayoutOffset(RenderSliver child, double layoutOffset, GrowthDirection growthDirection) {
    assert(growthDirection == GrowthDirection.forward);
1955
    final SliverLogicalParentData childParentData = child.parentData! as SliverLogicalParentData;
1956 1957 1958 1959 1960
    childParentData.layoutOffset = layoutOffset;
  }

  @override
  Offset paintOffsetOf(RenderSliver child) {
1961
    final SliverLogicalParentData childParentData = child.parentData! as SliverLogicalParentData;
1962
    return computeAbsolutePaintOffset(child, childParentData.layoutOffset!, GrowthDirection.forward);
1963 1964 1965 1966 1967 1968 1969
  }

  @override
  double scrollOffsetOf(RenderSliver child, double scrollOffsetWithinChild) {
    assert(child.parent == this);
    assert(child.constraints.growthDirection == GrowthDirection.forward);
    double scrollOffsetToChild = 0.0;
1970
    RenderSliver? current = firstChild;
1971
    while (current != child) {
1972
      scrollOffsetToChild += current!.geometry!.scrollExtent;
1973 1974 1975 1976 1977
      current = childAfter(current);
    }
    return scrollOffsetToChild + scrollOffsetWithinChild;
  }

1978 1979 1980 1981 1982
  @override
  double maxScrollObstructionExtentBefore(RenderSliver child) {
    assert(child.parent == this);
    assert(child.constraints.growthDirection == GrowthDirection.forward);
    double pinnedExtent = 0.0;
1983
    RenderSliver? current = firstChild;
1984
    while (current != child) {
1985
      pinnedExtent += current!.geometry!.maxScrollObstructionExtent;
1986 1987 1988 1989 1990
      current = childAfter(current);
    }
    return pinnedExtent;
  }

1991 1992
  @override
  void applyPaintTransform(RenderObject child, Matrix4 transform) {
1993
    // Hit test logic relies on this always providing an invertible matrix.
1994
    assert(child != null);
1995
    final Offset offset = paintOffsetOf(child as RenderSliver);
1996 1997 1998 1999 2000 2001 2002 2003
    transform.translate(offset.dx, offset.dy);
  }

  @override
  double computeChildMainAxisPosition(RenderSliver child, double parentMainAxisPosition) {
    assert(child != null);
    assert(child.constraints != null);
    assert(hasSize);
2004
    final SliverLogicalParentData childParentData = child.parentData! as SliverLogicalParentData;
2005 2006 2007
    switch (applyGrowthDirectionToAxisDirection(child.constraints.axisDirection, child.constraints.growthDirection)) {
      case AxisDirection.down:
      case AxisDirection.right:
2008
        return parentMainAxisPosition - childParentData.layoutOffset!;
2009
      case AxisDirection.up:
2010
        return (size.height - parentMainAxisPosition) - childParentData.layoutOffset!;
2011
      case AxisDirection.left:
2012
        return (size.width - parentMainAxisPosition) - childParentData.layoutOffset!;
2013 2014 2015 2016
    }
  }

  @override
2017
  int get indexOfFirstChild => 0;
2018 2019 2020 2021 2022

  @override
  String labelForChild(int index) => 'child $index';

  @override
2023 2024
  Iterable<RenderSliver> get childrenInPaintOrder {
    final List<RenderSliver> children = <RenderSliver>[];
2025
    RenderSliver? child = lastChild;
2026
    while (child != null) {
2027
      children.add(child);
2028
      child = childBefore(child);
2029
    }
2030
    return children;
2031 2032 2033
  }

  @override
2034 2035
  Iterable<RenderSliver> get childrenInHitTestOrder {
    final List<RenderSliver> children = <RenderSliver>[];
2036
    RenderSliver? child = firstChild;
2037
    while (child != null) {
2038
      children.add(child);
2039
      child = childAfter(child);
2040
    }
2041
    return children;
2042 2043
  }
}