shifted_box.dart 32.3 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

import 'box.dart';
8
import 'debug.dart';
9
import 'object.dart';
10

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

19
  @override
20
  double computeMinIntrinsicWidth(double height) {
21
    if (child != null)
22 23
      return child.getMinIntrinsicWidth(height);
    return 0.0;
24 25
  }

26
  @override
27
  double computeMaxIntrinsicWidth(double height) {
28
    if (child != null)
29 30
      return child.getMaxIntrinsicWidth(height);
    return 0.0;
31 32
  }

33
  @override
34
  double computeMinIntrinsicHeight(double width) {
35
    if (child != null)
36 37
      return child.getMinIntrinsicHeight(width);
    return 0.0;
38 39
  }

40
  @override
41
  double computeMaxIntrinsicHeight(double width) {
42
    if (child != null)
43 44
      return child.getMaxIntrinsicHeight(width);
    return 0.0;
45 46
  }

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

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

70
  @override
Adam Barth's avatar
Adam Barth committed
71
  bool hitTestChildren(HitTestResult result, { Point position }) {
72
    if (child != null) {
Hixie's avatar
Hixie committed
73
      final BoxParentData childParentData = child.parentData;
74 75
      final Point childPosition = new Point(position.x - childParentData.offset.dx,
                                            position.y - childParentData.offset.dy);
Adam Barth's avatar
Adam Barth committed
76
      return child.hitTest(result, position: childPosition);
77
    }
Adam Barth's avatar
Adam Barth committed
78
    return false;
79 80 81 82
  }

}

