shifted_box.dart 42.4 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 192
    if (child == null) {
      size = constraints.constrain(new 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
    childParentData.offset = new Offset(_resolvedPadding.left, _resolvedPadding.top);
202
    size = constraints.constrain(new 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
  void debugFillProperties(DiagnosticPropertiesBuilder description) {
220
    super.debugFillProperties(description);
221
    description.add(new DiagnosticsProperty<EdgeInsetsGeometry>('padding', padding));
222
    description.add(new 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 242 243 244 245 246
  /// A constructor to be used only when the extending class also has a mixin.
  // TODO(gspencer): Remove this constructor once https://github.com/dart-lang/sdk/issues/15101 is fixed.
  @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 a [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
  void debugFillProperties(DiagnosticPropertiesBuilder description) {
319
    super.debugFillProperties(description);
320
    description.add(new DiagnosticsProperty<AlignmentGeometry>('alignment', alignment));
321
    description.add(new EnumProperty<TextDirection>('textDirection', textDirection, defaultValue: null));
322 323 324
  }
}

325
/// Positions its child using a [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 383
      size = constraints.constrain(new Size(shrinkWrapWidth ? child.size.width * (_widthFactor ?? 1.0) : double.INFINITY,
                                            shrinkWrapHeight ? child.size.height * (_heightFactor ?? 1.0) : double.INFINITY));
384
      alignChild();
385
    } else {
386 387
      size = constraints.constrain(new Size(shrinkWrapWidth ? 0.0 : double.INFINITY,
                                            shrinkWrapHeight ? 0.0 : double.INFINITY));
388 389 390
    }
  }

391
  @override
392 393 394 395 396 397 398
  void debugPaintSize(PaintingContext context, Offset offset) {
    super.debugPaintSize(context, offset);
    assert(() {
      Paint paint;
      if (child != null && !child.size.isEmpty) {
        Path path;
        paint = new Paint()
399
          ..style = PaintingStyle.stroke
400
          ..strokeWidth = 1.0
401
          ..color = const Color(0xFFFFFF00);
402 403 404 405
        path = new Path();
        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 441
          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 {
        paint = new Paint()
442
          ..color = const Color(0x90909090);
443 444 445
        context.canvas.drawRect(offset & size, paint);
      }
      return true;
446
    }());
447 448
  }

449
  @override
450
  void debugFillProperties(DiagnosticPropertiesBuilder description) {
451 452 453
    super.debugFillProperties(description);
    description.add(new DoubleProperty('widthFactor', _widthFactor, ifNull: 'expand'));
    description.add(new 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 487
///
/// 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.

488
class RenderConstrainedOverflowBox extends RenderAligningShiftedBox {
489
  /// Creates a render object that lets its child overflow itself.
490
  RenderConstrainedOverflowBox({
491 492 493 494 495
    RenderBox child,
    double minWidth,
    double maxWidth,
    double minHeight,
    double maxHeight,
496
    AlignmentGeometry alignment: Alignment.center,
497
    TextDirection textDirection,
498 499 500 501
  }) : _minWidth = minWidth,
       _maxWidth = maxWidth,
       _minHeight = minHeight,
       _maxHeight = maxHeight,
502
       super(child: child, alignment: alignment, textDirection: textDirection);
503 504 505 506 507

  /// 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;
508
  set minWidth(double value) {
509 510 511 512 513 514 515 516 517 518
    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;
519
  set maxWidth(double value) {
520 521 522 523 524 525 526 527 528 529
    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;
530
  set minHeight(double value) {
531 532 533 534 535 536 537 538 539 540
    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;
541
  set maxHeight(double value) {
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
    if (_maxHeight == value)
      return;
    _maxHeight = value;
    markNeedsLayout();
  }

  BoxConstraints _getInnerConstraints(BoxConstraints constraints) {
    return new BoxConstraints(
      minWidth: _minWidth ?? constraints.minWidth,
      maxWidth: _maxWidth ?? constraints.maxWidth,
      minHeight: _minHeight ?? constraints.minHeight,
      maxHeight: _maxHeight ?? constraints.maxHeight
    );
  }

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

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

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

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

583 584 585 586 587 588
/// 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
/// on an infinite canvas with no constraints. This box will then expand
/// as much as it can within its own constraints and align the child based on
589
/// [alignment]. If the box cannot expand enough to accommodate the entire
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
/// child, the child will be clipped.
///
/// In debug mode, if the child overflows the box, a warning will be printed on
/// the console, and black and yellow striped areas will appear where theR
/// overflow occurs.
///
/// See also:
///
///  * [RenderConstrainedBox] renders a box which imposes constraints on its
///    child.
///  * [RenderConstrainedOverflowBox], renders a box that imposes different
///    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 634
  /// be retained, and if set to [Axis.horizontal], then horizontal constraints
  /// will be retained.
  Axis get constrainedAxis => _constrainedAxis;
  Axis _constrainedAxis;
  set constrainedAxis(Axis value) {
    assert(value != null);
    if (_constrainedAxis == value)
      return;
    _constrainedAxis = value;
    markNeedsLayout();
  }
635

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

  @override
  void performLayout() {
    if (child != null) {
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
      // Let the child lay itself out at it's "natural" size, but if
      // constrainedAxis is non-null, keep any constraints on that axis.
      if (constrainedAxis != null) {
        switch (constrainedAxis) {
          case Axis.horizontal:
            child.layout(new BoxConstraints(
              maxWidth: constraints.maxWidth, minWidth: constraints.minWidth),
              parentUsesSize: true,
            );
            break;
          case Axis.vertical:
            child.layout(new BoxConstraints(
              maxHeight: constraints.maxHeight, minHeight: constraints.minHeight),
              parentUsesSize: true,
            );
            break;
        }
      } else {
        child.layout(const BoxConstraints(), parentUsesSize: true);
      }
663 664 665 666 667 668 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 717 718 719 720 721 722 723 724 725 726
      size = constraints.constrain(child.size);
      alignChild();
      final BoxParentData childParentData = child.parentData;
      _overflowContainerRect = Offset.zero & size;
      _overflowChildRect = childParentData.offset & child.size;
    } else {
      size = constraints.constrain(Size.zero);
      _overflowContainerRect = Rect.zero;
      _overflowChildRect = Rect.zero;
    }

    final RelativeRect overflow = new RelativeRect.fromRect(_overflowContainerRect, _overflowChildRect);
    _isOverflowing = overflow.left > 0.0 ||
      overflow.right > 0.0 ||
      overflow.top > 0.0 ||
      overflow.bottom > 0.0;
  }

  @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.
727
class RenderSizedOverflowBox extends RenderAligningShiftedBox {
728 729 730
  /// Creates a render box of a given size that lets its child overflow.
  ///
  /// The [requestedSize] argument must not be null.
731 732
  RenderSizedOverflowBox({
    RenderBox child,
733
    @required Size requestedSize,
734
    Alignment alignment: Alignment.center,
735
    TextDirection textDirection,
736 737
  }) : assert(requestedSize != null),
       _requestedSize = requestedSize,
738
       super(child: child, alignment: alignment, textDirection: textDirection);
739 740 741 742

  /// The size this render box should attempt to be.
  Size get requestedSize => _requestedSize;
  Size _requestedSize;
743
  set requestedSize(Size value) {
744 745 746 747 748 749 750 751
    assert(value != null);
    if (_requestedSize == value)
      return;
    _requestedSize = value;
    markNeedsLayout();
  }

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

  @override
757
  double computeMaxIntrinsicWidth(double height) {
758
    return _requestedSize.width;
759 760 761
  }

  @override
762
  double computeMinIntrinsicHeight(double width) {
763
    return _requestedSize.height;
764 765 766
  }

  @override
767
  double computeMaxIntrinsicHeight(double width) {
768
    return _requestedSize.height;
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
  }

  @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 {
798 799 800 801
  /// 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.
802 803 804 805
  RenderFractionallySizedOverflowBox({
    RenderBox child,
    double widthFactor,
    double heightFactor,
806
    Alignment alignment: Alignment.center,
807
    TextDirection textDirection,
808 809
  }) : _widthFactor = widthFactor,
       _heightFactor = heightFactor,
810
       super(child: child, alignment: alignment, textDirection: textDirection) {
811 812 813 814 815 816 817
    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
818
  /// incoming width constraint multiplied by this factor. If null, the child is
819
  /// given the incoming width constraints.
820 821
  double get widthFactor => _widthFactor;
  double _widthFactor;
822
  set widthFactor(double value) {
823 824 825 826 827 828 829 830 831 832
    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
833
  /// incoming width constraint multiplied by this factor. If null, the child is
834
  /// given the incoming width constraints.
835 836
  double get heightFactor => _heightFactor;
  double _heightFactor;
837
  set heightFactor(double value) {
838 839 840 841 842 843 844 845 846 847 848
    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) {
849
      final double width = maxWidth * _widthFactor;
850 851 852 853 854 855
      minWidth = width;
      maxWidth = width;
    }
    double minHeight = constraints.minHeight;
    double maxHeight = constraints.maxHeight;
    if (_heightFactor != null) {
856
      final double height = maxHeight * _heightFactor;
857 858 859 860 861 862 863 864 865 866 867 868
      minHeight = height;
      maxHeight = height;
    }
    return new BoxConstraints(
      minWidth: minWidth,
      maxWidth: maxWidth,
      minHeight: minHeight,
      maxHeight: maxHeight
    );
  }

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

  @override
881
  double computeMaxIntrinsicWidth(double height) {
882 883
    double result;
    if (child == null) {
884
      result = super.computeMaxIntrinsicWidth(height);
885 886 887 888 889
    } else { // the following line relies on double.INFINITY absorption
      result = child.getMaxIntrinsicWidth(height * (_heightFactor ?? 1.0));
    }
    assert(result.isFinite);
    return result / (_widthFactor ?? 1.0);
890 891 892
  }

  @override
893
  double computeMinIntrinsicHeight(double width) {
894 895
    double result;
    if (child == null) {
896
      result = super.computeMinIntrinsicHeight(width);
897 898 899 900 901
    } else { // the following line relies on double.INFINITY absorption
      result = child.getMinIntrinsicHeight(width * (_widthFactor ?? 1.0));
    }
    assert(result.isFinite);
    return result / (_heightFactor ?? 1.0);
902 903 904
  }

  @override
905
  double computeMaxIntrinsicHeight(double width) {
906 907
    double result;
    if (child == null) {
908
      result = super.computeMaxIntrinsicHeight(width);
909 910 911 912 913
    } else { // the following line relies on double.INFINITY absorption
      result = child.getMaxIntrinsicHeight(width * (_widthFactor ?? 1.0));
    }
    assert(result.isFinite);
    return result / (_heightFactor ?? 1.0);
914 915 916 917 918 919 920 921 922 923 924 925 926 927
  }

  @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
928
  void debugFillProperties(DiagnosticPropertiesBuilder description) {
929 930 931
    super.debugFillProperties(description);
    description.add(new DoubleProperty('widthFactor', _widthFactor, ifNull: 'pass-through'));
    description.add(new DoubleProperty('heightFactor', _heightFactor, ifNull: 'pass-through'));
932 933 934
  }
}

Adam Barth's avatar
Adam Barth committed
935
/// A delegate for computing the layout of a render object with a single child.
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
///
/// 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.
960
abstract class SingleChildLayoutDelegate {
961 962 963 964
  /// Creates a layout delegate.
  ///
  /// The layout will update whenever [relayout] notifies its listeners.
  const SingleChildLayoutDelegate({ Listenable relayout }) : _relayout = relayout;
965

966
  final Listenable _relayout;
967 968 969

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

973 974 975 976 977 978 979
  /// 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
980 981
  BoxConstraints getConstraintsForChild(BoxConstraints constraints) => constraints;

982 983 984 985 986 987 988 989 990
  /// 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.
991
  Offset getPositionForChild(Size size, Size childSize) => Offset.zero;
992

993 994 995 996 997 998 999
  /// 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
1000 1001
  /// instance, then the method should return true, otherwise it should return
  /// false.
1002
  ///
1003
  /// If the method returns false, then the [getSize],
1004 1005 1006 1007
  /// [getConstraintsForChild], and [getPositionForChild] calls might be
  /// optimized away.
  ///
  /// It's possible that the layout methods will get called even if
1008
  /// [shouldRelayout] returns false (e.g. if an ancestor changed its layout).
1009 1010 1011
  /// It's also possible that the layout method will get called
  /// without [shouldRelayout] being called at all (e.g. if the parent changes
  /// size).
1012
  bool shouldRelayout(covariant SingleChildLayoutDelegate oldDelegate);
Adam Barth's avatar
Adam Barth committed
1013 1014
}

1015 1016 1017 1018 1019 1020
/// 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.
1021
class RenderCustomSingleChildLayoutBox extends RenderShiftedBox {
1022
  /// Creates a render box that defers its layout to a delegate.
1023 1024
  ///
  /// The [delegate] argument must not be null.
1025
  RenderCustomSingleChildLayoutBox({
Adam Barth's avatar
Adam Barth committed
1026
    RenderBox child,
1027
    @required SingleChildLayoutDelegate delegate
1028 1029 1030
  }) : assert(delegate != null),
       _delegate = delegate,
       super(child);
Adam Barth's avatar
Adam Barth committed
1031

1032
  /// A delegate that controls this object's layout.
1033 1034
  SingleChildLayoutDelegate get delegate => _delegate;
  SingleChildLayoutDelegate _delegate;
1035
  set delegate(SingleChildLayoutDelegate newDelegate) {
Adam Barth's avatar
Adam Barth committed
1036 1037 1038
    assert(newDelegate != null);
    if (_delegate == newDelegate)
      return;
1039 1040
    final SingleChildLayoutDelegate oldDelegate = _delegate;
    if (newDelegate.runtimeType != oldDelegate.runtimeType || newDelegate.shouldRelayout(oldDelegate))
1041
      markNeedsLayout();
Adam Barth's avatar
Adam Barth committed
1042
    _delegate = newDelegate;
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
    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
1059 1060 1061 1062 1063 1064
  }

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

1065 1066 1067 1068
  // 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.

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

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

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

1093
  @override
1094
  double computeMaxIntrinsicHeight(double width) {
1095 1096 1097 1098
    final double height = _getSize(new BoxConstraints.tightForFinite(width: width)).height;
    if (height.isFinite)
      return height;
    return 0.0;
Adam Barth's avatar
Adam Barth committed
1099 1100
  }

1101
  @override
Adam Barth's avatar
Adam Barth committed
1102
  void performLayout() {
1103
    size = _getSize(constraints);
Adam Barth's avatar
Adam Barth committed
1104
    if (child != null) {
1105
      final BoxConstraints childConstraints = delegate.getConstraintsForChild(constraints);
1106
      assert(childConstraints.debugAssertIsValid(isAppliedConstraint: true));
1107
      child.layout(childConstraints, parentUsesSize: !childConstraints.isTight);
Adam Barth's avatar
Adam Barth committed
1108
      final BoxParentData childParentData = child.parentData;
1109
      childParentData.offset = delegate.getPositionForChild(size, childConstraints.isTight ? childConstraints.smallest : child.size);
Adam Barth's avatar
Adam Barth committed
1110 1111 1112 1113
    }
  }
}

1114 1115 1116
/// 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
1117 1118 1119 1120
/// 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
1121
/// of the box. This is typically not desirable, in particular, that
1122 1123 1124 1125 1126 1127 1128 1129
/// 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.
1130
class RenderBaseline extends RenderShiftedBox {
1131 1132
  /// Creates a [RenderBaseline] object.
  ///
1133
  /// The [baseline] and [baselineType] arguments must not be null.
1134 1135
  RenderBaseline({
    RenderBox child,
1136 1137
    @required double baseline,
    @required TextBaseline baselineType
1138 1139 1140
  }) : assert(baseline != null),
       assert(baselineType != null),
       _baseline = baseline,
1141
       _baselineType = baselineType,
1142
       super(child);
1143

1144 1145
  /// The number of logical pixels from the top of this box at which to position
  /// the child's baseline.
1146
  double get baseline => _baseline;
1147
  double _baseline;
1148
  set baseline(double value) {
1149 1150 1151 1152 1153 1154 1155
    assert(value != null);
    if (_baseline == value)
      return;
    _baseline = value;
    markNeedsLayout();
  }

1156
  /// The type of baseline to use for positioning the child.
1157
  TextBaseline get baselineType => _baselineType;
1158
  TextBaseline _baselineType;
1159
  set baselineType(TextBaseline value) {
1160 1161 1162 1163 1164 1165 1166
    assert(value != null);
    if (_baselineType == value)
      return;
    _baselineType = value;
    markNeedsLayout();
  }

1167
  @override
1168 1169 1170
  void performLayout() {
    if (child != null) {
      child.layout(constraints.loosen(), parentUsesSize: true);
1171
      final double childBaseline = child.getDistanceToBaseline(baselineType);
1172
      final double actualBaseline = baseline;
1173
      final double top = actualBaseline - childBaseline;
Hixie's avatar
Hixie committed
1174
      final BoxParentData childParentData = child.parentData;
1175 1176 1177
      childParentData.offset = new Offset(0.0, top);
      final Size childSize = child.size;
      size = constraints.constrain(new Size(childSize.width, top + childSize.height));
1178 1179 1180 1181 1182
    } else {
      performResize();
    }
  }

1183
  @override
1184
  void debugFillProperties(DiagnosticPropertiesBuilder description) {
1185 1186 1187
    super.debugFillProperties(description);
    description.add(new DoubleProperty('baseline', baseline));
    description.add(new EnumProperty<TextBaseline>('baselineType', baselineType));
1188
  }
1189
}