shifted_box.dart 42.1 KB
Newer Older
1 2 3 4
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'dart:math' as math;
6

7 8
import 'package:flutter/foundation.dart';

9
import 'box.dart';
10
import 'debug.dart';
11
import 'debug_overflow_indicator.dart';
12
import 'object.dart';
13
import 'stack.dart' show RelativeRect;
14

15 16
/// Abstract class for one-child-layout render boxes that provide control over
/// the child's position.
17
abstract class RenderShiftedBox extends RenderBox with RenderObjectWithChildMixin<RenderBox> {
18
  /// Initializes the [child] property for subclasses.
19 20 21 22
  RenderShiftedBox(RenderBox child) {
    this.child = child;
  }

23
  @override
24
  double computeMinIntrinsicWidth(double height) {
25
    if (child != null)
26 27
      return child.getMinIntrinsicWidth(height);
    return 0.0;
28 29
  }

30
  @override
31
  double computeMaxIntrinsicWidth(double height) {
32
    if (child != null)
33 34
      return child.getMaxIntrinsicWidth(height);
    return 0.0;
35 36
  }

37
  @override
38
  double computeMinIntrinsicHeight(double width) {
39
    if (child != null)
40 41
      return child.getMinIntrinsicHeight(width);
    return 0.0;
42 43
  }

44
  @override
45
  double computeMaxIntrinsicHeight(double width) {
46
    if (child != null)
47 48
      return child.getMaxIntrinsicHeight(width);
    return 0.0;
49 50
  }

51
  @override
52 53 54
  double computeDistanceToActualBaseline(TextBaseline baseline) {
    double result;
    if (child != null) {
55
      assert(!debugNeedsLayout);
56
      result = child.getDistanceToActualBaseline(baseline);
Hixie's avatar
Hixie committed
57
      final BoxParentData childParentData = child.parentData;
58
      if (result != null)
59
        result += childParentData.offset.dy;
60 61 62 63 64 65
    } else {
      result = super.computeDistanceToActualBaseline(baseline);
    }
    return result;
  }

66
  @override
67
  void paint(PaintingContext context, Offset offset) {
Hixie's avatar
Hixie committed
68 69
    if (child != null) {
      final BoxParentData childParentData = child.parentData;
Adam Barth's avatar
Adam Barth committed
70
      context.paintChild(child, childParentData.offset + offset);
Hixie's avatar
Hixie committed
71
    }
72 73
  }

74
  @override
75
  bool hitTestChildren(HitTestResult result, { Offset position }) {
76
    if (child != null) {
Hixie's avatar
Hixie committed
77
      final BoxParentData childParentData = child.parentData;
78
      return child.hitTest(result, position: position - childParentData.offset);
79
    }
Adam Barth's avatar
Adam Barth committed
80
    return false;
81 82 83 84
  }

}

85 86 87 88 89 90
/// Insets its child by the given padding.
///
/// When passing layout constraints to its child, padding shrinks the
/// constraints by the given padding, causing the child to layout at a smaller
/// size. Padding then sizes itself to its child's size, inflated by the
/// padding, effectively creating empty space around the child.
91
class RenderPadding extends RenderShiftedBox {
92 93 94
  /// Creates a render object that insets its child.
  ///
  /// The [padding] argument must not be null and must have non-negative insets.
95
  RenderPadding({
96 97 98
    @required EdgeInsetsGeometry padding,
    TextDirection textDirection,
    RenderBox child,
99 100
  }) : assert(padding != null),
       assert(padding.isNonNegative),
101
       _textDirection = textDirection,
102
       _padding = padding,
Ian Hickson's avatar
Ian Hickson committed
103
       super(child);
104 105 106

  EdgeInsets _resolvedPadding;

Ian Hickson's avatar
Ian Hickson committed
107 108 109 110 111 112 113 114 115 116
  void _resolve() {
    if (_resolvedPadding != null)
      return;
    _resolvedPadding = padding.resolve(textDirection);
    assert(_resolvedPadding.isNonNegative);
  }

  void _markNeedResolution() {
    _resolvedPadding = null;
    markNeedsLayout();
117
  }
118

119
  /// The amount to pad the child in each dimension.
120 121
  ///
  /// If this is set to an [EdgeInsetsDirectional] object, then [textDirection]
122
  /// must not be null.
123 124 125
  EdgeInsetsGeometry get padding => _padding;
  EdgeInsetsGeometry _padding;
  set padding(EdgeInsetsGeometry value) {
126
    assert(value != null);
127
    assert(value.isNonNegative);
128 129 130
    if (_padding == value)
      return;
    _padding = value;
Ian Hickson's avatar
Ian Hickson committed
131
    _markNeedResolution();
132 133 134
  }

