sliver.dart 81.2 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6 7 8 9
// 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;

import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';

10
import 'box.dart';
11 12
import 'debug.dart';
import 'object.dart';
13
import 'viewport.dart';
14
import 'viewport_offset.dart';
15 16 17 18

// CORE TYPES FOR SLIVERS
// The RenderSliver base class and its helper types.

19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
/// Called to get the item extent by the index of item.
///
/// Used by [ListView.itemExtentBuilder] and [SliverVariedExtentList.itemExtentBuilder].
typedef ItemExtentBuilder = double Function(int index, SliverLayoutDimensions dimensions);

/// Relates the dimensions of the [RenderSliver] during layout.
///
/// Used by [ListView.itemExtentBuilder] and [SliverVariedExtentList.itemExtentBuilder].
@immutable
class SliverLayoutDimensions {
  /// Constructs a [SliverLayoutDimensions] with the specified parameters.
  const SliverLayoutDimensions({
    required this.scrollOffset,
    required this.precedingScrollExtent,
    required this.viewportMainAxisExtent,
    required this.crossAxisExtent
  });

  /// {@macro flutter.rendering.SliverConstraints.scrollOffset}
  final double scrollOffset;

  /// {@macro flutter.rendering.SliverConstraints.precedingScrollExtent}
  final double precedingScrollExtent;

  /// The number of pixels the viewport can display in the main axis.
  ///
  /// For a vertical list, this is the height of the viewport.
  final double viewportMainAxisExtent;

  /// The number of pixels in the cross-axis.
  ///
  /// For a vertical list, this is the width of the sliver.
  final double crossAxisExtent;

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) {
      return true;
    }
    if (other is! SliverLayoutDimensions) {
      return false;
    }
    return other.scrollOffset == scrollOffset &&
      other.precedingScrollExtent == precedingScrollExtent &&
      other.viewportMainAxisExtent == viewportMainAxisExtent &&
      other.crossAxisExtent == crossAxisExtent;
  }

  @override
  String toString() {
    return 'scrollOffset: $scrollOffset'
      ' precedingScrollExtent: $precedingScrollExtent'
      ' viewportMainAxisExtent: $viewportMainAxisExtent'
      ' crossAxisExtent: $crossAxisExtent';
  }

  @override
  int get hashCode => Object.hash(
    scrollOffset,
    precedingScrollExtent,
    viewportMainAxisExtent,
    viewportMainAxisExtent
  );
}

84 85 86 87 88 89 90 91 92 93
/// The direction in which a sliver's contents are ordered, relative to the
/// scroll offset axis.
///
/// For example, a vertical alphabetical list that is going [AxisDirection.down]
/// with a [GrowthDirection.forward] would have the A at the top and the Z at
/// the bottom, with the A adjacent to the origin, as would such a list going
/// [AxisDirection.up] with a [GrowthDirection.reverse]. On the other hand, a
/// vertical alphabetical list that is going [AxisDirection.down] with a
/// [GrowthDirection.reverse] would have the Z at the top (at scroll offset
/// zero) and the A below it.
94
///
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
/// {@template flutter.rendering.GrowthDirection.sample}
/// Most scroll views by default are ordered [GrowthDirection.forward].
/// Changing the default values of [ScrollView.anchor],
/// [ScrollView.center], or both, can configure a scroll view for
/// [GrowthDirection.reverse].
///
/// {@tool dartpad}
/// This sample shows a [CustomScrollView], with [Radio] buttons in the
/// [AppBar.bottom] that change the [AxisDirection] to illustrate different
/// configurations. The [CustomScrollView.anchor] and [CustomScrollView.center]
/// properties are also set to have the 0 scroll offset positioned in the middle
/// of the viewport, with [GrowthDirection.forward] and [GrowthDirection.reverse]
/// illustrated on either side. The sliver that shares the
/// [CustomScrollView.center] key is positioned at the [CustomScrollView.anchor].
///
/// ** See code in examples/api/lib/rendering/growth_direction/growth_direction.0.dart **
/// {@end-tool}
/// {@endtemplate}
///
/// See also:
///
///   * [applyGrowthDirectionToAxisDirection], which returns the direction in
///     which the scroll offset increases.
118
enum GrowthDirection {
119
  /// This sliver's contents are ordered in the same direction as the
120 121 122 123 124 125 126 127
  /// [AxisDirection]. For example, a vertical alphabetical list that is going
  /// [AxisDirection.down] with a [GrowthDirection.forward] would have the A at
  /// the top and the Z at the bottom, with the A adjacent to the origin.
  ///
  /// See also:
  ///
  ///   * [applyGrowthDirectionToAxisDirection], which returns the direction in
  ///     which the scroll offset increases.
128 129
  forward,

130 131
  /// This sliver's contents are ordered in the opposite direction of the
  /// [AxisDirection].
132 133 134 135 136
  ///
  /// See also:
  ///
  ///   * [applyGrowthDirectionToAxisDirection], which returns the direction in
  ///     which the scroll offset increases.
137 138 139
  reverse,
}

140 141 142 143 144 145 146 147 148
/// Flips the [AxisDirection] if the [GrowthDirection] is [GrowthDirection.reverse].
///
/// Specifically, returns `axisDirection` if `growthDirection` is
/// [GrowthDirection.forward], otherwise returns [flipAxisDirection] applied to
/// `axisDirection`.
///
/// This function is useful in [RenderSliver] subclasses that are given both an
/// [AxisDirection] and a [GrowthDirection] and wish to compute the
/// [AxisDirection] in which growth will occur.
149 150 151 152 153
AxisDirection applyGrowthDirectionToAxisDirection(AxisDirection axisDirection, GrowthDirection growthDirection) {
  switch (growthDirection) {
    case GrowthDirection.forward:
      return axisDirection;
    case GrowthDirection.reverse:
154
      return flipAxisDirection(axisDirection);
155 156 157
  }
}

158 159
/// Flips the [ScrollDirection] if the [GrowthDirection] is
/// [GrowthDirection.reverse].
160 161
///
/// Specifically, returns `scrollDirection` if `scrollDirection` is
162 163
/// [GrowthDirection.forward], otherwise returns [flipScrollDirection] applied
/// to `scrollDirection`.
164 165 166 167
///
/// This function is useful in [RenderSliver] subclasses that are given both an
/// [ScrollDirection] and a [GrowthDirection] and wish to compute the
/// [ScrollDirection] in which growth will occur.
Josh Soref's avatar
Josh Soref committed
168
ScrollDirection applyGrowthDirectionToScrollDirection(ScrollDirection scrollDirection, GrowthDirection growthDirection) {
169 170 171 172 173 174 175 176
  switch (growthDirection) {
    case GrowthDirection.forward:
      return scrollDirection;
    case GrowthDirection.reverse:
      return flipScrollDirection(scrollDirection);
  }
}

177 178 179 180 181 182 183
/// Immutable layout constraints for [RenderSliver] layout.
///
/// The [SliverConstraints] describe the current scroll state of the viewport
/// from the point of view of the sliver receiving the constraints. For example,
/// a [scrollOffset] of zero means that the leading edge of the sliver is
/// visible in the viewport, not that the viewport itself has a zero scroll
/// offset.
184
class SliverConstraints extends Constraints {
185
  /// Creates sliver constraints with the given information.
186
  const SliverConstraints({
187 188 189 190 191 192 193 194 195 196 197 198
    required this.axisDirection,
    required this.growthDirection,
    required this.userScrollDirection,
    required this.scrollOffset,
    required this.precedingScrollExtent,
    required this.overlap,
    required this.remainingPaintExtent,
    required this.crossAxisExtent,
    required this.crossAxisDirection,
    required this.viewportMainAxisExtent,
    required this.remainingCacheExtent,
    required this.cacheOrigin,
199
  });
200

201 202
  /// Creates a copy of this object but with the given fields replaced with the
  /// new values.
203
  SliverConstraints copyWith({
204 205 206 207 208 209 210 211 212 213 214 215
    AxisDirection? axisDirection,
    GrowthDirection? growthDirection,
    ScrollDirection? userScrollDirection,
    double? scrollOffset,
    double? precedingScrollExtent,
    double? overlap,
    double? remainingPaintExtent,
    double? crossAxisExtent,
    AxisDirection? crossAxisDirection,
    double? viewportMainAxisExtent,
    double? remainingCacheExtent,
    double? cacheOrigin,
216
  }) {
217
    return SliverConstraints(
218 219 220 221
      axisDirection: axisDirection ?? this.axisDirection,
      growthDirection: growthDirection ?? this.growthDirection,
      userScrollDirection: userScrollDirection ?? this.userScrollDirection,
      scrollOffset: scrollOffset ?? this.scrollOffset,
222
      precedingScrollExtent: precedingScrollExtent ?? this.precedingScrollExtent,
223 224 225
      overlap: overlap ?? this.overlap,
      remainingPaintExtent: remainingPaintExtent ?? this.remainingPaintExtent,
      crossAxisExtent: crossAxisExtent ?? this.crossAxisExtent,
226
      crossAxisDirection: crossAxisDirection ?? this.crossAxisDirection,
227
      viewportMainAxisExtent: viewportMainAxisExtent ?? this.viewportMainAxisExtent,
228 229
      remainingCacheExtent: remainingCacheExtent ?? this.remainingCacheExtent,
      cacheOrigin: cacheOrigin ?? this.cacheOrigin,
230 231 232 233 234
    );
  }

  /// The direction in which the [scrollOffset] and [remainingPaintExtent]
  /// increase.
235 236 237 238 239 240 241 242
  ///
  /// {@tool dartpad}
  /// This sample shows a [CustomScrollView], with [Radio] buttons in the
  /// [AppBar.bottom] that change the [AxisDirection] to illustrate different
  /// configurations.
  ///
  /// ** See code in examples/api/lib/painting/axis_direction/axis_direction.0.dart **
  /// {@end-tool}
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
  final AxisDirection axisDirection;

  /// The direction in which the contents of slivers are ordered, relative to
  /// the [axisDirection].
  ///
  /// For example, if the [axisDirection] is [AxisDirection.up], and the
  /// [growthDirection] is [GrowthDirection.forward], then an alphabetical list
  /// will have A at the bottom, then B, then C, and so forth, with Z at the
  /// top, with the bottom of the A at scroll offset zero, and the top of the Z
  /// at the highest scroll offset.
  ///
  /// If a viewport has an overall [AxisDirection] of [AxisDirection.down], then
  /// slivers above the absolute zero offset will have an axis of
  /// [AxisDirection.up] and a growth direction of [GrowthDirection.reverse],
  /// while slivers below the absolute zero offset will have the same axis
  /// direction as the viewport and a growth direction of
  /// [GrowthDirection.forward]. (The slivers with a reverse growth direction
  /// still see only positive scroll offsets; the scroll offsets are reversed as
  /// well, with zero at the absolute zero point, and positive numbers going
  /// away from there.)
  ///
264 265
  /// Normally, the absolute zero offset is determined by the viewport's
  /// [RenderViewport.center] and [RenderViewport.anchor] properties.
266 267
  ///
  /// {@macro flutter.rendering.GrowthDirection.sample}
268 269 270 271 272
  final GrowthDirection growthDirection;

