shifted_box.dart 43 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(BoxHitTestResult result, { Offset position }) {
76
    if (child != null) {
Hixie's avatar
Hixie committed
77
      final BoxParentData childParentData = child.parentData;
78 79 80 81 82 83 84 85
      return result.addWithPaintOffset(
        offset: childParentData.offset,
        position: position,
        hitTest: (BoxHitTestResult result, Offset transformed) {
          assert(transformed == position - childParentData.offset);
          return child.hitTest(result, position: transformed);
        },
      );
86
    }
Adam Barth's avatar
Adam Barth committed
87
    return false;
88 89 90 91
  }

}

92 93 94 95 96 97
/// 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.
98
class RenderPadding extends RenderShiftedBox {
99 100 101
  /// Creates a render object that insets its child.
  ///
  /// The [padding] argument must not be null and must have non-negative insets.
102
  RenderPadding({
103 104 105
    @required EdgeInsetsGeometry padding,
    TextDirection textDirection,
    RenderBox child,
106 107
  }) : assert(padding != null),
       assert(padding.isNonNegative),
108
       _textDirection = textDirection,
109
       _padding = padding,
Ian Hickson's avatar
Ian Hickson committed
110
       super(child);
111 112 113

  EdgeInsets _resolvedPadding;

Ian Hickson's avatar
Ian Hickson committed
114 115 116 117 118 119 120 121 122 123
  void _resolve() {
    if (_resolvedPadding != null)
      return;
    _resolvedPadding = padding.resolve(textDirection);
    assert(_resolvedPadding.isNonNegative);
  }

  void _markNeedResolution() {
    _resolvedPadding = null;
    markNeedsLayout();
124
  }
125

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

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

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

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

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

184
  @override
185
  double computeMaxIntrinsicHeight(double width) {
Ian Hickson's avatar
Ian Hickson committed
186
    _resolve();
187 188
    final double totalHorizontalPadding = _resolvedPadding.left + _resolvedPadding.right;
    final double totalVerticalPadding = _resolvedPadding.top + _resolvedPadding.bottom;
189
    if (child != null) // next line relies on double.infinity absorption
190
      return child.getMaxIntrinsicHeight(math.max(0.0, width - totalHorizontalPadding)) + totalVerticalPadding;
191
    return totalVerticalPadding;
192 193
  }

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

215
  @override
216 217 218
  void debugPaintSize(PaintingContext context, Offset offset) {
    super.debugPaintSize(context, offset);
    assert(() {
219
      final Rect outerRect = offset & size;
220
      debugPaintPadding(context.canvas, outerRect, child != null ? _resolvedPadding.deflateRect(outerRect) : null);
221
      return true;
222
    }());
223 224
  }

225
  @override
226 227
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
228 229
    properties.add(DiagnosticsProperty<EdgeInsetsGeometry>('padding', padding));
    properties.add(EnumProperty<TextDirection>('textDirection', textDirection, defaultValue: null));
230
  }
231 232
}

233
/// Abstract class for one-child-layout render boxes that use a
234
/// [AlignmentGeometry] to align their children.
235
abstract class RenderAligningShiftedBox extends RenderShiftedBox {
236 237 238
  /// Initializes member variables for subclasses.
  ///
  /// The [alignment] argument must not be null.
239 240 241
  ///
  /// The [textDirection] must be non-null if the [alignment] is
  /// direction-sensitive.
242
  RenderAligningShiftedBox({
243
    AlignmentGeometry alignment = Alignment.center,
Ian Hickson's avatar
Ian Hickson committed
244
    @required TextDirection textDirection,
245 246
    RenderBox child,
  }) : assert(alignment != null),
247
       _alignment = alignment,
248
       _textDirection = textDirection,
Ian Hickson's avatar
Ian Hickson committed
249
       super(child);
250

251
  /// A constructor to be used only when the extending class also has a mixin.
252
  // TODO(gspencer): Remove this constructor once https://github.com/dart-lang/sdk/issues/31543 is fixed.
253
  @protected
254
  RenderAligningShiftedBox.mixin(AlignmentGeometry alignment, TextDirection textDirection, RenderBox child)
255 256
    : this(alignment: alignment, textDirection: textDirection, child: child);

257
  Alignment _resolvedAlignment;
258

Ian Hickson's avatar
Ian Hickson committed
259 260 261 262 263 264 265 266 267
  void _resolve() {
    if (_resolvedAlignment != null)
      return;
    _resolvedAlignment = alignment.resolve(textDirection);
  }