  /// The text direction with which to resolve [padding].
Ian Hickson's avatar
Ian Hickson committed
135 136 137
  ///
  /// This may be changed to null, but only after the [padding] has been changed
  /// to a value that does not depend on the direction.
138 139 140 141 142 143
  TextDirection get textDirection => _textDirection;
  TextDirection _textDirection;
  set textDirection(TextDirection value) {
    if (_textDirection == value)
      return;
    _textDirection = value;
Ian Hickson's avatar
Ian Hickson committed
144
    _markNeedResolution();
145 146
  }

147
  @override
148
  double computeMinIntrinsicWidth(double height) {
Ian Hickson's avatar
Ian Hickson committed
149
    _resolve();
150 151
    final double totalHorizontalPadding = _resolvedPadding.left + _resolvedPadding.right;
    final double totalVerticalPadding = _resolvedPadding.top + _resolvedPadding.bottom;
152
    if (child != null) // next line relies on double.infinity absorption
153
      return child.getMinIntrinsicWidth(math.max(0.0, height - totalVerticalPadding)) + totalHorizontalPadding;
154
    return totalHorizontalPadding;
155 156
  }

157
  @override
158
  double computeMaxIntrinsicWidth(double height) {
Ian Hickson's avatar
Ian Hickson committed
159
    _resolve();
160 161
    final double totalHorizontalPadding = _resolvedPadding.left + _resolvedPadding.right;
    final double totalVerticalPadding = _resolvedPadding.top + _resolvedPadding.bottom;
162
    if (child != null) // next line relies on double.infinity absorption
163
      return child.getMaxIntrinsicWidth(math.max(0.0, height - totalVerticalPadding)) + totalHorizontalPadding;
164
    return totalHorizontalPadding;
165 166
  }

167
  @override
168
  double computeMinIntrinsicHeight(double width) {
Ian Hickson's avatar
Ian Hickson committed
169
    _resolve();
170 171
    final double totalHorizontalPadding = _resolvedPadding.left + _resolvedPadding.right;
    final double totalVerticalPadding = _resolvedPadding.top + _resolvedPadding.bottom;
172
    if (child != null) // next line relies on double.infinity absorption
173
      return child.getMinIntrinsicHeight(math.max(0.0, width - totalHorizontalPadding)) + totalVerticalPadding;
174
    return totalVerticalPadding;
175 176
  }

177
  @override
178
  double computeMaxIntrinsicHeight(double width) {
Ian Hickson's avatar
Ian Hickson committed
179
    _resolve();
180 181
    final double totalHorizontalPadding = _resolvedPadding.left + _resolvedPadding.right;
    final double totalVerticalPadding = _resolvedPadding.top + _resolvedPadding.bottom;
182
    if (child != null) // next line relies on double.infinity absorption
183
      return child.getMaxIntrinsicHeight(math.max(0.0, width - totalHorizontalPadding)) + totalVerticalPadding;
184
    return totalVerticalPadding;
185 186
  }

187
  @override
188
  void performLayout() {
Ian Hickson's avatar
Ian Hickson committed
189
    _resolve();
190
    assert(_resolvedPadding != null);
191
    if (child == null) {
192
      size = constraints.constrain(Size(
193 194
        _resolvedPadding.left + _resolvedPadding.right,
        _resolvedPadding.top + _resolvedPadding.bottom
195 196 197
      ));
      return;
    }
198
    final BoxConstraints innerConstraints = constraints.deflate(_resolvedPadding);
199
    child.layout(innerConstraints, parentUsesSize: true);
Hixie's avatar
Hixie committed
200
    final BoxParentData childParentData = child.parentData;
201 202
    childParentData.offset = Offset(_resolvedPadding.left, _resolvedPadding.top);
    size = constraints.constrain(Size(
203 204
      _resolvedPadding.left + child.size.width + _resolvedPadding.right,
      _resolvedPadding.top + child.size.height + _resolvedPadding.bottom
205 206 207
    ));
  }

208
  @override
209 210 211
  void debugPaintSize(PaintingContext context, Offset offset) {
    super.debugPaintSize(context, offset);
    assert(() {
212
      final Rect outerRect = offset & size;
213
      debugPaintPadding(context.canvas, outerRect, child != null ? _resolvedPadding.deflateRect(outerRect) : null);
214
      return true;
215
    }());
216 217
  }

218
  @override
219 220
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
221 222
    properties.add(DiagnosticsProperty<EdgeInsetsGeometry>('padding', padding));
    properties.add(EnumProperty<TextDirection>('textDirection', textDirection, defaultValue: null));
223
  }
224 225
}

226
/// Abstract class for one-child-layout render boxes that use a
227
/// [AlignmentGeometry] to align their children.
228
abstract class RenderAligningShiftedBox extends RenderShiftedBox {
229 230 231
  /// Initializes member variables for subclasses.
  ///
  /// The [alignment] argument must not be null.
232
  RenderAligningShiftedBox({
233
    AlignmentGeometry alignment = Alignment.center,
Ian Hickson's avatar
Ian Hickson committed
234
    @required TextDirection textDirection,
235 236
    RenderBox child,
  }) : assert(alignment != null),
237
       _alignment = alignment,
238
       _textDirection = textDirection,
Ian Hickson's avatar
Ian Hickson committed
239
       super(child);
240

241
  /// A constructor to be used only when the extending class also has a mixin.
242
  // TODO(gspencer): Remove this constructor once https://github.com/dart-lang/sdk/issues/31543 is fixed.
243 244 245 246
  @protected
  RenderAligningShiftedBox.mixin(AlignmentGeometry alignment,TextDirection textDirection, RenderBox child)
    : this(alignment: alignment, textDirection: textDirection, child: child);

247
  Alignment _resolvedAlignment;
248

Ian Hickson's avatar
Ian Hickson committed
249 250 251 252 253 254 255 256 257
  void _resolve() {
    if (_resolvedAlignment != null)
      return;
    _resolvedAlignment = alignment.resolve(textDirection);
  }

  void _markNeedResolution() {
    _resolvedAlignment = null;
    markNeedsLayout();
258
  }
259

260 261 262
  /// How to align the child.
  ///
  /// The x and y values of the alignment control the horizontal and vertical
263
  /// alignment, respectively. An x value of -1.0 means that the left edge of
264 265 266
  /// the child is aligned with the left edge of the parent whereas an x value
  /// of 1.0 means that the right edge of the child is aligned with the right
  /// edge of the parent. Other values interpolate (and extrapolate) linearly.
267
  /// For example, a value of 0.0 means that the center of the child is aligned
268
  /// with the center of the parent.
269
  ///
270
  /// If this is set to an [AlignmentDirectional] object, then
271
  /// [textDirection] must not be null.
272 273
  AlignmentGeometry get alignment => _alignment;
  AlignmentGeometry _alignment;
274 275
  /// Sets the alignment to a new value, and triggers a layout update.
  ///
Ian Hickson's avatar
Ian Hickson committed
276
  /// The new alignment must not be null.
277
  set alignment(AlignmentGeometry value) {
278
    assert(value != null);
279
    if (_alignment == value)
280
      return;
281
    _alignment = value;
Ian Hickson's avatar
Ian Hickson committed
282
    _markNeedResolution();
283 284 285
  }