  /// The direction in which the user is attempting to scroll, relative to the
  /// [axisDirection] and [growthDirection].
  ///
273
  /// For example, if [growthDirection] is [GrowthDirection.forward] and
274
  /// [axisDirection] is [AxisDirection.down], then a
275
  /// [ScrollDirection.reverse] means that the user is scrolling down, in the
276
  /// positive [scrollOffset] direction.
277 278 279 280 281 282 283 284 285
  ///
  /// If the _user_ is not scrolling, this will return [ScrollDirection.idle]
  /// even if there is (for example) a [ScrollActivity] currently animating the
  /// position.
  ///
  /// This is used by some slivers to determine how to react to a change in
  /// scroll offset. For example, [RenderSliverFloatingPersistentHeader] will
  /// only expand a floating app bar when the [userScrollDirection] is in the
  /// positive scroll offset direction.
286 287
  ///
  /// {@macro flutter.rendering.ScrollDirection.sample}
288 289
  final ScrollDirection userScrollDirection;

290
  /// {@template flutter.rendering.SliverConstraints.scrollOffset}
291
  /// The scroll offset, in this sliver's coordinate system, that corresponds to
292
  /// the earliest visible part of this sliver in the [AxisDirection] if
293 294
  /// [SliverConstraints.growthDirection] is [GrowthDirection.forward] or in the opposite
  /// [AxisDirection] direction if [SliverConstraints.growthDirection] is [GrowthDirection.reverse].
295
  ///
296
  /// For example, if [AxisDirection] is [AxisDirection.down] and [SliverConstraints.growthDirection]
297 298
  /// is [GrowthDirection.forward], then scroll offset is the amount the top of
  /// the sliver has been scrolled past the top of the viewport.
299 300 301 302 303 304 305
  ///
  /// This value is typically used to compute whether this sliver should still
  /// protrude into the viewport via [SliverGeometry.paintExtent] and
  /// [SliverGeometry.layoutExtent] considering how far the beginning of the
  /// sliver is above the beginning of the viewport.
  ///
  /// For slivers whose top is not past the top of the viewport, the
306
  /// [scrollOffset] is `0` when [AxisDirection] is [AxisDirection.down] and
307
  /// [SliverConstraints.growthDirection] is [GrowthDirection.forward]. The set of slivers with
308 309
  /// [scrollOffset] `0` includes all the slivers that are below the bottom of the
  /// viewport.
310 311 312 313
  ///
  /// [SliverConstraints.remainingPaintExtent] is typically used to accomplish
  /// the same goal of computing whether scrolled out slivers should still
  /// partially 'protrude in' from the bottom of the viewport.
314 315
  ///
  /// Whether this corresponds to the beginning or the end of the sliver's
316 317
  /// contents depends on the [SliverConstraints.growthDirection].
  /// {@endtemplate}
318 319
  final double scrollOffset;

320
  /// {@template flutter.rendering.SliverConstraints.precedingScrollExtent}
321 322
  /// The scroll distance that has been consumed by all [RenderSliver]s that
  /// came before this [RenderSliver].
323 324 325
  ///
  /// # Edge Cases
  ///
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
  /// [RenderSliver]s often lazily create their internal content as layout
  /// occurs, e.g., [SliverList]. In this case, when [RenderSliver]s exceed the
  /// viewport, their children are built lazily, and the [RenderSliver] does not
  /// have enough information to estimate its total extent,
  /// [precedingScrollExtent] will be [double.infinity] for all [RenderSliver]s
  /// that appear after the lazily constructed child. This is because a total
  /// [SliverGeometry.scrollExtent] cannot be calculated unless all inner
  /// children have been created and sized, or the number of children and
  /// estimated extents are provided. The infinite [SliverGeometry.scrollExtent]
  /// will become finite as soon as enough information is available to estimate
  /// the overall extent of all children within the given [RenderSliver].
  ///
  /// [RenderSliver]s may legitimately be infinite, meaning that they can scroll
  /// content forever without reaching the end. For any [RenderSliver]s that
  /// appear after the infinite [RenderSliver], the [precedingScrollExtent] will
  /// be [double.infinity].
342
  /// {@endtemplate}
343 344
  final double precedingScrollExtent;

345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
  /// The number of pixels from where the pixels corresponding to the
  /// [scrollOffset] will be painted up to the first pixel that has not yet been
  /// painted on by an earlier sliver, in the [axisDirection].
  ///
  /// For example, if the previous sliver had a [SliverGeometry.paintExtent] of
  /// 100.0 pixels but a [SliverGeometry.layoutExtent] of only 50.0 pixels,
  /// then the [overlap] of this sliver will be 50.0.
  ///
  /// This is typically ignored unless the sliver is itself going to be pinned
  /// or floating and wants to avoid doing so under the previous sliver.
  final double overlap;

  /// The number of pixels of content that the sliver should consider providing.
  /// (Providing more pixels than this is inefficient.)
  ///
  /// The actual number of pixels provided should be specified in the
  /// [RenderSliver.geometry] as [SliverGeometry.paintExtent].
362 363 364 365 366 367
  ///
  /// This value may be infinite, for example if the viewport is an
  /// unconstrained [RenderShrinkWrappingViewport].
  ///
  /// This value may be 0.0, for example if the sliver is scrolled off the
  /// bottom of a downwards vertical viewport.
368 369
  final double remainingPaintExtent;

370 371
  /// The number of pixels in the cross-axis.
  ///
372
  /// For a vertical list, this is the width of the sliver.
373 374
  final double crossAxisExtent;

375 376 377 378 379 380
  /// The direction in which children should be placed in the cross axis.
  ///
  /// Typically used in vertical lists to describe whether the ambient
  /// [TextDirection] is [TextDirection.rtl] or [TextDirection.ltr].
  final AxisDirection crossAxisDirection;

381 382 383 384 385
  /// The number of pixels the viewport can display in the main axis.
  ///
  /// For a vertical list, this is the height of the viewport.
  final double viewportMainAxisExtent;

386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
  /// Where the cache area starts relative to the [scrollOffset].
  ///
  /// Slivers that fall into the cache area located before the leading edge and
  /// after the trailing edge of the viewport should still render content
  /// because they are about to become visible when the user scrolls.
  ///
  /// The [cacheOrigin] describes where the [remainingCacheExtent] starts relative
  /// to the [scrollOffset]. A cache origin of 0 means that the sliver does not
  /// have to provide any content before the current [scrollOffset]. A
  /// [cacheOrigin] of -250.0 means that even though the first visible part of
  /// the sliver will be at the provided [scrollOffset], the sliver should
  /// render content starting 250.0 before the [scrollOffset] to fill the
  /// cache area of the viewport.
  ///
  /// The [cacheOrigin] is always negative or zero and will never exceed
  /// -[scrollOffset]. In other words, a sliver is never asked to provide
  /// content before its zero [scrollOffset].
  ///
  /// See also:
405
  ///
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
  ///  * [RenderViewport.cacheExtent] for a description of a viewport's cache area.
  final double cacheOrigin;


  /// Describes how much content the sliver should provide starting from the
  /// [cacheOrigin].
  ///
  /// Not all content in the [remainingCacheExtent] will be visible as some
  /// of it might fall into the cache area of the viewport.
  ///
  /// Each sliver should start laying out content at the [cacheOrigin] and
  /// try to provide as much content as the [remainingCacheExtent] allows.
  ///
  /// The [remainingCacheExtent] is always larger or equal to the
  /// [remainingPaintExtent]. Content, that falls in the [remainingCacheExtent],
  /// but is outside of the [remainingPaintExtent] is currently not visible
  /// in the viewport.
  ///
  /// See also:
425
  ///
426 427 428
  ///  * [RenderViewport.cacheExtent] for a description of a viewport's cache area.
  final double remainingCacheExtent;

429
  /// The axis along which the [scrollOffset] and [remainingPaintExtent] are measured.
430
  Axis get axis => axisDirectionToAxis(axisDirection);
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463

  /// Return what the [growthDirection] would be if the [axisDirection] was
  /// either [AxisDirection.down] or [AxisDirection.right].
  ///
  /// This is the same as [growthDirection] unless the [axisDirection] is either
  /// [AxisDirection.up] or [AxisDirection.left], in which case it is the
  /// opposite growth direction.
  ///
  /// This can be useful in combination with [axis] to view the [axisDirection]
  /// and [growthDirection] in different terms.
  GrowthDirection get normalizedGrowthDirection {
    switch (axisDirection) {
      case AxisDirection.down:
      case AxisDirection.right:
        return growthDirection;
      case AxisDirection.up:
      case AxisDirection.left:
        switch (growthDirection) {
          case GrowthDirection.forward:
            return GrowthDirection.reverse;
          case GrowthDirection.reverse:
            return GrowthDirection.forward;
        }
    }
  }

  @override
  bool get isTight => false;

  @override
  bool get isNormalized {
    return scrollOffset >= 0.0
        && crossAxisExtent >= 0.0
464
        && axisDirectionToAxis(axisDirection) != axisDirectionToAxis(crossAxisDirection)
465
        && viewportMainAxisExtent >= 0.0
466 467 468
        && remainingPaintExtent >= 0.0;
  }

469 470 471 472 473 474 475 476
  /// Returns [BoxConstraints] that reflects the sliver constraints.
  ///
  /// The `minExtent` and `maxExtent` are used as the constraints in the main
  /// axis. If non-null, the given `crossAxisExtent` is used as a tight
  /// constraint in the cross axis. Otherwise, the [crossAxisExtent] from this
  /// object is used as a constraint in the cross axis.
  ///
  /// Useful for slivers that have [RenderBox] children.
477
  BoxConstraints asBoxConstraints({
478 479
    double minExtent = 0.0,
    double maxExtent = double.infinity,
480
    double? crossAxisExtent,
481
  }) {
482
    crossAxisExtent ??= this.crossAxisExtent;
483 484
    switch (axis) {
      case Axis.horizontal:
485
        return BoxConstraints(
486 487 488 489 490 491
          minHeight: crossAxisExtent,
          maxHeight: crossAxisExtent,
          minWidth: minExtent,
          maxWidth: maxExtent,
        );
      case Axis.vertical:
492
        return BoxConstraints(
493 494 495 496 497 498 499 500 501 502
          minWidth: crossAxisExtent,
          maxWidth: crossAxisExtent,
          minHeight: minExtent,
          maxHeight: maxExtent,
        );
    }
  }