  void _markNeedResolution() {
    _resolvedAlignment = null;
    markNeedsLayout();
268
  }
269

270 271 272
  /// How to align the child.
  ///
  /// The x and y values of the alignment control the horizontal and vertical
273
  /// alignment, respectively. An x value of -1.0 means that the left edge of
274 275 276
  /// 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.
277
  /// For example, a value of 0.0 means that the center of the child is aligned
278
  /// with the center of the parent.
279
  ///
280
  /// If this is set to an [AlignmentDirectional] object, then
281
  /// [textDirection] must not be null.
282 283
  AlignmentGeometry get alignment => _alignment;
  AlignmentGeometry _alignment;
284 285
  /// Sets the alignment to a new value, and triggers a layout update.
  ///
Ian Hickson's avatar
Ian Hickson committed
286
  /// The new alignment must not be null.
287
  set alignment(AlignmentGeometry value) {
288
    assert(value != null);
289
    if (_alignment == value)
290
      return;
291
    _alignment = value;
Ian Hickson's avatar
Ian Hickson committed
292
    _markNeedResolution();
293 294 295
  }

  /// The text direction with which to resolve [alignment].
Ian Hickson's avatar
Ian Hickson committed
296 297 298
  ///
  /// This may be changed to null, but only after [alignment] has been changed
  /// to a value that does not depend on the direction.
299 300 301 302 303 304
  TextDirection get textDirection => _textDirection;
  TextDirection _textDirection;
  set textDirection(TextDirection value) {
    if (_textDirection == value)
      return;
    _textDirection = value;
Ian Hickson's avatar
Ian Hickson committed
305
    _markNeedResolution();
306 307
  }

308 309 310 311 312 313 314 315
  /// 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.
316
  @protected
317
  void alignChild() {
Ian Hickson's avatar
Ian Hickson committed
318
    _resolve();
319
    assert(child != null);
320
    assert(!child.debugNeedsLayout);
321 322
    assert(child.hasSize);
    assert(hasSize);
Ian Hickson's avatar
Ian Hickson committed
323
    assert(_resolvedAlignment != null);
324
    final BoxParentData childParentData = child.parentData;
325
    childParentData.offset = _resolvedAlignment.alongOffset(size - child.size);
326 327 328
  }

  @override
329 330
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
331 332
    properties.add(DiagnosticsProperty<AlignmentGeometry>('alignment', alignment));
    properties.add(EnumProperty<TextDirection>('textDirection', textDirection, defaultValue: null));
333 334 335
  }
}

336
/// Positions its child using an [AlignmentGeometry].
337 338 339
///
/// 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,
340
/// with an alignment of [Alignment.bottomRight].
341 342 343 344 345 346
///
/// 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 {
347
  /// Creates a render object that positions its child.
348 349 350 351
  RenderPositionedBox({
    RenderBox child,
    double widthFactor,
    double heightFactor,
352
    AlignmentGeometry alignment = Alignment.center,
353
    TextDirection textDirection,
354 355 356
  }) : assert(widthFactor == null || widthFactor >= 0.0),
       assert(heightFactor == null || heightFactor >= 0.0),
       _widthFactor = widthFactor,
357
       _heightFactor = heightFactor,
358
       super(child: child, alignment: alignment, textDirection: textDirection);
359

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

373
  /// If non-null, sets its height to the child's height multiplied by this factor.
374 375
  ///
  /// Can be both greater and less than 1.0 but must be positive.