83 84 85 86 87 88
/// 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.
89
class RenderPadding extends RenderShiftedBox {
90 91 92
  /// Creates a render object that insets its child.
  ///
  /// The [padding] argument must not be null and must have non-negative insets.
93
  RenderPadding({
94
    EdgeInsets padding,
95 96
    RenderBox child
  }) : _padding = padding, super(child) {
97
    assert(padding != null);
98
    assert(padding.isNonNegative);
99 100
  }

101
  /// The amount to pad the child in each dimension.
102 103
  EdgeInsets get padding => _padding;
  EdgeInsets _padding;
104
  set padding (EdgeInsets value) {
105
    assert(value != null);
106
    assert(value.isNonNegative);
107 108 109 110 111 112
    if (_padding == value)
      return;
    _padding = value;
    markNeedsLayout();
  }

113
  @override
114
  double computeMinIntrinsicWidth(double height) {
115 116 117
    final double totalHorizontalPadding = padding.left + padding.right;
    final double totalVerticalPadding = padding.top + padding.bottom;
    if (child != null) // next line relies on double.INFINITY absorption
118
      return child.getMinIntrinsicWidth(math.max(0.0, height - totalVerticalPadding)) + totalHorizontalPadding;
119
    return totalHorizontalPadding;
120 121
  }

122
  @override
123
  double computeMaxIntrinsicWidth(double height) {
124 125 126
    final double totalHorizontalPadding = padding.left + padding.right;
    final double totalVerticalPadding = padding.top + padding.bottom;
    if (child != null) // next line relies on double.INFINITY absorption
127
      return child.getMaxIntrinsicWidth(math.max(0.0, height - totalVerticalPadding)) + totalHorizontalPadding;
128
    return totalHorizontalPadding;
129 130
  }

131
  @override
132
  double computeMinIntrinsicHeight(double width) {
133 134 135
    final double totalHorizontalPadding = padding.left + padding.right;
    final double totalVerticalPadding = padding.top + padding.bottom;
    if (child != null) // next line relies on double.INFINITY absorption
136
      return child.getMinIntrinsicHeight(math.max(0.0, width - totalHorizontalPadding)) + totalVerticalPadding;
137
    return totalVerticalPadding;
138 139
  }

140
  @override
141
  double computeMaxIntrinsicHeight(double width) {
142 143 144
    final double totalHorizontalPadding = padding.left + padding.right;
    final double totalVerticalPadding = padding.top + padding.bottom;
    if (child != null) // next line relies on double.INFINITY absorption
145
      return child.getMaxIntrinsicHeight(math.max(0.0, width - totalHorizontalPadding)) + totalVerticalPadding;
146
    return totalVerticalPadding;
147 148
  }

149
  @override
150 151 152 153 154 155 156 157 158 159 160
  void performLayout() {
    assert(padding != null);
    if (child == null) {
      size = constraints.constrain(new Size(
        padding.left + padding.right,
        padding.top + padding.bottom
      ));
      return;
    }
    BoxConstraints innerConstraints = constraints.deflate(padding);
    child.layout(innerConstraints, parentUsesSize: true);
Hixie's avatar
Hixie committed
161
    final BoxParentData childParentData = child.parentData;
162
    childParentData.offset = new Offset(padding.left, padding.top);
163 164 165 166 167 168
    size = constraints.constrain(new Size(
      padding.left + child.size.width + padding.right,
      padding.top + child.size.height + padding.bottom
    ));
  }

169
  @override
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
  void debugPaintSize(PaintingContext context, Offset offset) {
    super.debugPaintSize(context, offset);
    assert(() {
      Paint paint;
      if (child != null && !child.size.isEmpty) {
        Path path;
        paint = new Paint()
          ..color = debugPaintPaddingColor;
        path = new Path()
          ..moveTo(offset.dx, offset.dy)
          ..lineTo(offset.dx + size.width, offset.dy)
          ..lineTo(offset.dx + size.width, offset.dy + size.height)
          ..lineTo(offset.dx, offset.dy + size.height)
          ..close()
          ..moveTo(offset.dx + padding.left, offset.dy + padding.top)
          ..lineTo(offset.dx + padding.left, offset.dy + size.height - padding.bottom)
          ..lineTo(offset.dx + size.width - padding.right, offset.dy + size.height - padding.bottom)
          ..lineTo(offset.dx + size.width - padding.right, offset.dy + padding.top)
          ..close();
        context.canvas.drawPath(path, paint);
        paint = new Paint()
          ..color = debugPaintPaddingInnerEdgeColor;
192
        const double kOutline = 2.0;
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
        path = new Path()
          ..moveTo(offset.dx + math.max(padding.left - kOutline, 0.0), offset.dy + math.max(padding.top - kOutline, 0.0))
          ..lineTo(offset.dx + math.min(size.width - padding.right + kOutline, size.width), offset.dy + math.max(padding.top - kOutline, 0.0))
          ..lineTo(offset.dx + math.min(size.width - padding.right + kOutline, size.width), offset.dy + math.min(size.height - padding.bottom + kOutline, size.height))
          ..lineTo(offset.dx + math.max(padding.left - kOutline, 0.0), offset.dy + math.min(size.height - padding.bottom + kOutline, size.height))
          ..close()
          ..moveTo(offset.dx + padding.left, offset.dy + padding.top)
          ..lineTo(offset.dx + padding.left, offset.dy + size.height - padding.bottom)
          ..lineTo(offset.dx + size.width - padding.right, offset.dy + size.height - padding.bottom)
          ..lineTo(offset.dx + size.width - padding.right, offset.dy + padding.top)
          ..close();
        context.canvas.drawPath(path, paint);
      } else {
        paint = new Paint()
          ..color = debugPaintSpacingColor;
        context.canvas.drawRect(offset & size, paint);
      }
      return true;
    });
  }

214
  @override
215 216 217
  void debugFillDescription(List<String> description) {
    super.debugFillDescription(description);
    description.add('padding: $padding');
218
  }
219 220
}

221 222
/// Abstract class for one-child-layout render boxes that use a
/// [FractionalOffset] to align their children.
223
abstract class RenderAligningShiftedBox extends RenderShiftedBox {
224 225 226
  /// Initializes member variables for subclasses.
  ///
  /// The [alignment] argument must not be null.
227
  RenderAligningShiftedBox({
228 229 230
    FractionalOffset alignment: FractionalOffset.center,
    RenderBox child
  }) : _alignment = alignment, super(child) {
231
    assert(alignment != null && alignment.dx != null && alignment.dy != null);
232 233
  }

234 235 236 237 238 239 240 241 242
  /// How to align the child.
  ///
  /// The x and y values of the alignment control the horizontal and vertical
  /// alignment, respectively.  An x value of 0.0 means that the left edge of
  /// 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.
  /// For example, a value of 0.5 means that the center of the child is aligned
  /// with the center of the parent.
243 244
  FractionalOffset get alignment => _alignment;
  FractionalOffset _alignment;
245 246 247
  /// Sets the alignment to a new value, and triggers a layout update.
  ///
  /// The new alignment must not be null or have any null properties.
248
  set alignment (FractionalOffset newAlignment) {
249
    assert(newAlignment != null && newAlignment.dx != null && newAlignment.dy != null);
250
    if (_alignment == newAlignment)
251
      return;
252
    _alignment = newAlignment;
253 254 255
    markNeedsLayout();
  }

256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
  /// 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() {
    assert(child != null);
    assert(!child.needsLayout);
    assert(child.hasSize);
    assert(hasSize);
    final BoxParentData childParentData = child.parentData;
    childParentData.offset = alignment.alongOffset(size - child.size);
  }

  @override
  void debugFillDescription(List<String> description) {
    super.debugFillDescription(description);
    description.add('alignment: $alignment');
  }
}