  /// The text direction with which to resolve [alignment].
Ian Hickson's avatar
Ian Hickson committed
286 287 288
  ///
  /// This may be changed to null, but only after [alignment] has been changed
  /// to a value that does not depend on the direction.
289 290 291 292 293 294
  TextDirection get textDirection => _textDirection;
  TextDirection _textDirection;
  set textDirection(TextDirection value) {
    if (_textDirection == value)
      return;
    _textDirection = value;
Ian Hickson's avatar
Ian Hickson committed
295
    _markNeedResolution();
296 297
  }

298 299 300 301 302 303 304 305 306
  /// Apply the current [alignment] to the [child].
  ///
  /// Subclasses should call this method if they have a child, to have
  /// this class perform the actual alignment. If there is no child,
  /// do not call this method.
  ///
  /// This method must be called after the child has been laid out and
  /// this object's own size has been set.
  void alignChild() {
Ian Hickson's avatar
Ian Hickson committed
307
    _resolve();
308
    assert(child != null);
309
    assert(!child.debugNeedsLayout);
310 311
    assert(child.hasSize);
    assert(hasSize);
Ian Hickson's avatar
Ian Hickson committed
312
    assert(_resolvedAlignment != null);
313
    final BoxParentData childParentData = child.parentData;
314
    childParentData.offset = _resolvedAlignment.alongOffset(size - child.size);
315 316 317
  }

  @override
318 319
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
320 321
    properties.add(DiagnosticsProperty<AlignmentGeometry>('alignment', alignment));
    properties.add(EnumProperty<TextDirection>('textDirection', textDirection, defaultValue: null));
322 323 324
  }
}

325
/// Positions its child using an [AlignmentGeometry].
326 327 328
///
/// For example, to align a box at the bottom right, you would pass this box a
/// tight constraint that is bigger than the child's natural size,
329
/// with an alignment of [Alignment.bottomRight].
330 331 332 333 334 335
///
/// By default, sizes to be as big as possible in both axes. If either axis is
/// unconstrained, then in that direction it will be sized to fit the child's
/// dimensions. Using widthFactor and heightFactor you can force this latter
/// behavior in all cases.
class RenderPositionedBox extends RenderAligningShiftedBox {
336
  /// Creates a render object that positions its child.
337 338 339 340
  RenderPositionedBox({
    RenderBox child,
    double widthFactor,
    double heightFactor,
341
    AlignmentGeometry alignment = Alignment.center,
342
    TextDirection textDirection,
343 344 345
  }) : assert(widthFactor == null || widthFactor >= 0.0),
       assert(heightFactor == null || heightFactor >= 0.0),
       _widthFactor = widthFactor,
346
       _heightFactor = heightFactor,
347
       super(child: child, alignment: alignment, textDirection: textDirection);
348

349
  /// If non-null, sets its width to the child's width multiplied by this factor.
350 351
  ///
  /// Can be both greater and less than 1.0 but must be positive.
352
  double get widthFactor => _widthFactor;
353
  double _widthFactor;
354
  set widthFactor(double value) {
355
    assert(value == null || value >= 0.0);
356
    if (_widthFactor == value)
357
      return;
358
    _widthFactor = value;
359 360 361
    markNeedsLayout();
  }

362
  /// If non-null, sets its height to the child's height multiplied by this factor.
363 364
  ///
  /// Can be both greater and less than 1.0 but must be positive.
365
  double get heightFactor => _heightFactor;
366
  double _heightFactor;
367
  set heightFactor(double value) {
368
    assert(value == null || value >= 0.0);
369 370 371 372 373
    if (_heightFactor == value)
      return;
    _heightFactor = value;
    markNeedsLayout();
  }
374

375
  @override
376
  void performLayout() {
377 378
    final bool shrinkWrapWidth = _widthFactor != null || constraints.maxWidth == double.infinity;
    final bool shrinkWrapHeight = _heightFactor != null || constraints.maxHeight == double.infinity;
379

380 381
    if (child != null) {
      child.layout(constraints.loosen(), parentUsesSize: true);
382
      size = constraints.constrain(Size(shrinkWrapWidth ? child.size.width * (_widthFactor ?? 1.0) : double.infinity,
383
                                            shrinkWrapHeight ? child.size.height * (_heightFactor ?? 1.0) : double.infinity));
384
      alignChild();
385
    } else {
386
      size = constraints.constrain(Size(shrinkWrapWidth ? 0.0 : double.infinity,
387
                                            shrinkWrapHeight ? 0.0 : double.infinity));
388 389 390
    }
  }

391
  @override
392 393 394 395 396 397
  void debugPaintSize(PaintingContext context, Offset offset) {
    super.debugPaintSize(context, offset);
    assert(() {
      Paint paint;
      if (child != null && !child.size.isEmpty) {
        Path path;
398
        paint = Paint()
399
          ..style = PaintingStyle.stroke
400
          ..strokeWidth = 1.0
401
          ..color = const Color(0xFFFFFF00);
402
        path = Path();
403 404 405
        final BoxParentData childParentData = child.parentData;
        if (childParentData.offset.dy > 0.0) {
          // vertical alignment arrows
406
          final double headSize = math.min(childParentData.offset.dy * 0.2, 10.0);
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
          path
            ..moveTo(offset.dx + size.width / 2.0, offset.dy)
            ..relativeLineTo(0.0, childParentData.offset.dy - headSize)
            ..relativeLineTo(headSize, 0.0)
            ..relativeLineTo(-headSize, headSize)
            ..relativeLineTo(-headSize, -headSize)
            ..relativeLineTo(headSize, 0.0)
            ..moveTo(offset.dx + size.width / 2.0, offset.dy + size.height)
            ..relativeLineTo(0.0, -childParentData.offset.dy + headSize)
            ..relativeLineTo(headSize, 0.0)
            ..relativeLineTo(-headSize, -headSize)
            ..relativeLineTo(-headSize, headSize)
            ..relativeLineTo(headSize, 0.0);
          context.canvas.drawPath(path, paint);
        }
        if (childParentData.offset.dx > 0.0) {
          // horizontal alignment arrows
424
          final double headSize = math.min(childParentData.offset.dx * 0.2, 10.0);
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
          path
            ..moveTo(offset.dx, offset.dy + size.height / 2.0)
            ..relativeLineTo(childParentData.offset.dx - headSize, 0.0)
            ..relativeLineTo(0.0, headSize)
            ..relativeLineTo(headSize, -headSize)
            ..relativeLineTo(-headSize, -headSize)
            ..relativeLineTo(0.0, headSize)
            ..moveTo(offset.dx + size.width, offset.dy + size.height / 2.0)
            ..relativeLineTo(-childParentData.offset.dx + headSize, 0.0)
            ..relativeLineTo(0.0, headSize)
            ..relativeLineTo(-headSize, -headSize)
            ..relativeLineTo(headSize, -headSize)
            ..relativeLineTo(0.0, headSize);
          context.canvas.drawPath(path, paint);
        }
      } else {
441
        paint = Paint()
442
          ..color = const Color(0x90909090);
443 444 445
        context.canvas.drawRect(offset & size, paint);
      }
      return true;
446
    }());
447 448
  }

449
  @override
450 451
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
452 453
    properties.add(DoubleProperty('widthFactor', _widthFactor, ifNull: 'expand'));
    properties.add(DoubleProperty('heightFactor', _heightFactor, ifNull: 'expand'));
454
  }