376
  double get heightFactor => _heightFactor;
377
  double _heightFactor;
378
  set heightFactor(double value) {
379
    assert(value == null || value >= 0.0);
380 381 382 383 384
    if (_heightFactor == value)
      return;
    _heightFactor = value;
    markNeedsLayout();
  }
385

386
  @override
387
  void performLayout() {
388 389
    final bool shrinkWrapWidth = _widthFactor != null || constraints.maxWidth == double.infinity;
    final bool shrinkWrapHeight = _heightFactor != null || constraints.maxHeight == double.infinity;
390

391 392
    if (child != null) {
      child.layout(constraints.loosen(), parentUsesSize: true);
393
      size = constraints.constrain(Size(shrinkWrapWidth ? child.size.width * (_widthFactor ?? 1.0) : double.infinity,
394
                                            shrinkWrapHeight ? child.size.height * (_heightFactor ?? 1.0) : double.infinity));
395
      alignChild();
396
    } else {
397
      size = constraints.constrain(Size(shrinkWrapWidth ? 0.0 : double.infinity,
398
                                            shrinkWrapHeight ? 0.0 : double.infinity));
399 400 401
    }
  }

402
  @override
403 404 405 406 407 408
  void debugPaintSize(PaintingContext context, Offset offset) {
    super.debugPaintSize(context, offset);
    assert(() {
      Paint paint;
      if (child != null && !child.size.isEmpty) {
        Path path;
409
        paint = Paint()
410
          ..style = PaintingStyle.stroke
411
          ..strokeWidth = 1.0
412
          ..color = const Color(0xFFFFFF00);
413
        path = Path();
414 415 416
        final BoxParentData childParentData = child.parentData;
        if (childParentData.offset.dy > 0.0) {
          // vertical alignment arrows
417
          final double headSize = math.min(childParentData.offset.dy * 0.2, 10.0);
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
          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
435
          final double headSize = math.min(childParentData.offset.dx * 0.2, 10.0);
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
          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 {
452
        paint = Paint()
453
          ..color = const Color(0x90909090);
454 455 456
        context.canvas.drawRect(offset & size, paint);
      }
      return true;
457
    }());
458 459
  }

460
  @override
461 462
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
463 464
    properties.add(DoubleProperty('widthFactor', _widthFactor, ifNull: 'expand'));
    properties.add(DoubleProperty('heightFactor', _heightFactor, ifNull: 'expand'));
465
  }
466 467
}

468 469 470 471 472 473 474 475 476 477 478 479 480
/// 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
481 482 483 484
/// 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.
485
///
486
/// The child is positioned according to [alignment]. To position a smaller
487
/// child inside a larger parent, use [RenderPositionedBox] and
488
/// [RenderConstrainedBox] rather than RenderConstrainedOverflowBox.
489 490 491 492 493 494 495 496 497
///
/// 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.
498
class RenderConstrainedOverflowBox extends RenderAligningShiftedBox {
499
  /// Creates a render object that lets its child overflow itself.
500
  RenderConstrainedOverflowBox({
501 502 503 504 505
    RenderBox child,
    double minWidth,
    double maxWidth,
    double minHeight,
    double maxHeight,
506
    AlignmentGeometry alignment = Alignment.center,
507
    TextDirection textDirection,
508 509 510 511
  }) : _minWidth = minWidth,
       _maxWidth = maxWidth,
       _minHeight = minHeight,
       _maxHeight = maxHeight,
512
       super(child: child, alignment: alignment, textDirection: textDirection);
513 514 515 516 517

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

  BoxConstraints _getInnerConstraints(BoxConstraints constraints) {
559
    return BoxConstraints(
560 561 562
      minWidth: _minWidth ?? constraints.minWidth,
      maxWidth: _maxWidth ?? constraints.maxWidth,
      minHeight: _minHeight ?? constraints.minHeight,
563
      maxHeight: _maxHeight ?? constraints.maxHeight,
564 565 566
    );
  }

567
  @override
568 569
  bool get sizedByParent => true;

570
  @override
571 572 573 574
  void performResize() {
    size = constraints.biggest;
  }

575
  @override
576 577 578
  void performLayout() {
    if (child != null) {
      child.layout(_getInnerConstraints(constraints), parentUsesSize: true);
579
      alignChild();
580 581 582
    }
  }

583
  @override
584 585
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
586 587 588 589
    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'));
590 591 592
  }
}