  @override
  bool debugAssertIsValid({
503
    bool isAppliedConstraint = false,
504
    InformationCollector? informationCollector,
505
  }) {
506
    assert(() {
507 508
      bool hasErrors = false;
      final StringBuffer errorMessage = StringBuffer('\n');
509
      void verify(bool check, String message) {
510
        if (check) {
511
          return;
512
        }
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
        hasErrors = true;
        errorMessage.writeln('  $message');
      }
      void verifyDouble(double property, String name, {bool mustBePositive = false, bool mustBeNegative = false}) {
        if (property.isNaN) {
          String additional = '.';
          if (mustBePositive) {
            additional = ', expected greater than or equal to zero.';
          } else if (mustBeNegative) {
            additional = ', expected less than or equal to zero.';
          }
          verify(false, 'The "$name" is NaN$additional');
        } else if (mustBePositive) {
          verify(property >= 0.0, 'The "$name" is negative.');
        } else if (mustBeNegative) {
          verify(property <= 0.0, 'The "$name" is positive.');
        }
530
      }
531 532 533 534
      verifyDouble(scrollOffset, 'scrollOffset');
      verifyDouble(overlap, 'overlap');
      verifyDouble(crossAxisExtent, 'crossAxisExtent');
      verifyDouble(scrollOffset, 'scrollOffset', mustBePositive: true);
535
      verify(axisDirectionToAxis(axisDirection) != axisDirectionToAxis(crossAxisDirection), 'The "axisDirection" and the "crossAxisDirection" are along the same axis.');
536 537 538 539 540
      verifyDouble(viewportMainAxisExtent, 'viewportMainAxisExtent', mustBePositive: true);
      verifyDouble(remainingPaintExtent, 'remainingPaintExtent', mustBePositive: true);
      verifyDouble(remainingCacheExtent, 'remainingCacheExtent', mustBePositive: true);
      verifyDouble(cacheOrigin, 'cacheOrigin', mustBeNegative: true);
      verifyDouble(precedingScrollExtent, 'precedingScrollExtent', mustBePositive: true);
541
      verify(isNormalized, 'The constraints are not normalized.'); // should be redundant with earlier checks
542 543 544 545 546 547 548 549
      if (hasErrors) {
        throw FlutterError.fromParts(<DiagnosticsNode>[
          ErrorSummary('$runtimeType is not valid: $errorMessage'),
          if (informationCollector != null)
            ...informationCollector(),
          DiagnosticsProperty<SliverConstraints>('The offending constraints were', this, style: DiagnosticsTreeStyle.errorProperty),
        ]);
      }
550
      return true;
551
    }());
552 553 554 555
    return true;
  }

  @override
556
  bool operator ==(Object other) {
557
    if (identical(this, other)) {
558
      return true;
559 560
    }
    if (other is! SliverConstraints) {
561
      return false;
562
    }
563 564
    assert(other.debugAssertIsValid());
    return other.axisDirection == axisDirection
565 566 567 568 569 570 571 572 573
        && other.growthDirection == growthDirection
        && other.scrollOffset == scrollOffset
        && other.overlap == overlap
        && other.remainingPaintExtent == remainingPaintExtent
        && other.crossAxisExtent == crossAxisExtent
        && other.crossAxisDirection == crossAxisDirection
        && other.viewportMainAxisExtent == viewportMainAxisExtent
        && other.remainingCacheExtent == remainingCacheExtent
        && other.cacheOrigin == cacheOrigin;
574 575 576
  }

  @override
577 578 579 580 581 582 583 584 585 586 587 588
  int get hashCode => Object.hash(
    axisDirection,
    growthDirection,
    scrollOffset,
    overlap,
    remainingPaintExtent,
    crossAxisExtent,
    crossAxisDirection,
    viewportMainAxisExtent,
    remainingCacheExtent,
    cacheOrigin,
  );
589 590 591

  @override
  String toString() {
592 593 594 595 596 597 598 599 600 601 602 603 604 605
    final List<String> properties = <String>[
      '$axisDirection',
      '$growthDirection',
      '$userScrollDirection',
      'scrollOffset: ${scrollOffset.toStringAsFixed(1)}',
      'remainingPaintExtent: ${remainingPaintExtent.toStringAsFixed(1)}',
      if (overlap != 0.0) 'overlap: ${overlap.toStringAsFixed(1)}',
      'crossAxisExtent: ${crossAxisExtent.toStringAsFixed(1)}',
      'crossAxisDirection: $crossAxisDirection',
      'viewportMainAxisExtent: ${viewportMainAxisExtent.toStringAsFixed(1)}',
      'remainingCacheExtent: ${remainingCacheExtent.toStringAsFixed(1)}',
      'cacheOrigin: ${cacheOrigin.toStringAsFixed(1)}',
    ];
    return 'SliverConstraints(${properties.join(', ')})';
606 607 608
  }
}

609 610 611 612
/// Describes the amount of space occupied by a [RenderSliver].
///
/// A sliver can occupy space in several different ways, which is why this class
/// contains multiple values.
613
@immutable
614
class SliverGeometry with Diagnosticable {
615 616 617 618 619 620
  /// Creates an object that describes the amount of space occupied by a sliver.
  ///
  /// If the [layoutExtent] argument is null, [layoutExtent] defaults to the
  /// [paintExtent]. If the [hitTestExtent] argument is null, [hitTestExtent]
  /// defaults to the [paintExtent]. If [visible] is null, [visible] defaults to
  /// whether [paintExtent] is greater than zero.
621
  const SliverGeometry({
622 623 624
    this.scrollExtent = 0.0,
    this.paintExtent = 0.0,
    this.paintOrigin = 0.0,
625
    double? layoutExtent,
626 627
    this.maxPaintExtent = 0.0,
    this.maxScrollObstructionExtent = 0.0,
628
    this.crossAxisExtent,
629 630
    double? hitTestExtent,
    bool? visible,
631
    this.hasVisualOverflow = false,
632
    this.scrollOffsetCorrection,
633
    double? cacheExtent,
634
  }) : assert(scrollOffsetCorrection != 0.0),
635
       layoutExtent = layoutExtent ?? paintExtent,
636
       hitTestExtent = hitTestExtent ?? paintExtent,
637
       cacheExtent = cacheExtent ?? layoutExtent ?? paintExtent,
638 639
       visible = visible ?? paintExtent > 0.0;

640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
  /// Creates a copy of this object but with the given fields replaced with the
  /// new values.
  SliverGeometry copyWith({
    double? scrollExtent,
    double? paintExtent,
    double? paintOrigin,
    double? layoutExtent,
    double? maxPaintExtent,
    double? maxScrollObstructionExtent,
    double? crossAxisExtent,
    double? hitTestExtent,
    bool? visible,
    bool? hasVisualOverflow,
    double? cacheExtent,
  }) {
    return SliverGeometry(
      scrollExtent: scrollExtent ?? this.scrollExtent,
      paintExtent: paintExtent ?? this.paintExtent,
      paintOrigin: paintOrigin ?? this.paintOrigin,
      layoutExtent: layoutExtent ?? this.layoutExtent,
      maxPaintExtent: maxPaintExtent ?? this.maxPaintExtent,
      maxScrollObstructionExtent: maxScrollObstructionExtent ?? this.maxScrollObstructionExtent,
      crossAxisExtent: crossAxisExtent ?? this.crossAxisExtent,
      hitTestExtent: hitTestExtent ?? this.hitTestExtent,
      visible: visible ?? this.visible,
      hasVisualOverflow: hasVisualOverflow ?? this.hasVisualOverflow,
      cacheExtent: cacheExtent ?? this.cacheExtent,
    );
  }

670
  /// A sliver that occupies no space at all.
671
  static const SliverGeometry zero = SliverGeometry();
672

673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
  /// The (estimated) total scrollable extent that this sliver has content for.
  ///
  /// This is the amount of scrolling the user needs to do to get from the
  /// beginning of this sliver to the end of this sliver.
  ///
  /// The value is used to calculate the [SliverConstraints.scrollOffset] of
  /// all slivers in the scrollable and thus should be provided whether the
  /// sliver is currently in the viewport or not.
  ///
  /// In a typical scrolling scenario, the [scrollExtent] is constant for a
  /// sliver throughout the scrolling while [paintExtent] and [layoutExtent]
  /// will progress from `0` when offscreen to between `0` and [scrollExtent]
  /// as the sliver scrolls partially into and out of the screen and is
  /// equal to [scrollExtent] while the sliver is entirely on screen. However,
  /// these relationships can be customized to achieve more special effects.
688 689 690 691 692
  ///
  /// This value must be accurate if the [paintExtent] is less than the
  /// [SliverConstraints.remainingPaintExtent] provided during layout.
  final double scrollExtent;

693 694 695 696 697
  /// The visual location of the first visible part of this sliver relative to
  /// its layout position.
  ///
  /// For example, if the sliver wishes to paint visually before its layout
  /// position, the [paintOrigin] is negative. The coordinate system this sliver
698 699 700 701 702 703 704 705 706 707
  /// uses for painting is relative to this [paintOrigin]. In other words,
  /// when [RenderSliver.paint] is called, the (0, 0) position of the [Offset]
  /// given to it is at this [paintOrigin].
  ///
  /// The coordinate system used for the [paintOrigin] itself is relative
  /// to the start of this sliver's layout position rather than relative to
  /// its current position on the viewport. In other words, in a typical
  /// scrolling scenario, [paintOrigin] remains constant at 0.0 rather than
  /// tracking from 0.0 to [SliverConstraints.viewportMainAxisExtent] as the
  /// sliver scrolls past the viewport.
708 709 710 711 712 713 714 715 716 717 718
  ///
  /// This value does not affect the layout of subsequent slivers. The next
  /// sliver is still placed at [layoutExtent] after this sliver's layout
  /// position. This value does affect where the [paintExtent] extent is
  /// measured from when computing the [SliverConstraints.overlap] for the next
  /// sliver.
  ///
  /// Defaults to 0.0, which means slivers start painting at their layout
  /// position by default.
  final double paintOrigin;

719 720 721 722 723 724 725 726
  /// The amount of currently visible visual space that was taken by the sliver
  /// to render the subset of the sliver that covers all or part of the
  /// [SliverConstraints.remainingPaintExtent] in the current viewport.
  ///
  /// This value does not affect how the next sliver is positioned. In other
  /// words, if this value was 100 and [layoutExtent] was 0, typical slivers
  /// placed after it would end up drawing in the same 100 pixel space while
  /// painting.
727 728 729
  ///
  /// This must be between zero and [SliverConstraints.remainingPaintExtent].
  ///
730 731 732 733 734
  /// This value is typically 0 when outside of the viewport and grows or
  /// shrinks from 0 or to 0 as the sliver is being scrolled into and out of the
  /// viewport unless the sliver wants to achieve a special effect and paint
  /// even when scrolled away.
  ///
735 736 737 738 739 740 741 742 743
  /// This contributes to the calculation for the next sliver's
  /// [SliverConstraints.overlap].
  final double paintExtent;

  /// The distance from the first visible part of this sliver to the first
  /// visible part of the next sliver, assuming the next sliver's
  /// [SliverConstraints.scrollOffset] is zero.
  ///
  /// This must be between zero and [paintExtent]. It defaults to [paintExtent].
744 745 746
  ///
  /// This value is typically 0 when outside of the viewport and grows or
  /// shrinks from 0 or to 0 as the sliver is being scrolled into and out of the
747
  /// viewport unless the sliver wants to achieve a special effect and push
748 749
  /// down the layout start position of subsequent slivers before the sliver is
  /// even scrolled into the viewport.
750 751 752 753 754
  final double layoutExtent;