455 456
}

457 458 459 460 461 462 463 464 465 466 467 468 469
/// A render object that imposes different constraints on its child than it gets
/// from its parent, possibly allowing the child to overflow the parent.
///
/// A render overflow box proxies most functions in the render box protocol to
/// its child, except that when laying out its child, it passes constraints
/// based on the minWidth, maxWidth, minHeight, and maxHeight fields instead of
/// just passing the parent's constraints in. Specifically, it overrides any of
/// the equivalent fields on the constraints given by the parent with the
/// constraints given by these fields for each such field that is not null. It
/// then sizes itself based on the parent's constraints' maxWidth and maxHeight,
/// ignoring the child's dimensions.
///
/// For example, if you wanted a box to always render 50 pixels high, regardless
470 471 472 473
/// of where it was rendered, you would wrap it in a
/// RenderConstrainedOverflowBox with minHeight and maxHeight set to 50.0.
/// Generally speaking, to avoid confusing behavior around hit testing, a
/// RenderConstrainedOverflowBox should usually be wrapped in a RenderClipRect.
474
///
475
/// The child is positioned according to [alignment]. To position a smaller
476
/// child inside a larger parent, use [RenderPositionedBox] and
477
/// [RenderConstrainedBox] rather than RenderConstrainedOverflowBox.
478 479 480 481 482 483 484 485 486
///
/// See also:
///
///  * [RenderUnconstrainedBox] for a render object that allows its children
///    to render themselves unconstrained, expands to fit them, and considers
///    overflow to be an error.
///  * [RenderSizedOverflowBox], a render object that is a specific size but
///    passes its original constraints through to its child, which it allows to
///    overflow.
487
class RenderConstrainedOverflowBox extends RenderAligningShiftedBox {
488
  /// Creates a render object that lets its child overflow itself.
489
  RenderConstrainedOverflowBox({
490 491 492 493 494
    RenderBox child,
    double minWidth,
    double maxWidth,
    double minHeight,
    double maxHeight,
495
    AlignmentGeometry alignment = Alignment.center,
496
    TextDirection textDirection,
497 498 499 500
  }) : _minWidth = minWidth,
       _maxWidth = maxWidth,
       _minHeight = minHeight,
       _maxHeight = maxHeight,
501
       super(child: child, alignment: alignment, textDirection: textDirection);
502 503 504 505 506

  /// The minimum width constraint to give the child. Set this to null (the
  /// default) to use the constraint from the parent instead.
  double get minWidth => _minWidth;
  double _minWidth;
507
  set minWidth(double value) {
508 509 510 511 512 513 514 515 516 517
    if (_minWidth == value)
      return;
    _minWidth = value;
    markNeedsLayout();
  }

  /// The maximum width constraint to give the child. Set this to null (the
  /// default) to use the constraint from the parent instead.
  double get maxWidth => _maxWidth;
  double _maxWidth;
518
  set maxWidth(double value) {
519 520 521 522 523 524 525 526 527 528
    if (_maxWidth == value)
      return;
    _maxWidth = value;
    markNeedsLayout();
  }

  /// The minimum height constraint to give the child. Set this to null (the
  /// default) to use the constraint from the parent instead.
  double get minHeight => _minHeight;
  double _minHeight;
529
  set minHeight(double value) {
530 531 532 533 534 535 536 537 538 539
    if (_minHeight == value)
      return;
    _minHeight = value;
    markNeedsLayout();
  }

  /// The maximum height constraint to give the child. Set this to null (the
  /// default) to use the constraint from the parent instead.
  double get maxHeight => _maxHeight;
  double _maxHeight;
540
  set maxHeight(double value) {
541 542 543 544 545 546 547
    if (_maxHeight == value)
      return;
    _maxHeight = value;
    markNeedsLayout();
  }

  BoxConstraints _getInnerConstraints(BoxConstraints constraints) {
548
    return BoxConstraints(
549 550 551 552 553 554 555
      minWidth: _minWidth ?? constraints.minWidth,
      maxWidth: _maxWidth ?? constraints.maxWidth,
      minHeight: _minHeight ?? constraints.minHeight,
      maxHeight: _maxHeight ?? constraints.maxHeight
    );
  }

556
  @override
557 558
  bool get sizedByParent => true;

559
  @override
560 561 562 563
  void performResize() {
    size = constraints.biggest;
  }

564
  @override
565 566 567
  void performLayout() {
    if (child != null) {
      child.layout(_getInnerConstraints(constraints), parentUsesSize: true);
568
      alignChild();
569 570 571
    }
  }

572
  @override
573 574
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
575 576 577 578
    properties.add(DoubleProperty('minWidth', minWidth, ifNull: 'use parent minWidth constraint'));
    properties.add(DoubleProperty('maxWidth', maxWidth, ifNull: 'use parent maxWidth constraint'));
    properties.add(DoubleProperty('minHeight', minHeight, ifNull: 'use parent minHeight constraint'));
    properties.add(DoubleProperty('maxHeight', maxHeight, ifNull: 'use parent maxHeight constraint'));
579 580 581
  }
}