593 594 595 596
/// 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
597 598 599 600 601
/// 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.
602 603
///
/// In debug mode, if the child overflows the box, a warning will be printed on
604
/// the console, and black and yellow striped areas will appear where the
605 606 607 608
/// overflow occurs.
///
/// See also:
///
609 610 611
///  * [RenderConstrainedBox], which renders a box which imposes constraints
///    on its child.
///  * [RenderConstrainedOverflowBox], which renders a box that imposes different
612 613 614 615 616 617
///    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 {
618 619 620 621
  /// 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.
622 623 624
  RenderUnconstrainedBox({
    @required AlignmentGeometry alignment,
    @required TextDirection textDirection,
625
    Axis constrainedAxis,
626 627
    RenderBox child,
  }) : assert(alignment != null),
628 629
       _constrainedAxis = constrainedAxis,
       super.mixin(alignment, textDirection, child);
630

631 632 633
  /// The axis to retain constraints on, if any.
  ///
  /// If not set, or set to null (the default), neither axis will retain its
634
  /// constraints. If set to [Axis.vertical], then vertical constraints will
635 636 637 638 639 640 641 642 643 644
  /// 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();
  }
645

646 647 648 649 650 651 652
  Rect _overflowContainerRect = Rect.zero;
  Rect _overflowChildRect = Rect.zero;
  bool _isOverflowing = false;

  @override
  void performLayout() {
    if (child != null) {
653 654
      // Let the child lay itself out at it's "natural" size, but if
      // constrainedAxis is non-null, keep any constraints on that axis.
655
      BoxConstraints childConstraints;
656 657 658
      if (constrainedAxis != null) {
        switch (constrainedAxis) {
          case Axis.horizontal:
659
            childConstraints = BoxConstraints(maxWidth: constraints.maxWidth, minWidth: constraints.minWidth);
660 661
            break;
          case Axis.vertical:
662
            childConstraints = BoxConstraints(maxHeight: constraints.maxHeight, minHeight: constraints.minHeight);
663 664 665
            break;
        }
      } else {
666
        childConstraints = const BoxConstraints();
667
      }
668
      child.layout(childConstraints, parentUsesSize: true);
669 670 671 672 673 674
      size = constraints.constrain(child.size);
      alignChild();
      final BoxParentData childParentData = child.parentData;
      _overflowContainerRect = Offset.zero & size;
      _overflowChildRect = childParentData.offset & child.size;
    } else {
675
      size = constraints.smallest;
676 677 678
      _overflowContainerRect = Rect.zero;
      _overflowChildRect = Rect.zero;
    }
679
    _isOverflowing = RelativeRect.fromRect(_overflowContainerRect, _overflowChildRect).hasInsets;
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
  }

  @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.
///
721 722 723
/// If the child's resulting size differs from this render object's size, then
/// the child is aligned according to the [alignment] property.
///
724
/// See also:
725
///
726 727 728 729 730 731
///  * [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.
732
class RenderSizedOverflowBox extends RenderAligningShiftedBox {
733 734
  /// Creates a render box of a given size that lets its child overflow.
  ///
735 736 737 738
  /// The [requestedSize] and [alignment] arguments must not be null.
  ///
  /// The [textDirection] argument must not be null if the [alignment] is
  /// direction-sensitive.
739 740
  RenderSizedOverflowBox({
    RenderBox child,
741
    @required Size requestedSize,
742
    AlignmentGeometry alignment = Alignment.center,
743
    TextDirection textDirection,
744 745
  }) : assert(requestedSize != null),
       _requestedSize = requestedSize,
746
       super(child: child, alignment: alignment, textDirection: textDirection);
747 748 749 750