  /// The (estimated) total paint extent that this sliver would be able to
  /// provide if the [SliverConstraints.remainingPaintExtent] was infinite.
  ///
755
  /// This is used by viewports that implement shrink-wrapping.
756 757 758 759
  ///
  /// By definition, this cannot be less than [paintExtent].
  final double maxPaintExtent;

760 761 762 763 764 765 766 767 768 769
  /// The maximum extent by which this sliver can reduce the area in which
  /// content can scroll if the sliver were pinned at the edge.
  ///
  /// Slivers that never get pinned at the edge, should return zero.
  ///
  /// A pinned app bar is an example for a sliver that would use this setting:
  /// When the app bar is pinned to the top, the area in which content can
  /// actually scroll is reduced by the height of the app bar.
  final double maxScrollObstructionExtent;

770 771 772 773 774 775 776 777 778 779 780 781
  /// The distance from where this sliver started painting to the bottom of
  /// where it should accept hits.
  ///
  /// This must be between zero and [paintExtent]. It defaults to [paintExtent].
  final double hitTestExtent;

  /// Whether this sliver should be painted.
  ///
  /// By default, this is true if [paintExtent] is greater than zero, and
  /// false if [paintExtent] is zero.
  final bool visible;

782 783 784 785 786 787 788
  /// Whether this sliver has visual overflow.
  ///
  /// By default, this is false, which means the viewport does not need to clip
  /// its children. If any slivers have visual overflow, the viewport will apply
  /// a clip to its children.
  final bool hasVisualOverflow;

789 790 791
  /// If this is non-zero after [RenderSliver.performLayout] returns, the scroll
  /// offset will be adjusted by the parent and then the entire layout of the
  /// parent will be rerun.
792
  ///
793 794 795 796
  /// When the value is non-zero, the [RenderSliver] does not need to compute
  /// the rest of the values when constructing the [SliverGeometry] or call
  /// [RenderObject.layout] on its children since [RenderSliver.performLayout]
  /// will be called again on this sliver in the same frame after the
797
  /// [SliverConstraints.scrollOffset] correction has been applied, when the
798 799
  /// proper [SliverGeometry] and layout of its children can be computed.
  ///
800 801 802
  /// If the parent is also a [RenderSliver], it must propagate this value
  /// in its own [RenderSliver.geometry] property until a viewport which adjusts
  /// its offset based on this value.
803
  final double? scrollOffsetCorrection;
804

805 806 807 808
  /// How many pixels the sliver has consumed in the
  /// [SliverConstraints.remainingCacheExtent].
  ///
  /// This value should be equal to or larger than the [layoutExtent] because
809
  /// the sliver always consumes at least the [layoutExtent] from the
810 811 812 813
  /// [SliverConstraints.remainingCacheExtent] and possibly more if it falls
  /// into the cache area of the viewport.
  ///
  /// See also:
814
  ///
815 816 817
  ///  * [RenderViewport.cacheExtent] for a description of a viewport's cache area.
  final double cacheExtent;

818 819 820 821 822 823 824 825 826 827
  /// The amount of space allocated to the cross axis.
  ///
  /// This value will be typically null unless it is different from
  /// [SliverConstraints.crossAxisExtent]. If null, then the cross axis extent of
  /// the sliver is assumed to be the same as the [SliverConstraints.crossAxisExtent].
  /// This is because slivers typically consume all of the extent that is available
  /// in the cross axis.
  ///
  /// See also:
  ///
828 829 830 831
  ///  * [SliverConstrainedCrossAxis] for an example of a sliver which takes up
  ///    a smaller cross axis extent than the provided constraint.
  ///  * [SliverCrossAxisGroup] for an example of a sliver which makes use of this
  ///  [crossAxisExtent] to lay out their children.
832 833
  final double? crossAxisExtent;

834 835 836
  /// Asserts that this geometry is internally consistent.
  ///
  /// Does nothing if asserts are disabled. Always returns true.
837
  bool debugAssertIsValid({
838
    InformationCollector? informationCollector,
839
  }) {
840
    assert(() {
841
      void verify(bool check, String summary, {List<DiagnosticsNode>? details}) {
842
        if (check) {
843
          return;
844
        }
845
        throw FlutterError.fromParts(<DiagnosticsNode>[
846
          ErrorSummary('${objectRuntimeType(this, 'SliverGeometry')} is not valid: $summary'),
847 848 849 850
          ...?details,
          if (informationCollector != null)
            ...informationCollector(),
        ]);
851
      }
852

853 854 855
      verify(scrollExtent >= 0.0, 'The "scrollExtent" is negative.');
      verify(paintExtent >= 0.0, 'The "paintExtent" is negative.');
      verify(layoutExtent >= 0.0, 'The "layoutExtent" is negative.');
856
      verify(cacheExtent >= 0.0, 'The "cacheExtent" is negative.');
857
      if (layoutExtent > paintExtent) {
858
        verify(false,
859 860
          'The "layoutExtent" exceeds the "paintExtent".',
          details: _debugCompareFloats('paintExtent', paintExtent, 'layoutExtent', layoutExtent),
861 862
        );
      }
863
      // If the paintExtent is slightly more than the maxPaintExtent, but the difference is still less
864 865
      // than precisionErrorTolerance, we will not throw the assert below.
      if (paintExtent - maxPaintExtent > precisionErrorTolerance) {
866
        verify(false,
867 868 869
          'The "maxPaintExtent" is less than the "paintExtent".',
          details:
            _debugCompareFloats('maxPaintExtent', maxPaintExtent, 'paintExtent', paintExtent)
870
              ..add(ErrorDescription("By definition, a sliver can't paint more than the maximum that it can paint!")),
871 872
        );
      }
873
      verify(hitTestExtent >= 0.0, 'The "hitTestExtent" is negative.');
874
      verify(scrollOffsetCorrection != 0.0, 'The "scrollOffsetCorrection" is zero.');
875
      return true;
876
    }());
877 878 879 880
    return true;
  }

  @override
881
  String toStringShort() => objectRuntimeType(this, 'SliverGeometry');
882 883

  @override
884 885
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
886
    properties.add(DoubleProperty('scrollExtent', scrollExtent));
887
    if (paintExtent > 0.0) {
888
      properties.add(DoubleProperty('paintExtent', paintExtent, unit : visible ? null : ' but not painting'));
889 890
    } else if (paintExtent == 0.0) {
      if (visible) {
891
        properties.add(DoubleProperty('paintExtent', paintExtent, unit: visible ? null : ' but visible'));
892
      }
893
      properties.add(FlagProperty('visible', value: visible, ifFalse: 'hidden'));
894 895
    } else {
      // Negative paintExtent!
896
      properties.add(DoubleProperty('paintExtent', paintExtent, tooltip: '!'));
897
    }
898 899 900 901 902 903 904
    properties.add(DoubleProperty('paintOrigin', paintOrigin, defaultValue: 0.0));
    properties.add(DoubleProperty('layoutExtent', layoutExtent, defaultValue: paintExtent));
    properties.add(DoubleProperty('maxPaintExtent', maxPaintExtent));
    properties.add(DoubleProperty('hitTestExtent', hitTestExtent, defaultValue: paintExtent));
    properties.add(DiagnosticsProperty<bool>('hasVisualOverflow', hasVisualOverflow, defaultValue: false));
    properties.add(DoubleProperty('scrollOffsetCorrection', scrollOffsetCorrection, defaultValue: null));
    properties.add(DoubleProperty('cacheExtent', cacheExtent, defaultValue: 0.0));
905 906 907
  }
}

908
/// Method signature for hit testing a [RenderSliver].
909 910 911 912 913 914 915 916
///
/// Used by [SliverHitTestResult.addWithAxisOffset] to hit test [RenderSliver]
/// children.
///
/// See also:
///
///  * [RenderSliver.hitTest], which documents more details around hit testing
///    [RenderSliver]s.
917
typedef SliverHitTest = bool Function(SliverHitTestResult result, { required double mainAxisPosition, required double crossAxisPosition });
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944

/// The result of performing a hit test on [RenderSliver]s.
///
/// An instance of this class is provided to [RenderSliver.hitTest] to record
/// the result of the hit test.
class SliverHitTestResult extends HitTestResult {
  /// Creates an empty hit test result for hit testing on [RenderSliver].
  SliverHitTestResult() : super();

  /// Wraps `result` to create a [HitTestResult] that implements the
  /// [SliverHitTestResult] protocol for hit testing on [RenderSliver]s.
  ///
  /// This method is used by [RenderObject]s that adapt between the
  /// [RenderSliver]-world and the non-[RenderSliver]-world to convert a
  /// (subtype of) [HitTestResult] to a [SliverHitTestResult] for hit testing on
  /// [RenderSliver]s.
  ///
  /// The [HitTestEntry] instances added to the returned [SliverHitTestResult]
  /// are also added to the wrapped `result` (both share the same underlying
  /// data structure to store [HitTestEntry] instances).
  ///
  /// See also:
  ///
  ///  * [HitTestResult.wrap], which turns a [SliverHitTestResult] back into a
  ///    generic [HitTestResult].
  ///  * [BoxHitTestResult.wrap], which turns a [SliverHitTestResult] into a
  ///    [BoxHitTestResult] for hit testing on [RenderBox] children.
945
  SliverHitTestResult.wrap(super.result) : super.wrap();
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967

  /// Transforms `mainAxisPosition` and `crossAxisPosition` to the local
  /// coordinate system of a child for hit-testing the child.
  ///
  /// The actual hit testing of the child needs to be implemented in the
  /// provided `hitTest` callback, which is invoked with the transformed
  /// `position` as argument.
  ///
  /// For the transform `mainAxisOffset` is subtracted from `mainAxisPosition`
  /// and `crossAxisOffset` is subtracted from `crossAxisPosition`.
  ///
  /// The `paintOffset` describes how the paint position of a point painted at
  /// the provided `mainAxisPosition` and `crossAxisPosition` would change after
  /// `mainAxisOffset` and `crossAxisOffset` have been applied. This
  /// `paintOffset` is used to properly convert [PointerEvent]s to the local
  /// coordinate system of the event receiver.
  ///
  /// The `paintOffset` may be null if `mainAxisOffset` and `crossAxisOffset` are
  /// both zero.
  ///
  /// The function returns the return value of `hitTest`.
  bool addWithAxisOffset({
968 969 970 971 972 973
    required Offset? paintOffset,
    required double mainAxisOffset,
    required double crossAxisOffset,
    required double mainAxisPosition,
    required double crossAxisPosition,
    required SliverHitTest hitTest,
974
  }) {
975
    if (paintOffset != null) {
976
      pushOffset(-paintOffset);
977 978
    }
    final bool isHit = hitTest(
979 980 981 982
      this,
      mainAxisPosition: mainAxisPosition - mainAxisOffset,
      crossAxisPosition: crossAxisPosition - crossAxisOffset,
    );
983 984 985 986
    if (paintOffset != null) {
      popTransform();
    }
    return isHit;
987 988 989
  }
}