582 583 584 585
/// Renders a box, imposing no constraints on its child, allowing the child to
/// render at its "natural" size.
///
/// This allows a child to render at the size it would render if it were alone
586 587 588 589 590
/// on an infinite canvas with no constraints. This box will then attempt to
/// adopt the same size, within the limits of its own constraints. If it ends
/// up with a different size, it will align the child based on [alignment].
/// If the box cannot expand enough to accommodate the entire child, the
/// child will be clipped.
591 592
///
/// In debug mode, if the child overflows the box, a warning will be printed on
593
/// the console, and black and yellow striped areas will appear where the
594 595 596 597
/// overflow occurs.
///
/// See also:
///
598 599 600
///  * [RenderConstrainedBox], which renders a box which imposes constraints
///    on its child.
///  * [RenderConstrainedOverflowBox], which renders a box that imposes different
601 602 603 604 605 606
///    constraints on its child than it gets from its parent, possibly allowing
///    the child to overflow the parent.
///  * [RenderSizedOverflowBox], a render object that is a specific size but
///    passes its original constraints through to its child, which it allows to
///    overflow.
class RenderUnconstrainedBox extends RenderAligningShiftedBox with DebugOverflowIndicatorMixin {
607 608 609 610
  /// Create a render object that sizes itself to the child but does not
  /// pass the [constraints] down to that child.
  ///
  /// The [alignment] must not be null.
611 612 613
  RenderUnconstrainedBox({
    @required AlignmentGeometry alignment,
    @required TextDirection textDirection,
614
    Axis constrainedAxis,
615 616
    RenderBox child,
  }) : assert(alignment != null),
617 618
       _constrainedAxis = constrainedAxis,
       super.mixin(alignment, textDirection, child);
619

620 621 622
  /// The axis to retain constraints on, if any.
  ///
  /// If not set, or set to null (the default), neither axis will retain its
623
  /// constraints. If set to [Axis.vertical], then vertical constraints will
624 625 626 627 628 629 630 631 632 633
  /// be retained, and if set to [Axis.horizontal], then horizontal constraints
  /// will be retained.
  Axis get constrainedAxis => _constrainedAxis;
  Axis _constrainedAxis;
  set constrainedAxis(Axis value) {
    if (_constrainedAxis == value)
      return;
    _constrainedAxis = value;
    markNeedsLayout();
  }
634

635 636 637 638 639 640 641
  Rect _overflowContainerRect = Rect.zero;
  Rect _overflowChildRect = Rect.zero;
  bool _isOverflowing = false;

  @override
  void performLayout() {
    if (child != null) {
642 643
      // Let the child lay itself out at it's "natural" size, but if
      // constrainedAxis is non-null, keep any constraints on that axis.
644
      BoxConstraints childConstraints;
645 646 647
      if (constrainedAxis != null) {
        switch (constrainedAxis) {
          case Axis.horizontal:
648
            childConstraints = BoxConstraints(maxWidth: constraints.maxWidth, minWidth: constraints.minWidth);
649 650
            break;
          case Axis.vertical:
651
            childConstraints = BoxConstraints(maxHeight: constraints.maxHeight, minHeight: constraints.minHeight);
652 653 654
            break;
        }
      } else {
655
        childConstraints = const BoxConstraints();
656
      }
657
      child.layout(childConstraints, parentUsesSize: true);
658 659 660 661 662 663
      size = constraints.constrain(child.size);
      alignChild();
      final BoxParentData childParentData = child.parentData;
      _overflowContainerRect = Offset.zero & size;
      _overflowChildRect = childParentData.offset & child.size;
    } else {
664
      size = constraints.smallest;
665 666 667
      _overflowContainerRect = Rect.zero;
      _overflowChildRect = Rect.zero;
    }
668
    _isOverflowing = RelativeRect.fromRect(_overflowContainerRect, _overflowChildRect).hasInsets;
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    // There's no point in drawing the child if we're empty, or there is no
    // child.
    if (child == null || size.isEmpty)
      return;

    if (!_isOverflowing) {
      super.paint(context, offset);
      return;
    }

    // We have overflow. Clip it.
    context.pushClipRect(needsCompositing, offset, Offset.zero & size, super.paint);

    // Display the overflow indicator.
    assert(() {
      paintOverflowIndicator(context, offset, _overflowContainerRect, _overflowChildRect);
      return true;
    }());
  }

  @override
  Rect describeApproximatePaintClip(RenderObject child) {
    return _isOverflowing ? Offset.zero & size : null;
  }

  @override
  String toStringShort() {
    String header = super.toStringShort();
    if (_isOverflowing)
      header += ' OVERFLOWING';
    return header;
  }
}

/// A render object that is a specific size but passes its original constraints
/// through to its child, which it allows to overflow.
///
/// See also:
///  * [RenderUnconstrainedBox] for a render object that allows its children
///    to render themselves unconstrained, expands to fit them, and considers
///    overflow to be an error.
///  * [RenderConstrainedOverflowBox] for a render object that imposes
///    different constraints on its child than it gets from its parent,
///    possibly allowing the child to overflow the parent.
717
class RenderSizedOverflowBox extends RenderAligningShiftedBox {
718 719 720
  /// Creates a render box of a given size that lets its child overflow.
  ///
  /// The [requestedSize] argument must not be null.
721 722
  RenderSizedOverflowBox({
    RenderBox child,
723
    @required Size requestedSize,
724
    Alignment alignment = Alignment.center,
725
    TextDirection textDirection,
726 727
  }) : assert(requestedSize != null),
       _requestedSize = requestedSize,
728
       super(child: child, alignment: alignment, textDirection: textDirection);
729 730 731 732