280
/// Positions its child using a [FractionalOffset].
281 282 283
///
/// 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,
Adam Barth's avatar
Adam Barth committed
284
/// with an alignment of [FractionalOffset.bottomRight].
285 286 287 288 289 290
///
/// 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 {
291
  /// Creates a render object that positions its child.
292 293 294 295
  RenderPositionedBox({
    RenderBox child,
    double widthFactor,
    double heightFactor,
Adam Barth's avatar
Adam Barth committed
296
    FractionalOffset alignment: FractionalOffset.center
297 298 299 300 301 302 303
  }) : _widthFactor = widthFactor,
       _heightFactor = heightFactor,
       super(child: child, alignment: alignment) {
    assert(widthFactor == null || widthFactor >= 0.0);
    assert(heightFactor == null || heightFactor >= 0.0);
  }

304 305 306
  /// If non-null, sets its width to the child's width multipled by this factor.
  ///
  /// Can be both greater and less than 1.0 but must be positive.
307
  double get widthFactor => _widthFactor;
308
  double _widthFactor;
309
  set widthFactor (double value) {
310
    assert(value == null || value >= 0.0);
311
    if (_widthFactor == value)
312
      return;
313
    _widthFactor = value;
314 315 316
    markNeedsLayout();
  }

317 318 319
  /// If non-null, sets its height to the child's height multipled by this factor.
  ///
  /// Can be both greater and less than 1.0 but must be positive.
320
  double get heightFactor => _heightFactor;
321
  double _heightFactor;
322
  set heightFactor (double value) {
323
    assert(value == null || value >= 0.0);
324 325 326 327 328
    if (_heightFactor == value)
      return;
    _heightFactor = value;
    markNeedsLayout();
  }
329

330
  @override
331
  void performLayout() {
332 333
    final bool shrinkWrapWidth = _widthFactor != null || constraints.maxWidth == double.INFINITY;
    final bool shrinkWrapHeight = _heightFactor != null || constraints.maxHeight == double.INFINITY;
334

335 336
    if (child != null) {
      child.layout(constraints.loosen(), parentUsesSize: true);
337 338
      size = constraints.constrain(new Size(shrinkWrapWidth ? child.size.width * (_widthFactor ?? 1.0) : double.INFINITY,
                                            shrinkWrapHeight ? child.size.height * (_heightFactor ?? 1.0) : double.INFINITY));
339
      alignChild();
340
    } else {
341 342
      size = constraints.constrain(new Size(shrinkWrapWidth ? 0.0 : double.INFINITY,
                                            shrinkWrapHeight ? 0.0 : double.INFINITY));
343 344 345
    }
  }

346
  @override
347 348 349 350 351 352 353
  void debugPaintSize(PaintingContext context, Offset offset) {
    super.debugPaintSize(context, offset);
    assert(() {
      Paint paint;
      if (child != null && !child.size.isEmpty) {
        Path path;
        paint = new Paint()
354
          ..style = PaintingStyle.stroke
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
          ..strokeWidth = 1.0
          ..color = debugPaintArrowColor;
        path = new Path();
        final BoxParentData childParentData = child.parentData;
        if (childParentData.offset.dy > 0.0) {
          // vertical alignment arrows
          double headSize = math.min(childParentData.offset.dy * 0.2, 10.0);
          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
          double headSize = math.min(childParentData.offset.dx * 0.2, 10.0);
          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()
          ..color = debugPaintSpacingColor;
        context.canvas.drawRect(offset & size, paint);
      }
      return true;
    });
  }

404
  @override
405 406
  void debugFillDescription(List<String> description) {
    super.debugFillDescription(description);
407 408
    description.add('widthFactor: ${_widthFactor ?? "expand"}');
    description.add('heightFactor: ${_heightFactor ?? "expand"}');
409
  }
410 411
}