  /// The size this render box should attempt to be.
  Size get requestedSize => _requestedSize;
  Size _requestedSize;
751
  set requestedSize(Size value) {
752 753 754 755 756 757 758 759
    assert(value != null);
    if (_requestedSize == value)
      return;
    _requestedSize = value;
    markNeedsLayout();
  }

  @override
760
  double computeMinIntrinsicWidth(double height) {
761
    return _requestedSize.width;
762 763 764
  }

  @override
765
  double computeMaxIntrinsicWidth(double height) {
766
    return _requestedSize.width;
767 768 769
  }

  @override
770
  double computeMinIntrinsicHeight(double width) {
771
    return _requestedSize.height;
772 773 774
  }

  @override
775
  double computeMaxIntrinsicHeight(double width) {
776
    return _requestedSize.height;
777 778 779 780 781 782 783 784 785 786 787 788 789
  }

  @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) {
790
      child.layout(constraints, parentUsesSize: true);
791 792 793 794 795 796 797 798 799 800 801 802 803
      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.
///
804 805 806
/// It then tries to size itself to the size of its child. Where this is not
/// possible (e.g. if the constraints from the parent are themselves tight), the
/// child is aligned according to [alignment].
807
class RenderFractionallySizedOverflowBox extends RenderAligningShiftedBox {
808 809 810 811
  /// 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.
812 813 814 815 816
  ///
  /// The [alignment] must not be null.
  ///
  /// The [textDirection] must be non-null if the [alignment] is
  /// direction-sensitive.
817 818 819 820
  RenderFractionallySizedOverflowBox({
    RenderBox child,
    double widthFactor,
    double heightFactor,
821
    AlignmentGeometry alignment = Alignment.center,
822
    TextDirection textDirection,
823 824
  }) : _widthFactor = widthFactor,
       _heightFactor = heightFactor,
825
       super(child: child, alignment: alignment, textDirection: textDirection) {
826 827 828 829 830 831 832
    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
833
  /// incoming width constraint multiplied by this factor. If null, the child is
834
  /// given the incoming width constraints.
835 836
  double get widthFactor => _widthFactor;
  double _widthFactor;
837
  set widthFactor(double value) {
838 839 840 841 842 843 844 845 846 847
    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
848
  /// incoming width constraint multiplied by this factor. If null, the child is
849
  /// given the incoming width constraints.
850 851
  double get heightFactor => _heightFactor;
  double _heightFactor;
852
  set heightFactor(double value) {
853 854 855 856 857 858 859 860 861 862 863
    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) {
864
      final double width = maxWidth * _widthFactor;
865 866 867 868 869 870
      minWidth = width;
      maxWidth = width;
    }
    double minHeight = constraints.minHeight;
    double maxHeight = constraints.maxHeight;
    if (_heightFactor != null) {
871
      final double height = maxHeight * _heightFactor;
872 873 874
      minHeight = height;
      maxHeight = height;
    }
875
    return BoxConstraints(
876 877 878
      minWidth: minWidth,
      maxWidth: maxWidth,
      minHeight: minHeight,
879
      maxHeight: maxHeight,
880 881 882 883
    );
  }

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

  @override
896
  double computeMaxIntrinsicWidth(double height) {
897 898
    double result;
    if (child == null) {
899
      result = super.computeMaxIntrinsicWidth(height);
900
    } else { // the following line relies on double.infinity absorption
901 902 903 904
      result = child.getMaxIntrinsicWidth(height * (_heightFactor ?? 1.0));
    }
    assert(result.isFinite);
    return result / (_widthFactor ?? 1.0);
905 906 907
  }

  @override
908
  double computeMinIntrinsicHeight(double width) {
909 910
    double result;
    if (child == null) {
911
      result = super.computeMinIntrinsicHeight(width);
912
    } else { // the following line relies on double.infinity absorption
913 914 915 916
      result = child.getMinIntrinsicHeight(width * (_widthFactor ?? 1.0));
    }
    assert(result.isFinite);
    return result / (_heightFactor ?? 1.0);
917 918 919
  }

  @override
920
  double computeMaxIntrinsicHeight(double width) {
921 922
    double result;
    if (child == null) {
923
      result = super.computeMaxIntrinsicHeight(width);
924
    } else { // the following line relies on double.infinity absorption
925 926 927 928
      result = child.getMaxIntrinsicHeight(width * (_widthFactor ?? 1.0));
    }
    assert(result.isFinite);
    return result / (_heightFactor ?? 1.0);
929 930 931 932 933 934 935 936 937 938 939 940 941 942
  }

  @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
943 944
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
945 946
    properties.add(DoubleProperty('widthFactor', _widthFactor, ifNull: 'pass-through'));
    properties.add(DoubleProperty('heightFactor', _heightFactor, ifNull: 'pass-through'));
947 948 949
  }
}

Adam Barth's avatar
Adam Barth committed
950
/// A delegate for computing the layout of a render object with a single child.
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
///
/// 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.
975
abstract class SingleChildLayoutDelegate {
976 977 978 979
  /// Creates a layout delegate.
  ///
  /// The layout will update whenever [relayout] notifies its listeners.
  const SingleChildLayoutDelegate({ Listenable relayout }) : _relayout = relayout;
980

981
  final Listenable _relayout;
982 983 984

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

988 989 990 991 992 993 994
  /// 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
995 996
  BoxConstraints getConstraintsForChild(BoxConstraints constraints) => constraints;

997 998 999 1000 1001 1002 1003 1004 1005
  /// 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.
1006
  Offset getPositionForChild(Size size, Size childSize) => Offset.zero;
1007

1008 1009 1010 1011 1012 1013 1014
  /// 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
1015 1016
  /// instance, then the method should return true, otherwise it should return
  /// false.
1017
  ///
1018
  /// If the method returns false, then the [getSize],
1019 1020 1021 1022
  /// [getConstraintsForChild], and [getPositionForChild] calls might be
  /// optimized away.
  ///
  /// It's possible that the layout methods will get called even if
1023
  /// [shouldRelayout] returns false (e.g. if an ancestor changed its layout).
1024 1025 1026
  /// It's also possible that the layout method will get called
  /// without [shouldRelayout] being called at all (e.g. if the parent changes
  /// size).
1027
  bool shouldRelayout(covariant SingleChildLayoutDelegate oldDelegate);
Adam Barth's avatar
Adam Barth committed
1028 1029
}

1030 1031 1032 1033 1034 1035
/// 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.
1036
class RenderCustomSingleChildLayoutBox extends RenderShiftedBox {
1037
  /// Creates a render box that defers its layout to a delegate.
1038 1039
  ///
  /// The [delegate] argument must not be null.
1040
  RenderCustomSingleChildLayoutBox({
Adam Barth's avatar
Adam Barth committed
1041
    RenderBox child,
1042
    @required SingleChildLayoutDelegate delegate,
1043 1044 1045
  }) : assert(delegate != null),
       _delegate = delegate,
       super(child);
Adam Barth's avatar
Adam Barth committed
1046

1047
  /// A delegate that controls this object's layout.
1048 1049
  SingleChildLayoutDelegate get delegate => _delegate;
  SingleChildLayoutDelegate _delegate;
1050
  set delegate(SingleChildLayoutDelegate newDelegate) {
Adam Barth's avatar
Adam Barth committed
1051 1052 1053
    assert(newDelegate != null);
    if (_delegate == newDelegate)
      return;
1054 1055
    final SingleChildLayoutDelegate oldDelegate = _delegate;
    if (newDelegate.runtimeType != oldDelegate.runtimeType || newDelegate.shouldRelayout(oldDelegate))
1056
      markNeedsLayout();
Adam Barth's avatar
Adam Barth committed
1057
    _delegate = newDelegate;
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
    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
1074 1075 1076 1077 1078 1079
  }

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

1080 1081 1082 1083
  // 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.

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

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

1100
  @override
1101
  double computeMinIntrinsicHeight(double width) {
1102
    final double height = _getSize(BoxConstraints.tightForFinite(width: width)).height;
1103 1104 1105
    if (height.isFinite)
      return height;
    return 0.0;
Adam Barth's avatar
Adam Barth committed
1106 1107
  }

1108
  @override
1109
  double computeMaxIntrinsicHeight(double width) {
1110
    final double height = _getSize(BoxConstraints.tightForFinite(width: width)).height;
1111 1112 1113
    if (height.isFinite)
      return height;
    return 0.0;
Adam Barth's avatar
Adam Barth committed
1114 1115
  }

1116
  @override
Adam Barth's avatar
Adam Barth committed
1117
  void performLayout() {
1118
    size = _getSize(constraints);
Adam Barth's avatar
Adam Barth committed
1119
    if (child != null) {
1120
      final BoxConstraints childConstraints = delegate.getConstraintsForChild(constraints);
1121
      assert(childConstraints.debugAssertIsValid(isAppliedConstraint: true));
1122
      child.layout(childConstraints, parentUsesSize: !childConstraints.isTight);
Adam Barth's avatar
Adam Barth committed
1123
      final BoxParentData childParentData = child.parentData;
1124
      childParentData.offset = delegate.getPositionForChild(size, childConstraints.isTight ? childConstraints.smallest : child.size);
Adam Barth's avatar
Adam Barth committed
1125 1126 1127 1128
    }
  }
}

1129 1130 1131
/// 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
1132 1133 1134 1135
/// 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
1136
/// of the box. This is typically not desirable, in particular, that
1137 1138 1139 1140 1141 1142 1143 1144
/// 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.
1145
class RenderBaseline extends RenderShiftedBox {
1146 1147
  /// Creates a [RenderBaseline] object.
  ///
1148
  /// The [baseline] and [baselineType] arguments must not be null.
1149 1150
  RenderBaseline({
    RenderBox child,
1151
    @required double baseline,
1152
    @required TextBaseline baselineType,
1153 1154 1155
  }) : assert(baseline != null),
       assert(baselineType != null),
       _baseline = baseline,
1156
       _baselineType = baselineType,
1157
       super(child);
1158

1159 1160
  /// The number of logical pixels from the top of this box at which to position
  /// the child's baseline.
1161
  double get baseline => _baseline;
1162
  double _baseline;
1163
  set baseline(double value) {
1164 1165 1166 1167 1168 1169 1170
    assert(value != null);
    if (_baseline == value)
      return;
    _baseline = value;
    markNeedsLayout();
  }

1171
  /// The type of baseline to use for positioning the child.
1172
  TextBaseline get baselineType => _baselineType;
1173
  TextBaseline _baselineType;
1174
  set baselineType(TextBaseline value) {
1175 1176 1177 1178 1179 1180 1181
    assert(value != null);
    if (_baselineType == value)
      return;
    _baselineType = value;
    markNeedsLayout();
  }

1182
  @override
1183 1184 1185
  void performLayout() {
    if (child != null) {
      child.layout(constraints.loosen(), parentUsesSize: true);
1186
      final double childBaseline = child.getDistanceToBaseline(baselineType);
1187
      final double actualBaseline = baseline;
1188
      final double top = actualBaseline - childBaseline;
Hixie's avatar
Hixie committed
1189
      final BoxParentData childParentData = child.parentData;
1190
      childParentData.offset = Offset(0.0, top);
1191
      final Size childSize = child.size;
1192
      size = constraints.constrain(Size(childSize.width, top + childSize.height));
1193 1194 1195 1196 1197
    } else {
      performResize();
    }
  }

1198
  @override
1199 1200
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
1201 1202
    properties.add(DoubleProperty('baseline', baseline));
    properties.add(EnumProperty<TextBaseline>('baselineType', baselineType));
1203
  }
1204
}