  /// The size this render box should attempt to be.
  Size get requestedSize => _requestedSize;
  Size _requestedSize;
733
  set requestedSize(Size value) {
734 735 736 737 738 739 740 741
    assert(value != null);
    if (_requestedSize == value)
      return;
    _requestedSize = value;
    markNeedsLayout();
  }

  @override
742
  double computeMinIntrinsicWidth(double height) {
743
    return _requestedSize.width;
744 745 746
  }

  @override
747
  double computeMaxIntrinsicWidth(double height) {
748
    return _requestedSize.width;
749 750 751
  }

  @override
752
  double computeMinIntrinsicHeight(double width) {
753
    return _requestedSize.height;
754 755 756
  }

  @override
757
  double computeMaxIntrinsicHeight(double width) {
758
    return _requestedSize.height;
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
  }

  @override
  double computeDistanceToActualBaseline(TextBaseline baseline) {
    if (child != null)
      return child.getDistanceToActualBaseline(baseline);
    return super.computeDistanceToActualBaseline(baseline);
  }

  @override
  void performLayout() {
    size = constraints.constrain(_requestedSize);
    if (child != null) {
      child.layout(constraints);
      alignChild();
    }
  }
}

/// Sizes its child to a fraction of the total available space.
///
/// For both its width and height, this render object imposes a tight
/// constraint on its child that is a multiple (typically less than 1.0) of the
/// maximum constraint it received from its parent on that axis. If the factor
/// for a given axis is null, then the constraints from the parent are just
/// passed through instead.
///
/// It then tries to size itself to the size of its child.
class RenderFractionallySizedOverflowBox extends RenderAligningShiftedBox {
788 789 790 791
  /// Creates a render box that sizes its child to a fraction of the total available space.
  ///
  /// If non-null, the [widthFactor] and [heightFactor] arguments must be
  /// non-negative.
792 793 794 795
  RenderFractionallySizedOverflowBox({
    RenderBox child,
    double widthFactor,
    double heightFactor,
796
    Alignment alignment = Alignment.center,
797
    TextDirection textDirection,
798 799
  }) : _widthFactor = widthFactor,
       _heightFactor = heightFactor,
800
       super(child: child, alignment: alignment, textDirection: textDirection) {
801 802 803 804 805 806 807
    assert(_widthFactor == null || _widthFactor >= 0.0);
    assert(_heightFactor == null || _heightFactor >= 0.0);
  }

  /// If non-null, the factor of the incoming width to use.
  ///
  /// If non-null, the child is given a tight width constraint that is the max
808
  /// incoming width constraint multiplied by this factor. If null, the child is
809
  /// given the incoming width constraints.
810 811
  double get widthFactor => _widthFactor;
  double _widthFactor;
812
  set widthFactor(double value) {
813 814 815 816 817 818 819 820 821 822
    assert(value == null || value >= 0.0);
    if (_widthFactor == value)
      return;
    _widthFactor = value;
    markNeedsLayout();
  }

  /// If non-null, the factor of the incoming height to use.
  ///
  /// If non-null, the child is given a tight height constraint that is the max
823
  /// incoming width constraint multiplied by this factor. If null, the child is
824
  /// given the incoming width constraints.
825 826
  double get heightFactor => _heightFactor;
  double _heightFactor;
827
  set heightFactor(double value) {
828 829 830 831 832 833 834 835 836 837 838
    assert(value == null || value >= 0.0);
    if (_heightFactor == value)
      return;
    _heightFactor = value;
    markNeedsLayout();
  }

  BoxConstraints _getInnerConstraints(BoxConstraints constraints) {
    double minWidth = constraints.minWidth;
    double maxWidth = constraints.maxWidth;
    if (_widthFactor != null) {
839
      final double width = maxWidth * _widthFactor;
840 841 842 843 844 845
      minWidth = width;
      maxWidth = width;
    }
    double minHeight = constraints.minHeight;
    double maxHeight = constraints.maxHeight;
    if (_heightFactor != null) {
846
      final double height = maxHeight * _heightFactor;
847 848 849
      minHeight = height;
      maxHeight = height;
    }
850
    return BoxConstraints(
851 852 853 854 855 856 857 858
      minWidth: minWidth,
      maxWidth: maxWidth,
      minHeight: minHeight,
      maxHeight: maxHeight
    );
  }

  @override
859
  double computeMinIntrinsicWidth(double height) {
860 861
    double result;
    if (child == null) {
862
      result = super.computeMinIntrinsicWidth(height);
863
    } else { // the following line relies on double.infinity absorption
864 865 866 867
      result = child.getMinIntrinsicWidth(height * (_heightFactor ?? 1.0));
    }
    assert(result.isFinite);
    return result / (_widthFactor ?? 1.0);
868 869 870
  }

  @override
871
  double computeMaxIntrinsicWidth(double height) {
872 873
    double result;
    if (child == null) {
874
      result = super.computeMaxIntrinsicWidth(height);
875
    } else { // the following line relies on double.infinity absorption
876 877 878 879
      result = child.getMaxIntrinsicWidth(height * (_heightFactor ?? 1.0));
    }
    assert(result.isFinite);
    return result / (_widthFactor ?? 1.0);
880 881 882
  }

  @override
883
  double computeMinIntrinsicHeight(double width) {
884 885
    double result;
    if (child == null) {
886
      result = super.computeMinIntrinsicHeight(width);
887
    } else { // the following line relies on double.infinity absorption
888 889 890 891
      result = child.getMinIntrinsicHeight(width * (_widthFactor ?? 1.0));
    }
    assert(result.isFinite);
    return result / (_heightFactor ?? 1.0);
892 893 894
  }

  @override
895
  double computeMaxIntrinsicHeight(double width) {
896 897
    double result;
    if (child == null) {
898
      result = super.computeMaxIntrinsicHeight(width);
899
    } else { // the following line relies on double.infinity absorption
900 901 902 903
      result = child.getMaxIntrinsicHeight(width * (_widthFactor ?? 1.0));
    }
    assert(result.isFinite);
    return result / (_heightFactor ?? 1.0);
904 905 906 907 908 909 910 911 912 913 914 915 916 917
  }