412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
/// 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
/// of where it was rendered, you would wrap it in a RenderOverflow with
/// minHeight and maxHeight set to 50.0. Generally speaking, to avoid confusing
427
/// behavior around hit testing, a RenderOverflowBox should usually be wrapped
428 429 430 431 432
/// in a RenderClipRect.
///
/// The child is positioned at the top left of the box. To position a smaller
/// child inside a larger parent, use [RenderPositionedBox] and
/// [RenderConstrainedBox] rather than RenderOverflowBox.
433
class RenderConstrainedOverflowBox extends RenderAligningShiftedBox {
434
  /// Creates a render object that lets its child overflow itself.
435
  RenderConstrainedOverflowBox({
436 437 438 439 440
    RenderBox child,
    double minWidth,
    double maxWidth,
    double minHeight,
    double maxHeight,
Adam Barth's avatar
Adam Barth committed
441
    FractionalOffset alignment: FractionalOffset.center
442 443 444 445
  }) : _minWidth = minWidth,
       _maxWidth = maxWidth,
       _minHeight = minHeight,
       _maxHeight = maxHeight,
446
       super(child: child, alignment: alignment);
447 448 449 450 451

  /// 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;
452
  set minWidth (double value) {
453 454 455 456 457 458 459 460 461 462
    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;
463
  set maxWidth (double value) {
464 465 466 467 468 469 470 471 472 473
    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;
474
  set minHeight (double value) {
475 476 477 478 479 480 481 482 483 484
    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;
485
  set maxHeight (double value) {
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
    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
    );
  }

501
  @override
502 503
  bool get sizedByParent => true;

504
  @override
505 506 507 508
  void performResize() {
    size = constraints.biggest;
  }

509
  @override
510 511 512
  void performLayout() {
    if (child != null) {
      child.layout(_getInnerConstraints(constraints), parentUsesSize: true);
513
      alignChild();
514 515 516
    }
  }

517
  @override
518 519 520 521 522 523
  void debugFillDescription(List<String> description) {
    super.debugFillDescription(description);
    description.add('minWidth: ${minWidth ?? "use parent minWidth constraint"}');
    description.add('maxWidth: ${maxWidth ?? "use parent maxWidth constraint"}');
    description.add('minHeight: ${minHeight ?? "use parent minHeight constraint"}');
    description.add('maxHeight: ${maxHeight ?? "use parent maxHeight constraint"}');
524 525 526
  }
}

527
/// A render box that is a specific size but passes its original constraints
528 529
/// through to its child, which will probably overflow.
class RenderSizedOverflowBox extends RenderAligningShiftedBox {
530 531 532
  /// Creates a render box of a given size that lets its child overflow.
  ///
  /// The [requestedSize] argument must not be null.
533 534 535
  RenderSizedOverflowBox({
    RenderBox child,
    Size requestedSize,
Adam Barth's avatar
Adam Barth committed
536
    FractionalOffset alignment: FractionalOffset.center
537 538 539 540 541 542 543 544
  }) : _requestedSize = requestedSize,
       super(child: child, alignment: alignment) {
    assert(requestedSize != null);
  }

  /// The size this render box should attempt to be.
  Size get requestedSize => _requestedSize;
  Size _requestedSize;
545
  set requestedSize (Size value) {
546 547 548 549 550 551 552 553
    assert(value != null);
    if (_requestedSize == value)
      return;
    _requestedSize = value;
    markNeedsLayout();
  }

  @override
554
  double computeMinIntrinsicWidth(double height) {
555
    return _requestedSize.width;
556 557 558
  }

  @override
559
  double computeMaxIntrinsicWidth(double height) {
560
    return _requestedSize.width;
561 562 563
  }

  @override
564
  double computeMinIntrinsicHeight(double width) {
565
    return _requestedSize.height;
566 567 568
  }

  @override
569
  double computeMaxIntrinsicHeight(double width) {
570
    return _requestedSize.height;
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
  }

  @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 {
600 601 602 603
  /// 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.
604 605 606 607
  RenderFractionallySizedOverflowBox({
    RenderBox child,
    double widthFactor,
    double heightFactor,
Adam Barth's avatar
Adam Barth committed
608
    FractionalOffset alignment: FractionalOffset.center
609 610 611 612 613 614 615 616 617 618 619
  }) : _widthFactor = widthFactor,
       _heightFactor = heightFactor,
       super(child: child, alignment: alignment) {
    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
  /// incoming width constraint multipled by this factor.  If null, the child is
620
  /// given the incoming width constraints.
621 622
  double get widthFactor => _widthFactor;
  double _widthFactor;
623
  set widthFactor (double value) {
624 625 626 627 628 629 630 631 632 633 634
    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
  /// incoming width constraint multipled by this factor.  If null, the child is
635
  /// given the incoming width constraints.
636 637
  double get heightFactor => _heightFactor;
  double _heightFactor;
638
  set heightFactor (double value) {
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
    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) {
      double width = maxWidth * _widthFactor;
      minWidth = width;
      maxWidth = width;
    }
    double minHeight = constraints.minHeight;
    double maxHeight = constraints.maxHeight;
    if (_heightFactor != null) {
      double height = maxHeight * _heightFactor;
      minHeight = height;
      maxHeight = height;
    }
    return new BoxConstraints(
      minWidth: minWidth,
      maxWidth: maxWidth,
      minHeight: minHeight,
      maxHeight: maxHeight
    );
  }

  @override
670
  double computeMinIntrinsicWidth(double height) {
671 672
    double result;
    if (child == null) {
673
      result = super.computeMinIntrinsicWidth(height);
674 675 676 677 678
    } else { // the following line relies on double.INFINITY absorption
      result = child.getMinIntrinsicWidth(height * (_heightFactor ?? 1.0));
    }
    assert(result.isFinite);
    return result / (_widthFactor ?? 1.0);
679 680 681
  }

  @override
682
  double computeMaxIntrinsicWidth(double height) {
683 684
    double result;
    if (child == null) {
685
      result = super.computeMaxIntrinsicWidth(height);
686 687 688 689 690
    } else { // the following line relies on double.INFINITY absorption
      result = child.getMaxIntrinsicWidth(height * (_heightFactor ?? 1.0));
    }
    assert(result.isFinite);
    return result / (_widthFactor ?? 1.0);
691 692 693
  }

  @override
694
  double computeMinIntrinsicHeight(double width) {
695 696
    double result;
    if (child == null) {
697
      result = super.computeMinIntrinsicHeight(width);
698 699 700 701 702
    } else { // the following line relies on double.INFINITY absorption
      result = child.getMinIntrinsicHeight(width * (_widthFactor ?? 1.0));
    }
    assert(result.isFinite);
    return result / (_heightFactor ?? 1.0);
703 704 705
  }

  @override
706
  double computeMaxIntrinsicHeight(double width) {
707 708
    double result;
    if (child == null) {
709
      result = super.computeMaxIntrinsicHeight(width);
710 711 712 713 714
    } else { // the following line relies on double.INFINITY absorption
      result = child.getMaxIntrinsicHeight(width * (_widthFactor ?? 1.0));
    }
    assert(result.isFinite);
    return result / (_heightFactor ?? 1.0);
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
  }

  @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
  void debugFillDescription(List<String> description) {
    super.debugFillDescription(description);
    description.add('widthFactor: ${_widthFactor ?? "pass-through"}');
    description.add('heightFactor: ${_heightFactor ?? "pass-through"}');
733 734 735
  }
}

Adam Barth's avatar
Adam Barth committed
736
/// A delegate for computing the layout of a render object with a single child.
737
class SingleChildLayoutDelegate {
738
  /// Returns the size of this object given the incoming constraints.
Adam Barth's avatar
Adam Barth committed
739 740
  Size getSize(BoxConstraints constraints) => constraints.biggest;

741
  /// Returns the box constraints for the child given the incoming constraints.
Adam Barth's avatar
Adam Barth committed
742 743 744
  BoxConstraints getConstraintsForChild(BoxConstraints constraints) => constraints;

  /// Returns the position where the child should be placed given the size of this object and the size of the child.
745
  Offset getPositionForChild(Size size, Size childSize) => Offset.zero;
746 747

  /// Override this method to return true when the child needs to be laid out.
748
  bool shouldRelayout(SingleChildLayoutDelegate oldDelegate) => true;
Adam Barth's avatar
Adam Barth committed
749 750
}

751 752 753 754 755 756
/// 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.
757
class RenderCustomSingleChildLayoutBox extends RenderShiftedBox {
758 759 760
  /// Creates a render box that defers its layout to a delgate.
  ///
  /// The [delegate] argument must not be null.
761
  RenderCustomSingleChildLayoutBox({
Adam Barth's avatar
Adam Barth committed
762
    RenderBox child,
763
    SingleChildLayoutDelegate delegate
Adam Barth's avatar
Adam Barth committed
764 765 766 767
  }) : _delegate = delegate, super(child) {
    assert(delegate != null);
  }

768
  /// A delegate that controls this object's layout.
769 770
  SingleChildLayoutDelegate get delegate => _delegate;
  SingleChildLayoutDelegate _delegate;
771
  set delegate (SingleChildLayoutDelegate newDelegate) {
Adam Barth's avatar
Adam Barth committed
772 773 774
    assert(newDelegate != null);
    if (_delegate == newDelegate)
      return;
775 776
    if (newDelegate.runtimeType != _delegate.runtimeType || newDelegate.shouldRelayout(_delegate))
      markNeedsLayout();
Adam Barth's avatar
Adam Barth committed
777 778 779 780 781 782 783
    _delegate = newDelegate;
  }

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

784 785 786 787
  // 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.

788
  @override
789
  double computeMinIntrinsicWidth(double height) {
790 791 792 793
    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
794 795
  }

796
  @override
797
  double computeMaxIntrinsicWidth(double height) {
798 799 800 801
    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
802 803
  }

804
  @override
805
  double computeMinIntrinsicHeight(double width) {
806 807 808 809
    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
810 811
  }

812
  @override
813
  double computeMaxIntrinsicHeight(double width) {
814 815 816 817
    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
818 819
  }

820
  @override
Adam Barth's avatar
Adam Barth committed
821 822
  bool get sizedByParent => true;

823
  @override
Adam Barth's avatar
Adam Barth committed
824 825 826 827
  void performResize() {
    size = _getSize(constraints);
  }

828
  @override
Adam Barth's avatar
Adam Barth committed
829 830
  void performLayout() {
    if (child != null) {
831
      BoxConstraints childConstraints = delegate.getConstraintsForChild(constraints);
832
      assert(childConstraints.debugAssertIsValid(isAppliedConstraint: true));
833
      child.layout(childConstraints, parentUsesSize: !childConstraints.isTight);
Adam Barth's avatar
Adam Barth committed
834
      final BoxParentData childParentData = child.parentData;
835
      childParentData.offset = delegate.getPositionForChild(size, childConstraints.isTight ? childConstraints.smallest : child.size);
Adam Barth's avatar
Adam Barth committed
836 837 838 839
    }
  }
}

840 841 842
/// 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
843 844 845 846 847 848 849 850 851 852 853 854 855
/// 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
/// of the box. This is typically not desireable, in particular, that
/// 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.
856
class RenderBaseline extends RenderShiftedBox {
857 858
  /// Creates a [RenderBaseline] object.
  ///
859
  /// The [baseline] and [baselineType] arguments must not be null.
860 861 862 863 864 865 866 867 868 869 870
  RenderBaseline({
    RenderBox child,
    double baseline,
    TextBaseline baselineType
  }) : _baseline = baseline,
       _baselineType = baselineType,
       super(child) {
    assert(baseline != null);
    assert(baselineType != null);
  }

871 872
  /// The number of logical pixels from the top of this box at which to position
  /// the child's baseline.
873
  double get baseline => _baseline;
874
  double _baseline;
875
  set baseline (double value) {
876 877 878 879 880 881 882
    assert(value != null);
    if (_baseline == value)
      return;
    _baseline = value;
    markNeedsLayout();
  }

883
  /// The type of baseline to use for positioning the child.
884
  TextBaseline get baselineType => _baselineType;
885
  TextBaseline _baselineType;
886
  set baselineType (TextBaseline value) {
887 888 889 890 891 892 893
    assert(value != null);
    if (_baselineType == value)
      return;
    _baselineType = value;
    markNeedsLayout();
  }

894
  @override
895 896 897
  void performLayout() {
    if (child != null) {
      child.layout(constraints.loosen(), parentUsesSize: true);
898
      final double childBaseline = child.getDistanceToBaseline(baselineType);
899
      final double actualBaseline = baseline;
900
      final double top = actualBaseline - childBaseline;
Hixie's avatar
Hixie committed
901
      final BoxParentData childParentData = child.parentData;
902 903 904
      childParentData.offset = new Offset(0.0, top);
      final Size childSize = child.size;
      size = constraints.constrain(new Size(childSize.width, top + childSize.height));
905 906 907 908 909
    } else {
      performResize();
    }
  }

910
  @override
911 912 913 914
  void debugFillDescription(List<String> description) {
    super.debugFillDescription(description);
    description.add('baseline: $baseline');
    description.add('baselineType: $baselineType');
915
  }
916
}