990 991 992 993
/// A hit test entry used by [RenderSliver].
///
/// The coordinate system used by this hit test entry is relative to the
/// [AxisDirection] of the target sliver.
994
class SliverHitTestEntry extends HitTestEntry<RenderSliver> {
995
  /// Creates a sliver hit test entry.
996
  SliverHitTestEntry(
997
    super.target, {
998 999
    required this.mainAxisPosition,
    required this.crossAxisPosition,
1000
  });
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012

  /// The distance in the [AxisDirection] from the edge of the sliver's painted
  /// area (as given by the [SliverConstraints.scrollOffset]) to the hit point.
  /// This can be an unusual direction, for example in the [AxisDirection.up]
  /// case this is a distance from the _bottom_ of the sliver's painted area.
  final double mainAxisPosition;

  /// The distance to the hit point in the axis opposite the
  /// [SliverConstraints.axis].
  ///
  /// If the cross axis is horizontal (i.e. the
  /// [SliverConstraints.axisDirection] is either [AxisDirection.down] or
1013
  /// [AxisDirection.up]), then the [crossAxisPosition] is a distance from the
1014 1015
  /// left edge of the sliver. If the cross axis is vertical (i.e. the
  /// [SliverConstraints.axisDirection] is either [AxisDirection.right] or
1016
  /// [AxisDirection.left]), then the [crossAxisPosition] is a distance from the
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
  /// top edge of the sliver.
  ///
  /// This is always a distance from the left or top of the parent, never a
  /// distance from the right or bottom.
  final double crossAxisPosition;

  @override
  String toString() => '${target.runtimeType}@(mainAxis: $mainAxisPosition, crossAxis: $crossAxisPosition)';
}

/// Parent data structure used by parents of slivers that position their
1028
/// children using layout offsets.
1029
///
1030
/// This data structure is optimized for fast layout. It is best used by parents
1031 1032 1033
/// that expect to have many children whose relative positions don't change even
/// when the scroll offset does.
class SliverLogicalParentData extends ParentData {
1034 1035
  /// The position of the child relative to the zero scroll offset.
  ///
nt4f04uNd's avatar
nt4f04uNd committed
1036
  /// The number of pixels from the zero scroll offset of the parent sliver
1037
  /// (the line at which its [SliverConstraints.scrollOffset] is zero) to the
1038 1039
  /// side of the child closest to that offset. A [layoutOffset] can be null
  /// when it cannot be determined. The value will be set after layout.
1040 1041
  ///
  /// In a typical list, this does not change as the parent is scrolled.
1042 1043
  ///
  /// Defaults to null.
1044
  double? layoutOffset;
1045 1046

  @override
1047
  String toString() => 'layoutOffset=${layoutOffset == null ? 'None': layoutOffset!.toStringAsFixed(1)}';
1048 1049
}

1050 1051
/// Parent data for slivers that have multiple children and that position their
/// children using layout offsets.
1052 1053
class SliverLogicalContainerParentData extends SliverLogicalParentData with ContainerParentDataMixin<RenderSliver> { }

1054
/// Parent data structure used by parents of slivers that position their
1055 1056 1057
/// children using absolute coordinates.
///
/// For example, used by [RenderViewport].
1058
///
1059
/// This data structure is optimized for fast painting, at the cost of requiring
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
/// additional work during layout when the children change their offsets. It is
/// best used by parents that expect to have few children, especially if those
/// children will themselves be very tall relative to the parent.
class SliverPhysicalParentData extends ParentData {
  /// The position of the child relative to the parent.
  ///
  /// This is the distance from the top left visible corner of the parent to the
  /// top left visible corner of the sliver.
  Offset paintOffset = Offset.zero;

1070 1071
  /// The [crossAxisFlex] factor to use for this sliver child.
  ///
1072 1073
  /// If used outside of a [SliverCrossAxisGroup] widget, this value has no meaning.
  ///
1074
  /// If null or zero, the child is inflexible and determines its own size in the cross axis.
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
  /// If non-zero, the amount of space the child can occupy in the cross axis is
  /// determined by dividing the free space (after placing the inflexible children)
  /// according to the flex factors of the flexible children.
  ///
  /// This value is only used by the [SliverCrossAxisGroup] widget to determine
  /// how to allocate its [SliverConstraints.crossAxisExtent] to its children.
  ///
  /// See also:
  ///
  ///  * [SliverCrossAxisGroup], which lays out multiple slivers along the
  ///    cross axis direction.
1086 1087
  int? crossAxisFlex;

1088 1089 1090 1091
  /// Apply the [paintOffset] to the given [transform].
  ///
  /// Used to implement [RenderObject.applyPaintTransform] by slivers that use
  /// [SliverPhysicalParentData].
1092
  void applyPaintTransform(Matrix4 transform) {
1093
    // Hit test logic relies on this always providing an invertible matrix.
1094 1095 1096 1097 1098 1099 1100
    transform.translate(paintOffset.dx, paintOffset.dy);
  }

  @override
  String toString() => 'paintOffset=$paintOffset';
}

1101 1102
/// Parent data for slivers that have multiple children and that position their
/// children using absolute coordinates.
1103 1104
class SliverPhysicalContainerParentData extends SliverPhysicalParentData with ContainerParentDataMixin<RenderSliver> { }

1105
List<DiagnosticsNode> _debugCompareFloats(String labelA, double valueA, String labelB, double valueB) {
1106 1107 1108 1109
  return <DiagnosticsNode>[
    if (valueA.toStringAsFixed(1) != valueB.toStringAsFixed(1))
      ErrorDescription(
        'The $labelA is ${valueA.toStringAsFixed(1)}, but '
1110
        'the $labelB is ${valueB.toStringAsFixed(1)}.',
1111 1112 1113 1114
      )
    else ...<DiagnosticsNode>[
      ErrorDescription('The $labelA is $valueA, but the $labelB is $valueB.'),
      ErrorHint(
1115
        'Maybe you have fallen prey to floating point rounding errors, and should explicitly '
1116
        'apply the min() or max() functions, or the clamp() method, to the $labelB?',
1117 1118 1119
      ),
    ],
  ];
1120 1121
}

1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
/// Base class for the render objects that implement scroll effects in viewports.
///
/// A [RenderViewport] has a list of child slivers. Each sliver — literally a
/// slice of the viewport's contents — is laid out in turn, covering the
/// viewport in the process. (Every sliver is laid out each time, including
/// those that have zero extent because they are "scrolled off" or are beyond
/// the end of the viewport.)
///
/// Slivers participate in the _sliver protocol_, wherein during [layout] each
/// sliver receives a [SliverConstraints] object and computes a corresponding
/// [SliverGeometry] that describes where it fits in the viewport. This is
/// analogous to the box protocol used by [RenderBox], which gets a
/// [BoxConstraints] as input and computes a [Size].
///
/// Slivers have a leading edge, which is where the position described by
/// [SliverConstraints.scrollOffset] for this sliver begins. Slivers have
/// several dimensions, the primary of which is [SliverGeometry.paintExtent],
/// which describes the extent of the sliver along the main axis, starting from
/// the leading edge, reaching either the end of the viewport or the end of the
/// sliver, whichever comes first.
///
/// Slivers can change dimensions based on the changing constraints in a
/// non-linear fashion, to achieve various scroll effects. For example, the
/// various [RenderSliverPersistentHeader] subclasses, on which [SliverAppBar]
/// is based, achieve effects such as staying visible despite the scroll offset,
/// or reappearing at different offsets based on the user's scroll direction
/// ([SliverConstraints.userScrollDirection]).
///
1150 1151
/// {@youtube 560 315 https://www.youtube.com/watch?v=Mz3kHQxBjGg}
///
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
/// ## Writing a RenderSliver subclass
///
/// Slivers can have sliver children, or children from another coordinate
/// system, typically box children. (For details on the box protocol, see
/// [RenderBox].) Slivers can also have different child models, typically having
/// either one child, or a list of children.
///
/// ### Examples of slivers
///
/// A good example of a sliver with a single child that is also itself a sliver
/// is [RenderSliverPadding], which indents its child. A sliver-to-sliver render
/// object such as this must construct a [SliverConstraints] object for its
/// child, then must take its child's [SliverGeometry] and use it to form its
/// own [geometry].
///
/// The other common kind of one-child sliver is a sliver that has a single
/// [RenderBox] child. An example of that would be [RenderSliverToBoxAdapter],
/// which lays out a single box and sizes itself around the box. Such a sliver
/// must use its [SliverConstraints] to create a [BoxConstraints] for the
/// child, lay the child out (using the child's [layout] method), and then use
/// the child's [RenderBox.size] to generate the sliver's [SliverGeometry].
///
/// The most common kind of sliver though is one with multiple children. The
/// most straight-forward example of this is [RenderSliverList], which arranges
/// its children one after the other in the main axis direction. As with the
/// one-box-child sliver case, it uses its [constraints] to create a
/// [BoxConstraints] for the children, and then it uses the aggregate
/// information from all its children to generate its [geometry]. Unlike the
/// one-child cases, however, it is judicious in which children it actually lays
/// out (and later paints). If the scroll offset is 1000 pixels, and it
/// previously determined that the first three children are each 400 pixels
/// tall, then it will skip the first two and start the layout with its third
/// child.
///
/// ### Layout
///
/// As they are laid out, slivers decide their [geometry], which includes their
/// size ([SliverGeometry.paintExtent]) and the position of the next sliver
/// ([SliverGeometry.layoutExtent]), as well as the position of each of their
/// children, based on the input [constraints] from the viewport such as the
/// scroll offset ([SliverConstraints.scrollOffset]).
///
/// For example, a sliver that just paints a box 100 pixels high would say its
/// [SliverGeometry.paintExtent] was 100 pixels when the scroll offset was zero,
/// but would say its [SliverGeometry.paintExtent] was 25 pixels when the scroll
/// offset was 75 pixels, and would say it was zero when the scroll offset was
/// 100 pixels or more. (This is assuming that
/// [SliverConstraints.remainingPaintExtent] was more than 100 pixels.)
///
/// The various dimensions that are provided as input to this system are in the
/// [constraints]. They are described in detail in the documentation for the
/// [SliverConstraints] class.
///
/// The [performLayout] function must take these [constraints] and create a
/// [SliverGeometry] object that it must then assign to the [geometry] property.
/// The different dimensions of the geometry that can be configured are
/// described in detail in the documentation for the [SliverGeometry] class.
///
/// ### Painting
///
/// In addition to implementing layout, a sliver must also implement painting.
/// This is achieved by overriding the [paint] method.
///
/// The [paint] method is called with an [Offset] from the [Canvas] origin to
/// the top-left corner of the sliver, _regardless of the axis direction_.
///
/// Subclasses should also override [applyPaintTransform] to provide the
/// [Matrix4] describing the position of each child relative to the sliver.
/// (This is used by, among other things, the accessibility layer, to determine
/// the bounds of the child.)
///
/// ### Hit testing
///
/// To implement hit testing, either override the [hitTestSelf] and
/// [hitTestChildren] methods, or, for more complex cases, instead override the
/// [hitTest] method directly.
///
/// To actually react to pointer events, the [handleEvent] method may be
/// implemented. By default it does nothing. (Typically gestures are handled by
/// widgets in the box protocol, not by slivers directly.)
///
/// ### Helper methods
///
/// There are a number of methods that a sliver should implement which will make
/// the other methods easier to implement. Each method listed below has detailed
/// documentation. In addition, the [RenderSliverHelpers] class can be used to
/// mix in some helpful methods.
///
/// #### childScrollOffset
///
/// If the subclass positions children anywhere other than at scroll offset
/// zero, it should override [childScrollOffset]. For example,
/// [RenderSliverList] and [RenderSliverGrid] override this method, but
/// [RenderSliverToBoxAdapter] does not.
///
/// This is used by, among other things, [Scrollable.ensureVisible].
///
/// #### childMainAxisPosition
///
/// Subclasses should implement [childMainAxisPosition] to describe where their
/// children are positioned.
///
/// #### childCrossAxisPosition
///
/// If the subclass positions children in the cross-axis at a position other
/// than zero, then it should override [childCrossAxisPosition]. For example
/// [RenderSliverGrid] overrides this method.
1259 1260 1261
abstract class RenderSliver extends RenderObject {
  // layout input
  @override
1262
  SliverConstraints get constraints => super.constraints as SliverConstraints;
1263

1264 1265 1266 1267 1268 1269 1270 1271
  /// The amount of space this sliver occupies.
  ///
  /// This value is stale whenever this object is marked as needing layout.
  /// During [performLayout], do not read the [geometry] of a child unless you
  /// pass true for parentUsesSize when calling the child's [layout] function.
  ///
  /// The geometry of a sliver should be set only during the sliver's
  /// [performLayout] or [performResize] functions. If you wish to change the
1272
  /// geometry of a sliver outside of those functions, call [markNeedsLayout]
1273
  /// instead to schedule a layout of the sliver.
1274 1275 1276
  SliverGeometry? get geometry => _geometry;
  SliverGeometry? _geometry;
  set geometry(SliverGeometry? value) {
1277 1278 1279 1280
    assert(!(debugDoingThisResize && debugDoingThisLayout));
    assert(sizedByParent || !debugDoingThisResize);
    assert(() {
      if ((sizedByParent && debugDoingThisResize) ||
1281
          (!sizedByParent && debugDoingThisLayout)) {
1282
        return true;
1283
      }
1284
      assert(!debugDoingThisResize);
1285
      DiagnosticsNode? contract, violation, hint;
1286 1287
      if (debugDoingThisLayout) {
        assert(sizedByParent);
1288
        violation = ErrorDescription('It appears that the geometry setter was called from performLayout().');
1289
      } else {
1290
        violation = ErrorDescription('The geometry setter was called from outside layout (neither performResize() nor performLayout() were being run for this object).');
1291
        if (owner != null && owner!.debugDoingLayout) {
1292
          hint = ErrorDescription('Only the object itself can set its geometry. It is a contract violation for other objects to set it.');
1293
        }
1294
      }
1295
      if (sizedByParent) {
1296
        contract = ErrorDescription('Because this RenderSliver has sizedByParent set to true, it must set its geometry in performResize().');
1297
      } else {
1298
        contract = ErrorDescription('Because this RenderSliver has sizedByParent set to false, it must set its geometry in performLayout().');
1299
      }
1300 1301 1302

      final List<DiagnosticsNode> information = <DiagnosticsNode>[
        ErrorSummary('RenderSliver geometry setter called incorrectly.'),
1303 1304 1305 1306
        violation,
        if (hint != null) hint,
        contract,
        describeForError('The RenderSliver in question is'),
1307 1308
      ];
      throw FlutterError.fromParts(information);
1309
    }());
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
    _geometry = value;
  }