  @override
  void performLayout() {
    if (child != null) {
      child.layout(_getInnerConstraints(constraints), parentUsesSize: true);
      size = constraints.constrain(child.size);
      alignChild();
    } else {
      size = constraints.constrain(_getInnerConstraints(constraints).constrain(Size.zero));
    }
  }

  @override
918 919
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
920 921
    properties.add(DoubleProperty('widthFactor', _widthFactor, ifNull: 'pass-through'));
    properties.add(DoubleProperty('heightFactor', _heightFactor, ifNull: 'pass-through'));
922 923 924
  }
}

Adam Barth's avatar
Adam Barth committed
925
/// A delegate for computing the layout of a render object with a single child.
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
///
/// Used by [CustomSingleChildLayout] (in the widgets library) and
/// [RenderCustomSingleChildLayoutBox] (in the rendering library).
///
/// When asked to layout, [CustomSingleChildLayout] first calls [getSize] with
/// its incoming constraints to determine its size. It then calls
/// [getConstraintsForChild] to determine the constraints to apply to the child.
/// After the child completes its layout, [RenderCustomSingleChildLayoutBox]
/// calls [getPositionForChild] to determine the child's position.
///
/// The [shouldRelayout] method is called when a new instance of the class
/// is provided, to check if the new instance actually represents different
/// information.
///
/// The most efficient way to trigger a relayout is to supply a relayout
/// argument to the constructor of the [SingleChildLayoutDelegate]. The custom
/// object will listen to this value and relayout whenever the animation
/// ticks, avoiding both the build phase of the pipeline.
///
/// See also:
///
///  * [CustomSingleChildLayout], the widget that uses this delegate.
///  * [RenderCustomSingleChildLayoutBox], render object that uses this
///    delegate.
950
abstract class SingleChildLayoutDelegate {
951 952 953 954
  /// Creates a layout delegate.
  ///
  /// The layout will update whenever [relayout] notifies its listeners.
  const SingleChildLayoutDelegate({ Listenable relayout }) : _relayout = relayout;
955

956
  final Listenable _relayout;
957 958 959

  /// The size of this object given the incoming constraints.
  ///
960
  /// Defaults to the biggest size that satisfies the given constraints.
Adam Barth's avatar
Adam Barth committed
961 962
  Size getSize(BoxConstraints constraints) => constraints.biggest;

963 964 965 966 967 968 969
  /// The constraints for the child given the incoming constraints.
  ///
  /// During layout, the child is given the layout constraints returned by this
  /// function. The child is required to pick a size for itself that satisfies
  /// these constraints.
  ///
  /// Defaults to the given constraints.
Adam Barth's avatar
Adam Barth committed
970 971
  BoxConstraints getConstraintsForChild(BoxConstraints constraints) => constraints;

972 973 974 975 976 977 978 979 980
  /// The position where the child should be placed.
  ///
  /// The `size` argument is the size of the parent, which might be different
  /// from the value returned by [getSize] if that size doesn't satisfy the
  /// constraints passed to [getSize]. The `childSize` argument is the size of
  /// the child, which will satisfy the constraints returned by
  /// [getConstraintsForChild].
  ///
  /// Defaults to positioning the child in the upper left corner of the parent.
981
  Offset getPositionForChild(Size size, Size childSize) => Offset.zero;
982

983 984 985 986 987 988 989
  /// Called whenever a new instance of the custom layout delegate class is
  /// provided to the [RenderCustomSingleChildLayoutBox] object, or any time
  /// that a new [CustomSingleChildLayout] object is created with a new instance
  /// of the custom layout delegate class (which amounts to the same thing,
  /// because the latter is implemented in terms of the former).
  ///
  /// If the new instance represents different information than the old
990 991
  /// instance, then the method should return true, otherwise it should return
  /// false.
992
  ///
993
  /// If the method returns false, then the [getSize],
994 995 996 997
  /// [getConstraintsForChild], and [getPositionForChild] calls might be
  /// optimized away.
  ///
  /// It's possible that the layout methods will get called even if
998
  /// [shouldRelayout] returns false (e.g. if an ancestor changed its layout).
999 1000 1001
  /// It's also possible that the layout method will get called
  /// without [shouldRelayout] being called at all (e.g. if the parent changes
  /// size).
1002
  bool shouldRelayout(covariant SingleChildLayoutDelegate oldDelegate);
Adam Barth's avatar
Adam Barth committed
1003 1004
}

1005 1006 1007 1008 1009 1010
/// Defers the layout of its single child to a delegate.
///
/// The delegate can determine the layout constraints for the child and can
/// decide where to position the child. The delegate can also determine the size
/// of the parent, but the size of the parent cannot depend on the size of the
/// child.
1011
class RenderCustomSingleChildLayoutBox extends RenderShiftedBox {
1012
  /// Creates a render box that defers its layout to a delegate.
1013 1014
  ///
  /// The [delegate] argument must not be null.
1015
  RenderCustomSingleChildLayoutBox({
Adam Barth's avatar
Adam Barth committed
1016
    RenderBox child,
1017
    @required SingleChildLayoutDelegate delegate
1018 1019 1020
  }) : assert(delegate != null),
       _delegate = delegate,
       super(child);
Adam Barth's avatar
Adam Barth committed
1021

1022
  /// A delegate that controls this object's layout.
1023 1024
  SingleChildLayoutDelegate get delegate => _delegate;
  SingleChildLayoutDelegate _delegate;
1025
  set delegate(SingleChildLayoutDelegate newDelegate) {
Adam Barth's avatar
Adam Barth committed
1026 1027 1028
    assert(newDelegate != null);
    if (_delegate == newDelegate)
      return;
1029 1030
    final SingleChildLayoutDelegate oldDelegate = _delegate;
    if (newDelegate.runtimeType != oldDelegate.runtimeType || newDelegate.shouldRelayout(oldDelegate))
1031
      markNeedsLayout();
Adam Barth's avatar
Adam Barth committed
1032
    _delegate = newDelegate;
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
    if (attached) {
      oldDelegate?._relayout?.removeListener(markNeedsLayout);
      newDelegate?._relayout?.addListener(markNeedsLayout);
    }
  }