  @override
  Rect get semanticBounds => paintBounds;

  @override
  Rect get paintBounds {
    switch (constraints.axis) {
      case Axis.horizontal:
1320
        return Rect.fromLTWH(
1321
          0.0, 0.0,
1322
          geometry!.paintExtent,
1323 1324 1325
          constraints.crossAxisExtent,
        );
      case Axis.vertical:
1326
        return Rect.fromLTWH(
1327
          0.0, 0.0,
1328
          constraints.crossAxisExtent,
1329
          geometry!.paintExtent,
1330 1331 1332 1333 1334 1335 1336 1337 1338
        );
    }
  }

  @override
  void debugResetSize() { }

  @override
  void debugAssertDoesMeetConstraints() {
1339
    assert(geometry!.debugAssertIsValid(
1340 1341 1342
      informationCollector: () => <DiagnosticsNode>[
        describeForError('The RenderSliver that returned the offending geometry was'),
      ],
1343
    ));
1344
    assert(() {
1345
      if (geometry!.paintOrigin + geometry!.paintExtent > constraints.remainingPaintExtent) {
1346 1347
        throw FlutterError.fromParts(<DiagnosticsNode>[
          ErrorSummary('SliverGeometry has a paintOffset that exceeds the remainingPaintExtent from the constraints.'),
1348 1349
          describeForError('The render object whose geometry violates the constraints is the following'),
          ..._debugCompareFloats(
1350
            'remainingPaintExtent', constraints.remainingPaintExtent,
1351
            'paintOrigin + paintExtent', geometry!.paintOrigin + geometry!.paintExtent,
1352 1353
          ),
          ErrorDescription(
1354 1355
            'The paintOrigin and paintExtent must cause the child sliver to paint '
            'within the viewport, and so cannot exceed the remainingPaintExtent.',
1356 1357
          ),
        ]);
1358 1359
      }
      return true;
1360
    }());
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371
  }

  @override
  void performResize() {
    assert(false);
  }

  /// For a center sliver, the distance before the absolute zero scroll offset
  /// that this sliver can cover.
  ///
  /// For example, if an [AxisDirection.down] viewport with an
Adam Barth's avatar
Adam Barth committed
1372
  /// [RenderViewport.anchor] of 0.5 has a single sliver with a height of 100.0
1373 1374 1375 1376
  /// and its [centerOffsetAdjustment] returns 50.0, then the sliver will be
  /// centered in the viewport when the scroll offset is 0.0.
  ///
  /// The distance here is in the opposite direction of the
Adam Barth's avatar
Adam Barth committed
1377
  /// [RenderViewport.axisDirection], so values will typically be positive.
1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398
  double get centerOffsetAdjustment => 0.0;

  /// Determines the set of render objects located at the given position.
  ///
  /// Returns true if the given point is contained in this render object or one
  /// of its descendants. Adds any render objects that contain the point to the
  /// given hit test result.
  ///
  /// The caller is responsible for providing the position in the local
  /// coordinate space of the callee. The callee is responsible for checking
  /// whether the given position is within its bounds.
  ///
  /// Hit testing requires layout to be up-to-date but does not require painting
  /// to be up-to-date. That means a render object can rely upon [performLayout]
  /// having been called in [hitTest] but cannot rely upon [paint] having been
  /// called. For example, a render object might be a child of a [RenderOpacity]
  /// object, which calls [hitTest] on its children when its opacity is zero
  /// even through it does not [paint] its children.
  ///
  /// ## Coordinates for RenderSliver objects
  ///
1399 1400 1401 1402 1403
  /// The `mainAxisPosition` is the distance in the [AxisDirection] (after
  /// applying the [GrowthDirection]) from the edge of the sliver's painted
  /// area. This can be an unusual direction, for example in the
  /// [AxisDirection.up] case this is a distance from the _bottom_ of the
  /// sliver's painted area.
1404 1405 1406 1407 1408 1409 1410 1411
  ///
  /// The `crossAxisPosition` is the distance in the other axis. If the cross
  /// axis is horizontal (i.e. the [SliverConstraints.axisDirection] is either
  /// [AxisDirection.down] or [AxisDirection.up]), then the `crossAxisPosition`
  /// is a distance from the left edge of the sliver. If the cross axis is
  /// vertical (i.e. the [SliverConstraints.axisDirection] is either
  /// [AxisDirection.right] or [AxisDirection.left]), then the
  /// `crossAxisPosition` is a distance from the top edge of the sliver.
1412 1413 1414 1415 1416 1417
  ///
  /// ## Implementing hit testing for slivers
  ///
  /// The most straight-forward way to implement hit testing for a new sliver
  /// render object is to override its [hitTestSelf] and [hitTestChildren]
  /// methods.
1418 1419
  bool hitTest(SliverHitTestResult result, { required double mainAxisPosition, required double crossAxisPosition }) {
    if (mainAxisPosition >= 0.0 && mainAxisPosition < geometry!.hitTestExtent &&
1420 1421 1422
        crossAxisPosition >= 0.0 && crossAxisPosition < constraints.crossAxisExtent) {
      if (hitTestChildren(result, mainAxisPosition: mainAxisPosition, crossAxisPosition: crossAxisPosition) ||
          hitTestSelf(mainAxisPosition: mainAxisPosition, crossAxisPosition: crossAxisPosition)) {
1423
        result.add(SliverHitTestEntry(
1424 1425
          this,
          mainAxisPosition: mainAxisPosition,
1426
          crossAxisPosition: crossAxisPosition,
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
        ));
        return true;
      }
    }
    return false;
  }

  /// Override this method if this render object can be hit even if its
  /// children were not hit.
  ///
  /// Used by [hitTest]. If you override [hitTest] and do not call this
  /// function, then you don't need to implement this function.
  ///
  /// For a discussion of the semantics of the arguments, see [hitTest].
  @protected
1442
  bool hitTestSelf({ required double mainAxisPosition, required double crossAxisPosition }) => false;
1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455

  /// Override this method to check whether any children are located at the
  /// given position.
  ///
  /// Typically children should be hit-tested in reverse paint order so that
  /// hit tests at locations where children overlap hit the child that is
  /// visually "on top" (i.e., paints later).
  ///
  /// Used by [hitTest]. If you override [hitTest] and do not call this
  /// function, then you don't need to implement this function.
  ///
  /// For a discussion of the semantics of the arguments, see [hitTest].
  @protected
1456
  bool hitTestChildren(SliverHitTestResult result, { required double mainAxisPosition, required double crossAxisPosition }) => false;
1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472

  /// Computes the portion of the region from `from` to `to` that is visible,
  /// assuming that only the region from the [SliverConstraints.scrollOffset]
  /// that is [SliverConstraints.remainingPaintExtent] high is visible, and that
  /// the relationship between scroll offsets and paint offsets is linear.
  ///
  /// For example, if the constraints have a scroll offset of 100 and a
  /// remaining paint extent of 100, and the arguments to this method describe
  /// the region 50..150, then the returned value would be 50 (from scroll
  /// offset 100 to scroll offset 150).
  ///
  /// This method is not useful if there is not a 1:1 relationship between
  /// consumed scroll offset and consumed paint extent. For example, if the
  /// sliver always paints the same amount but consumes a scroll offset extent
  /// that is proportional to the [SliverConstraints.scrollOffset], then this
  /// function's results will not be consistent.
1473 1474
  // This could be a static method but isn't, because it would be less convenient
  // to call it from subclasses if it was.
1475
  double calculatePaintOffset(SliverConstraints constraints, { required double from, required double to }) {
1476 1477 1478 1479
    assert(from <= to);
    final double a = constraints.scrollOffset;
    final double b = constraints.scrollOffset + constraints.remainingPaintExtent;
    // the clamp on the next line is to avoid floating point rounding errors
1480
    return clampDouble(clampDouble(to, a, b) - clampDouble(from, a, b), 0.0, constraints.remainingPaintExtent);
1481 1482
  }

1483 1484 1485 1486 1487 1488 1489 1490
  /// Computes the portion of the region from `from` to `to` that is within
  /// the cache extent of the viewport, assuming that only the region from the
  /// [SliverConstraints.cacheOrigin] that is
  /// [SliverConstraints.remainingCacheExtent] high is visible, and that
  /// the relationship between scroll offsets and paint offsets is linear.
  ///
  /// This method is not useful if there is not a 1:1 relationship between
  /// consumed scroll offset and consumed cache extent.
1491
  double calculateCacheOffset(SliverConstraints constraints, { required double from, required double to }) {
1492 1493 1494 1495
    assert(from <= to);
    final double a = constraints.scrollOffset + constraints.cacheOrigin;
    final double b = constraints.scrollOffset + constraints.remainingCacheExtent;
    // the clamp on the next line is to avoid floating point rounding errors
1496
    return clampDouble(clampDouble(to, a, b) - clampDouble(from, a, b), 0.0, constraints.remainingCacheExtent);
1497 1498
  }

1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509
  /// Returns the distance from the leading _visible_ edge of the sliver to the
  /// side of the given child closest to that edge.
  ///
  /// For example, if the [constraints] describe this sliver as having an axis
  /// direction of [AxisDirection.down], then this is the distance from the top
  /// of the visible portion of the sliver to the top of the child. On the other
  /// hand, if the [constraints] describe this sliver as having an axis
  /// direction of [AxisDirection.up], then this is the distance from the bottom
  /// of the visible portion of the sliver to the bottom of the child. In both
  /// cases, this is the direction of increasing
  /// [SliverConstraints.scrollOffset] and
1510
  /// [SliverLogicalParentData.layoutOffset].
1511 1512 1513 1514 1515 1516 1517 1518
  ///
  /// For children that are [RenderSliver]s, the leading edge of the _child_
  /// will be the leading _visible_ edge of the child, not the part of the child
  /// that would locally be a scroll offset 0.0. For children that are not
  /// [RenderSliver]s, for example a [RenderBox] child, it's the actual distance
  /// to the edge of the box, since those boxes do not know how to handle being
  /// scrolled.
  ///
1519 1520
  /// This method differs from [childScrollOffset] in that
  /// [childMainAxisPosition] gives the distance from the leading _visible_ edge
1521 1522 1523 1524
  /// of the sliver whereas [childScrollOffset] gives the distance from the
  /// sliver's zero scroll offset.
  ///
  /// Calling this for a child that is not visible is not valid.
1525
  @protected
1526
  double childMainAxisPosition(covariant RenderObject child) {
1527
    assert(() {
1528
      throw FlutterError('${objectRuntimeType(this, 'RenderSliver')} does not implement childPosition.');
1529
    }());
1530 1531 1532
    return 0.0;
  }

1533
  /// Returns the distance along the cross axis from the zero of the cross axis
1534 1535
  /// in this sliver's [paint] coordinate space to the nearest side of the given
  /// child.
1536 1537 1538 1539 1540
  ///
  /// For example, if the [constraints] describe this sliver as having an axis
  /// direction of [AxisDirection.down], then this is the distance from the left
  /// of the sliver to the left of the child. Similarly, if the [constraints]
  /// describe this sliver as having an axis direction of [AxisDirection.up],
1541 1542 1543
  /// then this is value is the same. If the axis direction is
  /// [AxisDirection.left] or [AxisDirection.right], then it is the distance
  /// from the top of the sliver to the top of the child.
1544 1545
  ///
  /// Calling this for a child that is not visible is not valid.
1546
  @protected
1547
  double childCrossAxisPosition(covariant RenderObject child) => 0.0;
1548

1549 1550 1551 1552 1553 1554 1555 1556
  /// Returns the scroll offset for the leading edge of the given child.
  ///
  /// The `child` must be a child of this sliver.
  ///
  /// This method differs from [childMainAxisPosition] in that
  /// [childMainAxisPosition] gives the distance from the leading _visible_ edge
  /// of the sliver whereas [childScrollOffset] gives the distance from sliver's
  /// zero scroll offset.
1557
  double? childScrollOffset(covariant RenderObject child) {
1558 1559 1560 1561
    assert(child.parent == this);
    return 0.0;
  }

1562 1563 1564
  @override
  void applyPaintTransform(RenderObject child, Matrix4 transform) {
    assert(() {
1565
      throw FlutterError('${objectRuntimeType(this, 'RenderSliver')} does not implement applyPaintTransform.');
1566
    }());
1567 1568
  }

Ian Hickson's avatar
Ian Hickson committed
1569 1570 1571
  /// This returns a [Size] with dimensions relative to the leading edge of the
  /// sliver, specifically the same offset that is given to the [paint] method.
  /// This means that the dimensions may be negative.
1572 1573
  ///
  /// This is only valid after [layout] has completed.
1574 1575 1576 1577
  ///
  /// See also:
  ///
  ///  * [getAbsoluteSize], which returns absolute size.
Ian Hickson's avatar
Ian Hickson committed
1578 1579 1580
  @protected
  Size getAbsoluteSizeRelativeToOrigin() {
    assert(geometry != null);
1581
    assert(!debugNeedsLayout);
Ian Hickson's avatar
Ian Hickson committed
1582 1583
    switch (applyGrowthDirectionToAxisDirection(constraints.axisDirection, constraints.growthDirection)) {
      case AxisDirection.up:
1584
        return Size(constraints.crossAxisExtent, -geometry!.paintExtent);
Ian Hickson's avatar
Ian Hickson committed
1585
      case AxisDirection.right:
1586
        return Size(geometry!.paintExtent, constraints.crossAxisExtent);
Ian Hickson's avatar
Ian Hickson committed
1587
      case AxisDirection.down:
1588
        return Size(constraints.crossAxisExtent, geometry!.paintExtent);
Ian Hickson's avatar
Ian Hickson committed
1589
      case AxisDirection.left:
1590
        return Size(-geometry!.paintExtent, constraints.crossAxisExtent);
Ian Hickson's avatar
Ian Hickson committed
1591 1592 1593
    }
  }

1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609
  /// This returns the absolute [Size] of the sliver.
  ///
  /// The dimensions are always positive and calling this is only valid after
  /// [layout] has completed.
  ///
  /// See also:
  ///
  ///  * [getAbsoluteSizeRelativeToOrigin], which returns the size relative to
  ///    the leading edge of the sliver.
  @protected
  Size getAbsoluteSize() {
    assert(geometry != null);
    assert(!debugNeedsLayout);
    switch (constraints.axisDirection) {
      case AxisDirection.up:
      case AxisDirection.down:
1610
        return Size(constraints.crossAxisExtent, geometry!.paintExtent);
1611 1612
      case AxisDirection.right:
      case AxisDirection.left:
1613
        return Size(geometry!.paintExtent, constraints.crossAxisExtent);
1614 1615 1616
    }
  }

1617
  void _debugDrawArrow(Canvas canvas, Paint paint, Offset p0, Offset p1, GrowthDirection direction) {
1618
    assert(() {
1619
      if (p0 == p1) {
Ian Hickson's avatar
Ian Hickson committed
1620
        return true;
1621
      }
1622
      assert(p0.dx == p1.dx || p0.dy == p1.dy); // must be axis-aligned
1623
      final double d = (p1 - p0).distance * 0.2;
1624
      final Offset temp;
1625 1626 1627 1628 1629 1630 1631 1632 1633 1634
      double dx1, dx2, dy1, dy2;
      switch (direction) {
        case GrowthDirection.forward:
          dx1 = dx2 = dy1 = dy2 = d;
        case GrowthDirection.reverse:
          temp = p0;
          p0 = p1;
          p1 = temp;
          dx1 = dx2 = dy1 = dy2 = -d;
      }
1635
      if (p0.dx == p1.dx) {
1636 1637 1638 1639 1640
        dx2 = -dx2;
      } else {
        dy2 = -dy2;
      }
      canvas.drawPath(
1641
        Path()
1642 1643 1644 1645 1646
          ..moveTo(p0.dx, p0.dy)
          ..lineTo(p1.dx, p1.dy)
          ..moveTo(p1.dx - dx1, p1.dy - dy1)
          ..lineTo(p1.dx, p1.dy)
          ..lineTo(p1.dx - dx2, p1.dy - dy2),
1647
        paint,
1648
      );
Ian Hickson's avatar
Ian Hickson committed
1649
      return true;
1650
    }());
1651 1652 1653 1654 1655 1656
  }

  @override
  void debugPaint(PaintingContext context, Offset offset) {
    assert(() {
      if (debugPaintSizeEnabled) {
1657
        final double strokeWidth = math.min(4.0, geometry!.paintExtent / 30.0);
1658
        final Paint paint = Paint()
1659
          ..color = const Color(0xFF33CC33)
1660 1661
          ..strokeWidth = strokeWidth
          ..style = PaintingStyle.stroke
1662
          ..maskFilter = MaskFilter.blur(BlurStyle.solid, strokeWidth);
1663
        final double arrowExtent = geometry!.paintExtent;
1664 1665 1666
        final double padding = math.max(2.0, strokeWidth);
        final Canvas canvas = context.canvas;
        canvas.drawCircle(
1667
          offset.translate(padding, padding),
1668 1669 1670 1671 1672 1673
          padding * 0.5,
          paint,
        );
        switch (constraints.axis) {
          case Axis.vertical:
            canvas.drawLine(
1674 1675
              offset,
              offset.translate(constraints.crossAxisExtent, 0.0),
1676 1677 1678 1679 1680
              paint,
            );
            _debugDrawArrow(
              canvas,
              paint,
1681 1682
              offset.translate(constraints.crossAxisExtent * 1.0 / 4.0, padding),
              offset.translate(constraints.crossAxisExtent * 1.0 / 4.0, arrowExtent - padding),
1683 1684 1685 1686 1687
              constraints.normalizedGrowthDirection,
            );
            _debugDrawArrow(
              canvas,
              paint,
1688 1689
              offset.translate(constraints.crossAxisExtent * 3.0 / 4.0, padding),
              offset.translate(constraints.crossAxisExtent * 3.0 / 4.0, arrowExtent - padding),
1690 1691 1692 1693
              constraints.normalizedGrowthDirection,
            );
          case Axis.horizontal:
            canvas.drawLine(
1694 1695
              offset,
              offset.translate(0.0, constraints.crossAxisExtent),
1696 1697 1698 1699 1700
              paint,
            );
            _debugDrawArrow(
              canvas,
              paint,
1701 1702
              offset.translate(padding, constraints.crossAxisExtent * 1.0 / 4.0),
              offset.translate(arrowExtent - padding, constraints.crossAxisExtent * 1.0 / 4.0),
1703 1704 1705 1706 1707
              constraints.normalizedGrowthDirection,
            );
            _debugDrawArrow(
              canvas,
              paint,
1708 1709
              offset.translate(padding, constraints.crossAxisExtent * 3.0 / 4.0),
              offset.translate(arrowExtent - padding, constraints.crossAxisExtent * 3.0 / 4.0),
1710 1711 1712 1713 1714
              constraints.normalizedGrowthDirection,
            );
        }
      }
      return true;
1715
    }());
1716 1717
  }

1718
  // This override exists only to change the type of the second argument.
1719 1720 1721 1722
  @override
  void handleEvent(PointerEvent event, SliverHitTestEntry entry) { }