  @override
  void attach(PipelineOwner owner) {
    super.attach(owner);
    _delegate?._relayout?.addListener(markNeedsLayout);
  }

  @override
  void detach() {
    _delegate?._relayout?.removeListener(markNeedsLayout);
    super.detach();
Adam Barth's avatar
Adam Barth committed
1049 1050 1051 1052 1053 1054
  }

  Size _getSize(BoxConstraints constraints) {
    return constraints.constrain(_delegate.getSize(constraints));
  }

1055 1056 1057 1058
  // TODO(ianh): It's a bit dubious to be using the getSize function from the delegate to
  // figure out the intrinsic dimensions. We really should either not support intrinsics,
  // or we should expose intrinsic delegate callbacks and throw if they're not implemented.

1059
  @override
1060
  double computeMinIntrinsicWidth(double height) {
1061
    final double width = _getSize(BoxConstraints.tightForFinite(height: height)).width;
1062 1063 1064
    if (width.isFinite)
      return width;
    return 0.0;
Adam Barth's avatar
Adam Barth committed
1065 1066
  }

1067
  @override
1068
  double computeMaxIntrinsicWidth(double height) {
1069
    final double width = _getSize(BoxConstraints.tightForFinite(height: height)).width;
1070 1071 1072
    if (width.isFinite)
      return width;
    return 0.0;
Adam Barth's avatar
Adam Barth committed
1073 1074
  }

1075
  @override
1076
  double computeMinIntrinsicHeight(double width) {
1077
    final double height = _getSize(BoxConstraints.tightForFinite(width: width)).height;
1078 1079 1080
    if (height.isFinite)
      return height;
    return 0.0;
Adam Barth's avatar
Adam Barth committed
1081 1082
  }

1083
  @override
1084
  double computeMaxIntrinsicHeight(double width) {
1085
    final double height = _getSize(BoxConstraints.tightForFinite(width: width)).height;
1086 1087 1088
    if (height.isFinite)
      return height;
    return 0.0;
Adam Barth's avatar
Adam Barth committed
1089 1090
  }

1091
  @override
Adam Barth's avatar
Adam Barth committed
1092
  void performLayout() {
1093
    size = _getSize(constraints);
Adam Barth's avatar
Adam Barth committed
1094
    if (child != null) {
1095
      final BoxConstraints childConstraints = delegate.getConstraintsForChild(constraints);
1096
      assert(childConstraints.debugAssertIsValid(isAppliedConstraint: true));
1097
      child.layout(childConstraints, parentUsesSize: !childConstraints.isTight);
Adam Barth's avatar
Adam Barth committed
1098
      final BoxParentData childParentData = child.parentData;
1099
      childParentData.offset = delegate.getPositionForChild(size, childConstraints.isTight ? childConstraints.smallest : child.size);
Adam Barth's avatar
Adam Barth committed
1100 1101 1102 1103
    }
  }
}

1104 1105 1106
/// Shifts the child down such that the child's baseline (or the
/// bottom of the child, if the child has no baseline) is [baseline]
/// logical pixels below the top of this box, then sizes this box to
1107 1108 1109 1110
/// contain the child.
///
/// If [baseline] is less than the distance from the top of the child
/// to the baseline of the child, then the child will overflow the top
1111
/// of the box. This is typically not desirable, in particular, that
1112 1113 1114 1115 1116 1117 1118 1119
/// part of the child will not be found when doing hit tests, so the
/// user cannot interact with that part of the child.
///
/// This box will be sized so that its bottom is coincident with the
/// bottom of the child. This means if this box shifts the child down,
/// there will be space between the top of this box and the top of the
/// child, but there is never space between the bottom of the child
/// and the bottom of the box.
1120
class RenderBaseline extends RenderShiftedBox {
1121 1122
  /// Creates a [RenderBaseline] object.
  ///
1123
  /// The [baseline] and [baselineType] arguments must not be null.
1124 1125
  RenderBaseline({
    RenderBox child,
1126
    @required double baseline,
1127
    @required TextBaseline baselineType,
1128 1129 1130
  }) : assert(baseline != null),
       assert(baselineType != null),
       _baseline = baseline,
1131
       _baselineType = baselineType,
1132
       super(child);
1133

1134 1135
  /// The number of logical pixels from the top of this box at which to position
  /// the child's baseline.
1136
  double get baseline => _baseline;
1137
  double _baseline;
1138
  set baseline(double value) {
1139 1140 1141 1142 1143 1144 1145
    assert(value != null);
    if (_baseline == value)
      return;
    _baseline = value;
    markNeedsLayout();
  }

1146
  /// The type of baseline to use for positioning the child.
1147
  TextBaseline get baselineType => _baselineType;
1148
  TextBaseline _baselineType;
1149
  set baselineType(TextBaseline value) {
1150 1151 1152 1153 1154 1155 1156
    assert(value != null);
    if (_baselineType == value)
      return;
    _baselineType = value;
    markNeedsLayout();
  }

1157
  @override
1158 1159 1160
  void performLayout() {
    if (child != null) {
      child.layout(constraints.loosen(), parentUsesSize: true);
1161
      final double childBaseline = child.getDistanceToBaseline(baselineType);
1162
      final double actualBaseline = baseline;
1163
      final double top = actualBaseline - childBaseline;
Hixie's avatar
Hixie committed
1164
      final BoxParentData childParentData = child.parentData;
1165
      childParentData.offset = Offset(0.0, top);
1166
      final Size childSize = child.size;
1167
      size = constraints.constrain(Size(childSize.width, top + childSize.height));
1168 1169 1170 1171 1172
    } else {
      performResize();
    }
  }

1173
  @override
1174 1175
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
1176 1177
    properties.add(DoubleProperty('baseline', baseline));
    properties.add(EnumProperty<TextBaseline>('baselineType', baselineType));
1178
  }
1179
}