  @override
1723 1724
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
1725
    properties.add(DiagnosticsProperty<SliverGeometry>('geometry', geometry));
1726 1727 1728 1729
  }
}

/// Mixin for [RenderSliver] subclasses that provides some utility functions.
1730
mixin RenderSliverHelpers implements RenderSliver {
1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753
  bool _getRightWayUp(SliverConstraints constraints) {
    bool rightWayUp;
    switch (constraints.axisDirection) {
      case AxisDirection.up:
      case AxisDirection.left:
        rightWayUp = false;
      case AxisDirection.down:
      case AxisDirection.right:
        rightWayUp = true;
    }
    switch (constraints.growthDirection) {
      case GrowthDirection.forward:
        break;
      case GrowthDirection.reverse:
        rightWayUp = !rightWayUp;
    }
    return rightWayUp;
  }

  /// Utility function for [hitTestChildren] for use when the children are
  /// [RenderBox] widgets.
  ///
  /// This function takes care of converting the position from the sliver
1754
  /// coordinate system to the Cartesian coordinate system used by [RenderBox].
1755
  ///
1756
  /// This function relies on [childMainAxisPosition] to determine the position of
1757 1758 1759 1760
  /// child in question.
  ///
  /// Calling this for a child that is not visible is not valid.
  @protected
1761
  bool hitTestBoxChild(BoxHitTestResult result, RenderBox child, { required double mainAxisPosition, required double crossAxisPosition }) {
1762
    final bool rightWayUp = _getRightWayUp(constraints);
1763 1764 1765 1766 1767
    double delta = childMainAxisPosition(child);
    final double crossAxisDelta = childCrossAxisPosition(child);
    double absolutePosition = mainAxisPosition - delta;
    final double absoluteCrossAxisPosition = crossAxisPosition - crossAxisDelta;
    Offset paintOffset, transformedPosition;
1768 1769
    switch (constraints.axis) {
      case Axis.horizontal:
1770
        if (!rightWayUp) {
1771
          absolutePosition = child.size.width - absolutePosition;
1772
          delta = geometry!.paintExtent - child.size.width - delta;
1773 1774 1775
        }
        paintOffset = Offset(delta, crossAxisDelta);
        transformedPosition = Offset(absolutePosition, absoluteCrossAxisPosition);
1776
      case Axis.vertical:
1777
        if (!rightWayUp) {
1778
          absolutePosition = child.size.height - absolutePosition;
1779
          delta = geometry!.paintExtent - child.size.height - delta;
1780 1781 1782
        }
        paintOffset = Offset(crossAxisDelta, delta);
        transformedPosition = Offset(absoluteCrossAxisPosition, absolutePosition);
1783
    }
1784 1785 1786
    return result.addWithOutOfBandPosition(
      paintOffset: paintOffset,
      hitTest: (BoxHitTestResult result) {
1787 1788 1789
        return child.hitTest(result, position: transformedPosition);
      },
    );
1790 1791 1792 1793 1794
  }

  /// Utility function for [applyPaintTransform] for use when the children are
  /// [RenderBox] widgets.
  ///
1795 1796 1797
  /// This function turns the value returned by [childMainAxisPosition] and
  /// [childCrossAxisPosition]for the child in question into a translation that
  /// it then applies to the given matrix.
1798 1799 1800 1801
  ///
  /// Calling this for a child that is not visible is not valid.
  @protected
  void applyPaintTransformForBoxChild(RenderBox child, Matrix4 transform) {
1802
    final bool rightWayUp = _getRightWayUp(constraints);
1803 1804
    double delta = childMainAxisPosition(child);
    final double crossAxisDelta = childCrossAxisPosition(child);
1805 1806
    switch (constraints.axis) {
      case Axis.horizontal:
1807
        if (!rightWayUp) {
1808
          delta = geometry!.paintExtent - child.size.width - delta;
1809
        }
1810
        transform.translate(delta, crossAxisDelta);
1811
      case Axis.vertical:
1812
        if (!rightWayUp) {
1813
          delta = geometry!.paintExtent - child.size.height - delta;
1814
        }
1815
        transform.translate(crossAxisDelta, delta);
1816 1817 1818 1819 1820 1821 1822
    }
  }
}

// ADAPTER FOR RENDER BOXES INSIDE SLIVERS
// Transitions from the RenderSliver world to the RenderBox world.

1823
/// An abstract class for [RenderSliver]s that contains a single [RenderBox].
1824 1825 1826
///
/// See also:
///
1827 1828 1829 1830 1831 1832
///  * [RenderSliver], which explains more about the Sliver protocol.
///  * [RenderBox], which explains more about the Box protocol.
///  * [RenderSliverToBoxAdapter], which extends this class to size the child
///    according to its preferred size.
///  * [RenderSliverFillRemaining], which extends this class to size the child
///    to fill the remaining space in the viewport.
1833
abstract class RenderSliverSingleBoxAdapter extends RenderSliver with RenderObjectWithChildMixin<RenderBox>, RenderSliverHelpers {
1834
  /// Creates a [RenderSliver] that wraps a [RenderBox].
1835
  RenderSliverSingleBoxAdapter({
1836
    RenderBox? child,
1837 1838 1839 1840 1841 1842
  }) {
    this.child = child;
  }

  @override
  void setupParentData(RenderObject child) {
1843
    if (child.parentData is! SliverPhysicalParentData) {
1844
      child.parentData = SliverPhysicalParentData();
1845
    }
1846 1847
  }

1848 1849 1850 1851
  /// Sets the [SliverPhysicalParentData.paintOffset] for the given child
  /// according to the [SliverConstraints.axisDirection] and
  /// [SliverConstraints.growthDirection] and the given geometry.
  @protected
1852
  void setChildParentData(RenderObject child, SliverConstraints constraints, SliverGeometry geometry) {
1853
    final SliverPhysicalParentData childParentData = child.parentData! as SliverPhysicalParentData;
1854 1855
    switch (applyGrowthDirectionToAxisDirection(constraints.axisDirection, constraints.growthDirection)) {
      case AxisDirection.up:
1856
        childParentData.paintOffset = Offset(0.0, -(geometry.scrollExtent - (geometry.paintExtent + constraints.scrollOffset)));
1857
      case AxisDirection.right:
1858
        childParentData.paintOffset = Offset(-constraints.scrollOffset, 0.0);
1859
      case AxisDirection.down:
1860
        childParentData.paintOffset = Offset(0.0, -constraints.scrollOffset);
1861
      case AxisDirection.left:
1862
        childParentData.paintOffset = Offset(-(geometry.scrollExtent - (geometry.paintExtent + constraints.scrollOffset)), 0.0);
1863 1864 1865 1866
    }
  }

  @override
1867 1868
  bool hitTestChildren(SliverHitTestResult result, { required double mainAxisPosition, required double crossAxisPosition }) {
    assert(geometry!.hitTestExtent > 0.0);
1869
    if (child != null) {
1870
      return hitTestBoxChild(BoxHitTestResult.wrap(result), child!, mainAxisPosition: mainAxisPosition, crossAxisPosition: crossAxisPosition);
1871
    }
1872 1873 1874 1875
    return false;
  }

  @override
1876
  double childMainAxisPosition(RenderBox child) {
1877 1878 1879 1880 1881 1882
    return -constraints.scrollOffset;
  }

  @override
  void applyPaintTransform(RenderObject child, Matrix4 transform) {
    assert(child == this.child);
1883
    final SliverPhysicalParentData childParentData = child.parentData! as SliverPhysicalParentData;
1884 1885 1886 1887 1888
    childParentData.applyPaintTransform(transform);
  }

  @override
  void paint(PaintingContext context, Offset offset) {
1889
    if (child != null && geometry!.visible) {
1890
      final SliverPhysicalParentData childParentData = child!.parentData! as SliverPhysicalParentData;
1891
      context.paintChild(child!, offset + childParentData.paintOffset);
1892 1893 1894
    }
  }
}
1895 1896 1897 1898 1899 1900 1901 1902 1903

/// A [RenderSliver] that contains a single [RenderBox].
///
/// The child will not be laid out if it is not visible. It is sized according
/// to the child's preferences in the main axis, and with a tight constraint
/// forcing it to the dimensions of the viewport in the cross axis.
///
/// See also:
///
1904 1905 1906 1907
///  * [RenderSliver], which explains more about the Sliver protocol.
///  * [RenderBox], which explains more about the Box protocol.
///  * [RenderViewport], which allows [RenderSliver] objects to be placed inside
///    a [RenderBox] (the opposite of this class).
1908 1909 1910
class RenderSliverToBoxAdapter extends RenderSliverSingleBoxAdapter {
  /// Creates a [RenderSliver] that wraps a [RenderBox].
  RenderSliverToBoxAdapter({
1911 1912
    super.child,
  });
1913 1914 1915 1916 1917 1918 1919

  @override
  void performLayout() {
    if (child == null) {
      geometry = SliverGeometry.zero;
      return;
    }
1920
    final SliverConstraints constraints = this.constraints;
1921
    child!.layout(constraints.asBoxConstraints(), parentUsesSize: true);
1922
    final double childExtent;
1923 1924
    switch (constraints.axis) {
      case Axis.horizontal:
1925
        childExtent = child!.size.width;
1926
      case Axis.vertical:
1927
        childExtent = child!.size.height;
1928 1929
    }
    final double paintedChildSize = calculatePaintOffset(constraints, from: 0.0, to: childExtent);
1930 1931
    final double cacheExtent = calculateCacheOffset(constraints, from: 0.0, to: childExtent);

1932 1933
    assert(paintedChildSize.isFinite);
    assert(paintedChildSize >= 0.0);
1934
    geometry = SliverGeometry(
1935 1936
      scrollExtent: childExtent,
      paintExtent: paintedChildSize,
1937
      cacheExtent: cacheExtent,
1938 1939 1940 1941
      maxPaintExtent: childExtent,
      hitTestExtent: paintedChildSize,
      hasVisualOverflow: childExtent > constraints.remainingPaintExtent || constraints.scrollOffset > 0.0,
    );
1942
    setChildParentData(child!, constraints, geometry!);
1943 1944
  }
}