box.dart 36.9 KB
Newer Older
1 2 3 4 5
// 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.

import 'dart:math' as math;
6
import 'dart:ui' as ui show lerpDouble;
7

8
import 'package:flutter/animation.dart';
9
import 'package:flutter/gestures.dart';
10
import 'package:vector_math/vector_math_64.dart';
11

12 13 14
import 'debug.dart';
import 'object.dart';

15 16 17 18 19 20 21
// This class should only be used in debug builds
class _DebugSize extends Size {
  _DebugSize(Size source, this._owner, this._canBeUsedByParent): super.copy(source);
  final RenderBox _owner;
  final bool _canBeUsedByParent;
}

22 23 24 25 26 27 28 29 30
/// The two cardinal directions in two dimensions.
enum Axis {
  /// Left and right
  horizontal,

  /// Up and down
  vertical,
}

31
/// Immutable layout constraints for box layout.
32 33 34 35
///
/// A size respects a BoxConstraints if, and only if, all of the following
/// relations hold:
///
36
/// * `minWidth <= size.width <= maxWidth`
37 38 39 40 41 42 43 44
/// * `minHeight <= size.height <= maxHeight`
///
/// The constraints themselves must satisfy these relations:
///
/// * `0.0 <= minWidth <= maxWidth <= double.INFINITY`
/// * `0.0 <= minHeight <= maxHeight <= double.INFINITY`
///
/// Note: `double.INFINITY` is a legal value for each constraint.
45
class BoxConstraints extends Constraints {
46
  /// Constructs box constraints with the given constraints
47 48 49 50 51 52 53
  const BoxConstraints({
    this.minWidth: 0.0,
    this.maxWidth: double.INFINITY,
    this.minHeight: 0.0,
    this.maxHeight: double.INFINITY
  });

54 55 56 57 58
  final double minWidth;
  final double maxWidth;
  final double minHeight;
  final double maxHeight;

59
  /// Constructs box constraints that is respected only by the given size.
60 61 62 63 64 65
  BoxConstraints.tight(Size size)
    : minWidth = size.width,
      maxWidth = size.width,
      minHeight = size.height,
      maxHeight = size.height;

66
  /// Constructs box constraints that require the given width or height.
67 68 69 70 71 72 73 74
  const BoxConstraints.tightFor({
    double width,
    double height
  }): minWidth = width != null ? width : 0.0,
      maxWidth = width != null ? width : double.INFINITY,
      minHeight = height != null ? height : 0.0,
      maxHeight = height != null ? height : double.INFINITY;

75
  /// Constructs box constraints that forbid sizes larger than the given size.
76 77 78 79 80 81
  BoxConstraints.loose(Size size)
    : minWidth = 0.0,
      maxWidth = size.width,
      minHeight = 0.0,
      maxHeight = size.height;

82
  /// Constructs box constraints that expand to fill another box contraints.
83 84 85 86 87 88 89 90 91 92
  ///
  /// If width or height is given, the constraints will require exactly the
  /// given value in the given dimension.
  const BoxConstraints.expand({
    double width,
    double height
  }): minWidth = width != null ? width : double.INFINITY,
      maxWidth = width != null ? width : double.INFINITY,
      minHeight = height != null ? height : double.INFINITY,
      maxHeight = height != null ? height : double.INFINITY;
93

Hixie's avatar
Hixie committed
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
  /// Returns new box constraints that remove the minimum width and height requirements.
  BoxConstraints copyWith({
    double minWidth,
    double maxWidth,
    double minHeight,
    double maxHeight
  }) {
    return new BoxConstraints(
      minWidth: minWidth ?? this.minWidth,
      maxWidth: maxWidth ?? this.maxWidth,
      minHeight: minHeight ?? this.minHeight,
      maxHeight: maxHeight ?? this.maxHeight
    );
  }

109
  /// Returns new box constraints that are smaller by the given edge dimensions.
110 111
  BoxConstraints deflate(EdgeDims edges) {
    assert(edges != null);
112
    assert(debugAssertIsNormalized);
113 114
    double horizontal = edges.left + edges.right;
    double vertical = edges.top + edges.bottom;
115 116
    double deflatedMinWidth = math.max(0.0, minWidth - horizontal);
    double deflatedMinHeight = math.max(0.0, minHeight - vertical);
117
    return new BoxConstraints(
118 119 120 121
      minWidth: deflatedMinWidth,
      maxWidth: math.max(deflatedMinWidth, maxWidth - horizontal),
      minHeight: deflatedMinHeight,
      maxHeight: math.max(deflatedMinHeight, maxHeight - vertical)
122 123 124
    );
  }

125
  /// Returns new box constraints that remove the minimum width and height requirements.
126
  BoxConstraints loosen() {
127
    assert(debugAssertIsNormalized);
128 129 130 131 132 133 134 135
    return new BoxConstraints(
      minWidth: 0.0,
      maxWidth: maxWidth,
      minHeight: 0.0,
      maxHeight: maxHeight
    );
  }

136 137
  /// Returns new box constraints that respect the given constraints while being
  /// as close as possible to the original constraints.
138
  BoxConstraints enforce(BoxConstraints constraints) {
139
    return new BoxConstraints(
140 141 142 143
      minWidth: minWidth.clamp(constraints.minWidth, constraints.maxWidth),
      maxWidth: maxWidth.clamp(constraints.minWidth, constraints.maxWidth),
      minHeight: minHeight.clamp(constraints.minHeight, constraints.maxHeight),
      maxHeight: maxHeight.clamp(constraints.minHeight, constraints.maxHeight)
144 145 146
    );
  }

147 148 149 150
  /// Returns new box constraints with a tight width and/or height as close to
  /// the given width and height as possible while still respecting the original
  /// box constraints.
  BoxConstraints tighten({ double width, double height }) {
151 152 153 154
    return new BoxConstraints(minWidth: width == null ? minWidth : width.clamp(minWidth, maxWidth),
                              maxWidth: width == null ? maxWidth : width.clamp(minWidth, maxWidth),
                              minHeight: height == null ? minHeight : height.clamp(minHeight, maxHeight),
                              maxHeight: height == null ? maxHeight : height.clamp(minHeight, maxHeight));
155 156
  }

157 158
  /// Returns box constraints with the same width constraints but with
  /// unconstrainted height.
159 160
  BoxConstraints widthConstraints() => new BoxConstraints(minWidth: minWidth, maxWidth: maxWidth);

161 162
  /// Returns box constraints with the same height constraints but with
  /// unconstrainted width
163 164
  BoxConstraints heightConstraints() => new BoxConstraints(minHeight: minHeight, maxHeight: maxHeight);

165 166
  /// Returns the width that both satisfies the constraints and is as close as
  /// possible to the given width.
167
  double constrainWidth([double width = double.INFINITY]) {
168
    assert(debugAssertIsNormalized);
169
    return width.clamp(minWidth, maxWidth);
170 171
  }

172 173
  /// Returns the height that both satisfies the constraints and is as close as
  /// possible to the given height.
174
  double constrainHeight([double height = double.INFINITY]) {
175
    assert(debugAssertIsNormalized);
176
    return height.clamp(minHeight, maxHeight);
177 178
  }

179 180
  /// Returns the size that both satisfies the constraints and is as close as
  /// possible to the given size.
181 182
  Size constrain(Size size) {
    Size result = new Size(constrainWidth(size.width), constrainHeight(size.height));
183 184 185 186 187
    assert(() {
      if (size is _DebugSize)
        result = new _DebugSize(result, size._owner, size._canBeUsedByParent);
      return true;
    });
188 189
    return result;
  }
190

191
  /// The biggest size that satisifes the constraints.
192 193
  Size get biggest => new Size(constrainWidth(), constrainHeight());

194
  /// The smallest size that satisfies the constraints.
195
  Size get smallest => new Size(constrainWidth(0.0), constrainHeight(0.0));
196

197
  /// Whether there is exactly one width value that satisfies the constraints.
198
  bool get hasTightWidth => minWidth >= maxWidth;
199

200
  /// Whether there is exactly one height value that satisfies the constraints.
201
  bool get hasTightHeight => minHeight >= maxHeight;
202

203
  /// Whether there is exactly one size that satifies the constraints.
204 205
  bool get isTight => hasTightWidth && hasTightHeight;

206 207 208 209 210 211
  /// Whether there is an upper bound on the maximum width.
  bool get hasBoundedWidth => maxWidth < double.INFINITY;

  /// Whether there is an upper bound on the maximum height.
  bool get hasBoundedHeight => maxHeight < double.INFINITY;

212
  /// Whether the given size satisfies the constraints.
213
  bool isSatisfiedBy(Size size) {
214
    assert(debugAssertIsNormalized);
215 216
    return (minWidth <= size.width) && (size.width <= maxWidth) &&
           (minHeight <= size.height) && (size.height <= maxHeight);
217 218
  }

Adam Barth's avatar
Adam Barth committed
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
  BoxConstraints operator*(double other) {
    return new BoxConstraints(
      minWidth: minWidth * other,
      maxWidth: maxWidth * other,
      minHeight: minHeight * other,
      maxHeight: maxHeight * other
    );
  }

  BoxConstraints operator/(double other) {
    return new BoxConstraints(
      minWidth: minWidth / other,
      maxWidth: maxWidth / other,
      minHeight: minHeight / other,
      maxHeight: maxHeight / other
    );
  }

  BoxConstraints operator~/(double other) {
    return new BoxConstraints(
      minWidth: (minWidth ~/ other).toDouble(),
      maxWidth: (maxWidth ~/ other).toDouble(),
      minHeight: (minHeight ~/ other).toDouble(),
      maxHeight: (maxHeight ~/ other).toDouble()
    );
  }

  BoxConstraints operator%(double other) {
    return new BoxConstraints(
      minWidth: minWidth % other,
      maxWidth: maxWidth % other,
      minHeight: minHeight % other,
      maxHeight: maxHeight % other
    );
  }

255
  /// Linearly interpolate between two BoxConstraints.
Adam Barth's avatar
Adam Barth committed
256 257 258 259 260 261 262 263 264
  ///
  /// If either is null, this function interpolates from [BoxConstraints.zero].
  static BoxConstraints lerp(BoxConstraints a, BoxConstraints b, double t) {
    if (a == null && b == null)
      return null;
    if (a == null)
      return b * t;
    if (b == null)
      return a * (1.0 - t);
265 266
    assert(a.debugAssertIsNormalized);
    assert(b.debugAssertIsNormalized);
Adam Barth's avatar
Adam Barth committed
267
    return new BoxConstraints(
268 269 270 271
      minWidth: ui.lerpDouble(a.minWidth, b.minWidth, t),
      maxWidth: ui.lerpDouble(a.maxWidth, b.maxWidth, t),
      minHeight: ui.lerpDouble(a.minHeight, b.minHeight, t),
      maxHeight: ui.lerpDouble(a.maxHeight, b.maxHeight, t)
Adam Barth's avatar
Adam Barth committed
272 273 274
    );
  }

275 276 277 278 279 280 281 282 283 284 285
  /// Returns whether the object's constraints are normalized.
  /// Constraints are normalised if the minimums are less than or
  /// equal to the corresponding maximums.
  ///
  /// For example, a BoxConstraints object with a minWidth of 100.0
  /// and a maxWidth of 90.0 is not normalized.
  ///
  /// Most of the APIs on BoxConstraints expect the constraints to be
  /// normalized and have undefined behavior when they are not. In
  /// checked mode, many of these APIs will assert if the constraints
  /// are not normalized.
286 287 288 289 290 291
  bool get isNormalized {
    return minWidth >= 0.0 &&
           minWidth <= maxWidth &&
           minHeight >= 0.0 &&
           minHeight <= maxHeight;
  }
292

293 294
  bool get debugAssertIsNormalized {
    assert(() {
295 296 297 298 299 300
      if (minWidth < 0.0 && minHeight < 0.0)
        throw new RenderingError('BoxConstraints has both a negative minimum width and a negative minimum height.\n$this');
      if (minWidth < 0.0)
        throw new RenderingError('BoxConstraints has a negative minimum width.\n$this');
      if (minHeight < 0.0)
        throw new RenderingError('BoxConstraints has a negative minimum height.\n$this');
301 302 303 304 305 306 307 308 309 310 311
      if (maxWidth < minWidth && maxHeight < minHeight)
        throw new RenderingError('BoxConstraints has both width and height constraints non-normalized.\n$this');
      if (maxWidth < minWidth)
        throw new RenderingError('BoxConstraints has non-normalized width constraints.\n$this');
      if (maxHeight < minHeight)
        throw new RenderingError('BoxConstraints has non-normalized height constraints.\n$this');
      return isNormalized;
    });
    return isNormalized;
  }

312 313 314 315 316 317 318 319 320
  BoxConstraints normalize() {
    return new BoxConstraints(
      minWidth: minWidth,
      maxWidth: minWidth > maxWidth ? minWidth : maxWidth,
      minHeight: minHeight,
      maxHeight: minHeight > maxHeight ? minHeight : maxHeight
    );
  }

Hixie's avatar
Hixie committed
321
  bool operator ==(dynamic other) {
322
    assert(debugAssertIsNormalized);
323 324
    if (identical(this, other))
      return true;
Hixie's avatar
Hixie committed
325 326 327
    if (other is! BoxConstraints)
      return false;
    final BoxConstraints typedOther = other;
328
    assert(typedOther.debugAssertIsNormalized);
Hixie's avatar
Hixie committed
329 330 331 332
    return minWidth == typedOther.minWidth &&
           maxWidth == typedOther.maxWidth &&
           minHeight == typedOther.minHeight &&
           maxHeight == typedOther.maxHeight;
333
  }
Hixie's avatar
Hixie committed
334

335
  int get hashCode {
336
    assert(debugAssertIsNormalized);
337
    return hashValues(minWidth, maxWidth, minHeight, maxHeight);
338 339
  }

Hixie's avatar
Hixie committed
340
  String toString() {
341
    String annotation = isNormalized ? '' : '; NOT NORMALIZED';
Hixie's avatar
Hixie committed
342
    if (minWidth == double.INFINITY && minHeight == double.INFINITY)
343
      return 'BoxConstraints(biggest$annotation)';
Hixie's avatar
Hixie committed
344 345
    if (minWidth == 0 && maxWidth == double.INFINITY &&
        minHeight == 0 && maxHeight == double.INFINITY)
346
      return 'BoxConstraints(unconstrained$annotation)';
Hixie's avatar
Hixie committed
347 348 349 350 351 352 353
    String describe(double min, double max, String dim) {
      if (min == max)
        return '$dim=${min.toStringAsFixed(1)}';
      return '${min.toStringAsFixed(1)}<=$dim<=${max.toStringAsFixed(1)}';
    }
    final String width = describe(minWidth, maxWidth, 'w');
    final String height = describe(minHeight, maxHeight, 'h');
354
    return 'BoxConstraints($width, $height$annotation)';
Hixie's avatar
Hixie committed
355
  }
356 357
}

358
/// A hit test entry used by [RenderBox].
359
class BoxHitTestEntry extends HitTestEntry {
Ian Hickson's avatar
Ian Hickson committed
360 361 362
  const BoxHitTestEntry(RenderBox target, this.localPosition) : super(target);

  RenderBox get target => super.target;
Adam Barth's avatar
Adam Barth committed
363

364
  /// The position of the hit test in the local coordinates of [target].
365
  final Point localPosition;
Ian Hickson's avatar
Ian Hickson committed
366 367

  String toString() => '${target.runtimeType}@$localPosition';
368 369
}

370
/// Parent data used by [RenderBox] and its subclasses.
371
class BoxParentData extends ParentData {
372 373 374 375
  /// The offset at which to paint the child in the parent's coordinate system
  Offset get offset => _offset;
  Offset _offset = Offset.zero;
  void set offset(Offset value) {
376
    assert(RenderObject.debugDoingLayout);
377
    _offset = value;
378
  }
379 380

  String toString() => 'offset=$offset';
381 382
}

Hixie's avatar
Hixie committed
383 384 385 386
/// Abstract ParentData subclass for RenderBox subclasses that want the
/// ContainerRenderObjectMixin.
abstract class ContainerBoxParentDataMixin<ChildType extends RenderObject> extends BoxParentData with ContainerParentDataMixin<ChildType> { }

387
/// A render object in a 2D cartesian coordinate system.
Adam Barth's avatar
Adam Barth committed
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
///
/// The size of each box is expressed as a width and a height. Each box has its
/// own coordinate system in which its upper left corner is placed at (0, 0).
/// The lower right corner of the box is therefore at (width, height). The box
/// contains all the points including the upper left corner and extending to,
/// but not including, the lower right corner.
///
/// Box layout is performed by passing a [BoxConstraints] object down the tree.
/// The box constraints establish a min and max value for the child's width
/// and height. In determining its size, the child must respect the constraints
/// given to it by its parent.
///
/// This protocol is sufficient for expressing a number of common box layout
/// data flows.  For example, to implement a width-in-height-out data flow, call
/// your child's [layout] function with a set of box constraints with a tight
/// width value (and pass true for parentUsesSize). After the child determines
/// its height, use the child's height to determine your size.
405 406 407 408 409 410 411
abstract class RenderBox extends RenderObject {

  void setupParentData(RenderObject child) {
    if (child.parentData is! BoxParentData)
      child.parentData = new BoxParentData();
  }

Adam Barth's avatar
Adam Barth committed
412
  /// Returns the minimum width that this box could be without failing to paint
413
  /// its contents within itself.
Adam Barth's avatar
Adam Barth committed
414 415
  ///
  /// Override in subclasses that implement [performLayout].
416
  double getMinIntrinsicWidth(BoxConstraints constraints) {
417
    assert(constraints.debugAssertIsNormalized);
418 419 420
    return constraints.constrainWidth(0.0);
  }

Adam Barth's avatar
Adam Barth committed
421
  /// Returns the smallest width beyond which increasing the width never
422
  /// decreases the height.
Adam Barth's avatar
Adam Barth committed
423 424
  ///
  /// Override in subclasses that implement [performLayout].
425
  double getMaxIntrinsicWidth(BoxConstraints constraints) {
426
    assert(constraints.debugAssertIsNormalized);
427 428 429
    return constraints.constrainWidth(0.0);
  }

Adam Barth's avatar
Adam Barth committed
430
  /// Return the minimum height that this box could be without failing to paint
Adam Barth's avatar
Adam Barth committed
431 432 433
  /// its contents within itself.
  ///
  /// Override in subclasses that implement [performLayout].
434
  double getMinIntrinsicHeight(BoxConstraints constraints) {
435
    assert(constraints.debugAssertIsNormalized);
436 437 438
    return constraints.constrainHeight(0.0);
  }

Adam Barth's avatar
Adam Barth committed
439 440 441 442 443 444 445 446
  /// Returns the smallest height beyond which increasing the height never
  /// decreases the width.
  ///
  /// If the layout algorithm used is width-in-height-out, i.e. the height
  /// depends on the width and not vice versa, then this will return the same
  /// as getMinIntrinsicHeight().
  ///
  /// Override in subclasses that implement [performLayout].
447
  double getMaxIntrinsicHeight(BoxConstraints constraints) {
448
    assert(constraints.debugAssertIsNormalized);
449 450 451
    return constraints.constrainHeight(0.0);
  }

452
  /// The size of this render box computed during layout.
453 454 455 456 457 458 459 460 461 462 463 464 465
  ///
  /// This value is stale whenever this object is marked as needing layout.
  /// During [performLayout], do not read the size of a child unless you pass
  /// true for parentUsesSize when calling the child's [layout] function.
  ///
  /// The size of a box should be set only during the box's [performLayout] or
  /// [performResize] functions. If you wish to change the size of a box outside
  /// of those functins, call [markNeedsLayout] instead to schedule a layout of
  /// the box.
  Size get size {
    assert(hasSize);
    assert(() {
      if (_size is _DebugSize) {
Hixie's avatar
Hixie committed
466
        final _DebugSize _size = this._size;
467 468
        assert(_size._owner == this);
        if (RenderObject.debugActiveLayout != null) {
469 470 471 472 473
          // We are always allowed to access our own size (for print debugging
          // and asserts if nothing else). Other than us, the only object that's
          // allowed to read our size is our parent, if they've said they will.
          // If you hit this assert trying to access a child's size, pass
          // "parentUsesSize: true" to that child's layout().
474 475 476
          assert(debugDoingThisResize || debugDoingThisLayout ||
                 (RenderObject.debugActiveLayout == parent && _size._canBeUsedByParent));
        }
Hixie's avatar
Hixie committed
477
        assert(_size == this._size);
478 479 480 481 482 483 484 485 486 487 488
      }
      return true;
    });
    return _size;
  }
  bool get hasSize => _size != null;
  Size _size;
  void set size(Size value) {
    assert((sizedByParent && debugDoingThisResize) ||
           (!sizedByParent && debugDoingThisLayout));
    assert(() {
489 490 491 492 493 494
      if (value is _DebugSize) {
        if (value._owner != this) {
          assert(value._owner.parent == this);
          assert(value._canBeUsedByParent);
        }
      }
495 496 497 498 499 500 501
      return true;
    });
    _size = value;
    assert(() {
      _size = new _DebugSize(_size, this, debugCanParentUseSize);
      return true;
    });
502
    assert(() { debugAssertDoesMeetConstraints(); return true; });
503 504
  }

Hixie's avatar
Hixie committed
505 506
  Rect get semanticBounds => Point.origin & size;

507 508 509 510 511
  void debugResetSize() {
    // updates the value of size._canBeUsedByParent if necessary
    size = size;
  }

512 513 514 515 516 517 518
  Map<TextBaseline, double> _cachedBaselines;
  bool _ancestorUsesBaseline = false;
  static bool _debugDoingBaseline = false;
  static bool _debugSetDoingBaseline(bool value) {
    _debugDoingBaseline = value;
    return true;
  }
Adam Barth's avatar
Adam Barth committed
519 520 521 522 523 524 525 526 527 528 529 530 531 532

  /// Returns the distance from the y-coordinate of the position of the box to
  /// the y-coordinate of the first given baseline in the box's contents.
  ///
  /// Used by certain layout models to align adjacent boxes on a common
  /// baseline, regardless of padding, font size differences, etc. If there is
  /// no baseline, this function returns the distance from the y-coordinate of
  /// the position of the box to the y-coordinate of the bottom of the box
  /// (i.e., the height of the box) unless the the caller passes true
  /// for `onlyReal`, in which case the function returns null.
  ///
  /// Only call this function calling [layout] on this box. You are only
  /// allowed to call this from the parent of this box during that parent's
  /// [performLayout] or [paint] functions.
533 534 535
  double getDistanceToBaseline(TextBaseline baseline, { bool onlyReal: false }) {
    assert(!needsLayout);
    assert(!_debugDoingBaseline);
Hixie's avatar
Hixie committed
536
    final RenderObject parent = this.parent;
537 538 539 540 541 542 543 544 545 546 547
    assert(() {
      if (RenderObject.debugDoingLayout)
        return (RenderObject.debugActiveLayout == parent) && parent.debugDoingThisLayout;
      if (RenderObject.debugDoingPaint)
        return ((RenderObject.debugActivePaint == parent) && parent.debugDoingThisPaint) ||
               ((RenderObject.debugActivePaint == this) && debugDoingThisPaint);
      return false;
    });
    assert(_debugSetDoingBaseline(true));
    double result = getDistanceToActualBaseline(baseline);
    assert(_debugSetDoingBaseline(false));
Hixie's avatar
Hixie committed
548
    assert(parent == this.parent);
549 550 551 552
    if (result == null && !onlyReal)
      return size.height;
    return result;
  }
Adam Barth's avatar
Adam Barth committed
553 554 555 556 557 558

  /// Calls [computeDistanceToActualBaseline] and caches the result.
  ///
  /// This function must only be called from [getDistanceToBaseline] and
  /// [computeDistanceToActualBaseline]. Do not call this function directly from
  /// outside those two methods.
559 560 561 562 563 564 565 566
  double getDistanceToActualBaseline(TextBaseline baseline) {
    assert(_debugDoingBaseline);
    _ancestorUsesBaseline = true;
    if (_cachedBaselines == null)
      _cachedBaselines = new Map<TextBaseline, double>();
    _cachedBaselines.putIfAbsent(baseline, () => computeDistanceToActualBaseline(baseline));
    return _cachedBaselines[baseline];
  }
Adam Barth's avatar
Adam Barth committed
567 568 569 570 571 572 573 574 575 576 577 578 579

  /// Returns the distance from the y-coordinate of the position of the box to
  /// the y-coordinate of the first given baseline in the box's contents, if
  /// any, or null otherwise.
  ///
  /// Do not call this function directly. Instead, call [getDistanceToBaseline]
  /// if you need to know the baseline of a child from an invocation of
  /// [performLayout] or [paint] and call [getDistanceToActualBaseline] if you
  /// are implementing [computeDistanceToActualBaseline] and need to defer to a
  /// child.
  ///
  /// Subclasses should override this function to supply the distances to their
  /// baselines.
580 581 582 583 584
  double computeDistanceToActualBaseline(TextBaseline baseline) {
    assert(_debugDoingBaseline);
    return null;
  }

585
  /// The box constraints most recently received from the parent.
586
  BoxConstraints get constraints => super.constraints;
587
  void debugAssertDoesMeetConstraints() {
588 589
    assert(constraints != null);
    assert(_size != null);
590 591 592 593 594 595 596 597 598
    // verify that the size is not infinite
    if (_size.isInfinite) {
      StringBuffer information = new StringBuffer();
      if (!constraints.hasBoundedWidth) {
        RenderBox node = this;
        while (!node.constraints.hasBoundedWidth && node.parent is RenderBox)
          node = node.parent;
        information.writeln('The nearest ancestor providing an unbounded width constraint is:');
        information.writeln('  $node');
599 600 601
        List<String> description = <String>[];
        node.debugFillDescription(description);
        for (String line in description)
602 603 604 605 606 607 608 609
        information.writeln('  $line');
      }
      if (!constraints.hasBoundedHeight) {
        RenderBox node = this;
        while (!node.constraints.hasBoundedHeight && node.parent is RenderBox)
          node = node.parent;
        information.writeln('The nearest ancestor providing an unbounded height constraint is:');
        information.writeln('  $node');
610 611 612
        List<String> description = <String>[];
        node.debugFillDescription(description);
        for (String line in description)
613 614 615 616 617 618 619 620 621 622 623
        information.writeln('  $line');
      }
      throw new RenderingError(
        '$runtimeType object was given an infinite size during layout.\n'
        'This probably means that it is a render object that tries to be\n'
        'as big as possible, but it was put inside another render object\n'
        'that allows its children to pick their own size.\n'
        '$information'
        'See https://flutter.io/layout/ for more information.'
      );
    }
624
    // verify that the size is within the constraints
625 626 627 628 629 630 631 632 633
    if (!constraints.isSatisfiedBy(_size)) {
      throw new RenderingError(
        '$runtimeType does not meet its constraints.\n'
        'Constraints: $constraints\n'
        'Size: $_size\n'
        'If you are not writing your own RenderBox subclass, then this is not\n'
        'your fault. Contact support: https://github.com/flutter/flutter/issues/new'
      );
    }
634
    // verify that the intrinsics are also within the constraints
635 636
    assert(!RenderObject.debugCheckingIntrinsics);
    RenderObject.debugCheckingIntrinsics = true;
637
    double intrinsic;
638 639
    StringBuffer failures = new StringBuffer();
    int failureCount = 0;
640
    intrinsic = getMinIntrinsicWidth(constraints);
641 642 643 644
    if (intrinsic != constraints.constrainWidth(intrinsic)) {
      failures.writeln(' * getMinIntrinsicWidth() -- returned: w=$intrinsic');
      failureCount += 1;
    }
645
    intrinsic = getMaxIntrinsicWidth(constraints);
646 647 648 649
    if (intrinsic != constraints.constrainWidth(intrinsic)) {
      failures.writeln(' * getMaxIntrinsicWidth() -- returned: w=$intrinsic');
      failureCount += 1;
    }
650
    intrinsic = getMinIntrinsicHeight(constraints);
651 652 653 654
    if (intrinsic != constraints.constrainHeight(intrinsic)) {
      failures.writeln(' * getMinIntrinsicHeight() -- returned: h=$intrinsic');
      failureCount += 1;
    }
655
    intrinsic = getMaxIntrinsicHeight(constraints);
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
    if (intrinsic != constraints.constrainHeight(intrinsic)) {
      failures.writeln(' * getMaxIntrinsicHeight() -- returned: h=$intrinsic');
      failureCount += 1;
    }
    RenderObject.debugCheckingIntrinsics = false;
    if (failures.isNotEmpty) {
      assert(failureCount > 0);
      throw new RenderingError(
        'The intrinsic dimension methods of the $runtimeType class returned values that violate the given constraints.\n'
        'The constraints were: $constraints\n'
        'The following method${failureCount > 1 ? "s" : ""} returned values outside of those constraints:\n'
        '$failures'
        'If you are not writing your own RenderBox subclass, then this is not\n'
        'your fault. Contact support: https://github.com/flutter/flutter/issues/new'
      );
    }
672 673 674 675 676 677
  }

  void markNeedsLayout() {
    if (_cachedBaselines != null && _cachedBaselines.isNotEmpty) {
      // if we have cached data, then someone must have used our data
      assert(_ancestorUsesBaseline);
Hixie's avatar
Hixie committed
678
      final RenderObject parent = this.parent;
679
      parent.markNeedsLayout();
Hixie's avatar
Hixie committed
680
      assert(parent == this.parent);
681 682 683 684 685 686 687 688 689 690 691 692
      // Now that they're dirty, we can forget that they used the
      // baseline. If they use it again, then we'll set the bit
      // again, and if we get dirty again, we'll notify them again.
      _ancestorUsesBaseline = false;
      _cachedBaselines.clear();
    } else {
      // if we've never cached any data, then nobody can have used it
      assert(!_ancestorUsesBaseline);
    }
    super.markNeedsLayout();
  }
  void performResize() {
693
    // default behavior for subclasses that have sizedByParent = true
694 695 696 697
    size = constraints.constrain(Size.zero);
    assert(!size.isInfinite);
  }
  void performLayout() {
698 699 700 701 702 703 704 705 706
    assert(() {
      if (!sizedByParent) {
        debugPrint('$runtimeType needs to either override performLayout() to\n'
          'set size and lay out children, or, set sizedByParent to true\n'
          'so that performResize() sizes the render object.');
        assert(sizedByParent);
      }
      return true;
    });
707 708
  }

709
  /// Determines the set of render objects located at the given position.
Adam Barth's avatar
Adam Barth committed
710 711 712 713 714 715 716 717
  ///
  /// Returns true if the given point is contained in this render object or one
  /// of its descendants. Adds any render objects that contain the point to the
  /// given hit test result.
  ///
  /// The caller is responsible for transforming [position] into the local
  /// coordinate space of the callee.  The callee is responsible for checking
  /// whether the given position is within its bounds.
718
  bool hitTest(HitTestResult result, { Point position }) {
719
    assert(!needsLayout);
720
    assert(_size != null && 'Missing size. Did you set a size during layout?' != null);
721 722
    if (position.x >= 0.0 && position.x < _size.width &&
        position.y >= 0.0 && position.y < _size.height) {
Adam Barth's avatar
Adam Barth committed
723 724 725 726
      if (hitTestChildren(result, position: position) || hitTestSelf(position)) {
        result.add(new BoxHitTestEntry(this, position));
        return true;
      }
727 728
    }
    return false;
729
  }
Adam Barth's avatar
Adam Barth committed
730

Adam Barth's avatar
Adam Barth committed
731
  /// Override this function if this render object can be hit even if its
732
  /// children were not hit.
Adam Barth's avatar
Adam Barth committed
733 734
  bool hitTestSelf(Point position) => false;

Adam Barth's avatar
Adam Barth committed
735
  /// Override this function to check whether any children are located at the
736
  /// given position.
Adam Barth's avatar
Adam Barth committed
737 738 739 740
  ///
  /// Typically children should be hit tested in reverse paint order so that
  /// hit tests at locations where children overlap hit the child that is
  /// visually "on top" (i.e., paints later).
Adam Barth's avatar
Adam Barth committed
741
  bool hitTestChildren(HitTestResult result, { Point position }) => false;
742

Adam Barth's avatar
Adam Barth committed
743
  /// Multiply the transform from the parent's coordinate system to this box's
744
  /// coordinate system into the given transform.
Adam Barth's avatar
Adam Barth committed
745 746 747 748
  ///
  /// This function is used to convert coordinate systems between boxes.
  /// Subclasses that apply transforms during painting should override this
  /// function to factor those transforms into the calculation.
749 750 751 752 753 754
  ///
  /// The RenderBox implementation takes care of adjusting the matrix for the
  /// position of the given child.
  void applyPaintTransform(RenderObject child, Matrix4 transform) {
    assert(child.parent == this);
    BoxParentData childParentData = child.parentData;
755 756
    Offset offset = childParentData.offset;
    transform.translate(offset.dx, offset.dy);
757 758
  }

Adam Barth's avatar
Adam Barth committed
759
  /// Convert the given point from the global coodinate system to the local
760
  /// coordinate system for this box.
761 762 763
  ///
  /// If the transform from global coordinates to local coordinates is
  /// degenerate, this function returns Point.origin.
764 765 766 767
  Point globalToLocal(Point point) {
    assert(attached);
    Matrix4 transform = new Matrix4.identity();
    RenderObject renderer = this;
768 769 770 771
    while (renderer.parent is RenderObject) {
      RenderObject rendererParent = renderer.parent;
      rendererParent.applyPaintTransform(renderer, transform);
      renderer = rendererParent;
772
    }
773 774 775
    double det = transform.invert();
    if (det == 0.0)
      return Point.origin;
Hixie's avatar
Hixie committed
776
    return MatrixUtils.transformPoint(transform, point);
777 778
  }

779 780
  /// Convert the given point from the local coordinate system for this box to
  /// the global coordinate system.
781
  Point localToGlobal(Point point) {
782
    List<RenderObject> renderers = <RenderObject>[];
783 784 785
    for (RenderObject renderer = this; renderer != null; renderer = renderer.parent)
      renderers.add(renderer);
    Matrix4 transform = new Matrix4.identity();
786 787
    for (int index = renderers.length - 1; index > 0; index -= 1)
      renderers[index].applyPaintTransform(renderers[index - 1], transform);
Hixie's avatar
Hixie committed
788
    return MatrixUtils.transformPoint(transform, point);
789 790
  }

791
  /// Returns a rectangle that contains all the pixels painted by this box.
Adam Barth's avatar
Adam Barth committed
792 793 794 795 796 797 798 799 800 801 802 803
  ///
  /// The paint bounds can be larger or smaller than [size], which is the amount
  /// of space this box takes up during layout. For example, if this box casts a
  /// shadow, that shadow might extend beyond the space allocated to this box
  /// during layout.
  ///
  /// The paint bounds are used to size the buffers into which this box paints.
  /// If the box attempts to paints outside its paint bounds, there might not be
  /// enough memory allocated to represent the box's visual appearance, which
  /// can lead to undefined behavior.
  ///
  /// The returned paint bounds are in the local coordinate system of this box.
804
  Rect get paintBounds => Point.origin & size;
Adam Barth's avatar
Adam Barth committed
805

806
  int _debugActivePointers = 0;
Ian Hickson's avatar
Ian Hickson committed
807
  void handleEvent(PointerEvent event, HitTestEntry entry) {
808 809 810
    super.handleEvent(event, entry);
    assert(() {
      if (debugPaintPointersEnabled) {
Ian Hickson's avatar
Ian Hickson committed
811
        if (event is PointerDownEvent) {
812
          _debugActivePointers += 1;
Ian Hickson's avatar
Ian Hickson committed
813
        } else if (event is PointerUpEvent || event is PointerCancelEvent) {
814
          _debugActivePointers -= 1;
Ian Hickson's avatar
Ian Hickson committed
815
        }
816 817 818 819 820 821
        markNeedsPaint();
      }
      return true;
    });
  }

822
  void debugPaint(PaintingContext context, Offset offset) {
823 824 825 826 827 828 829 830 831
    assert(() {
      if (debugPaintSizeEnabled)
        debugPaintSize(context, offset);
      if (debugPaintBaselinesEnabled)
        debugPaintBaselines(context, offset);
      if (debugPaintPointersEnabled)
        debugPaintPointers(context, offset);
      return true;
    });
832
  }
833
  void debugPaintSize(PaintingContext context, Offset offset) {
834 835
    assert(() {
      Paint paint = new Paint()
836
       ..style = PaintingStyle.stroke
837 838 839 840 841
       ..strokeWidth = 1.0
       ..color = debugPaintSizeColor;
      context.canvas.drawRect((offset & size).deflate(0.5), paint);
      return true;
    });
842
  }
843
  void debugPaintBaselines(PaintingContext context, Offset offset) {
844 845
    assert(() {
      Paint paint = new Paint()
846
       ..style = PaintingStyle.stroke
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
       ..strokeWidth = 0.25;
      Path path;
      // ideographic baseline
      double baselineI = getDistanceToBaseline(TextBaseline.ideographic, onlyReal: true);
      if (baselineI != null) {
        paint.color = debugPaintIdeographicBaselineColor;
        path = new Path();
        path.moveTo(offset.dx, offset.dy + baselineI);
        path.lineTo(offset.dx + size.width, offset.dy + baselineI);
        context.canvas.drawPath(path, paint);
      }
      // alphabetic baseline
      double baselineA = getDistanceToBaseline(TextBaseline.alphabetic, onlyReal: true);
      if (baselineA != null) {
        paint.color = debugPaintAlphabeticBaselineColor;
        path = new Path();
        path.moveTo(offset.dx, offset.dy + baselineA);
        path.lineTo(offset.dx + size.width, offset.dy + baselineA);
        context.canvas.drawPath(path, paint);
      }
      return true;
    });
869
  }
870
  void debugPaintPointers(PaintingContext context, Offset offset) {
871 872 873 874 875 876 877 878
    assert(() {
      if (_debugActivePointers > 0) {
        Paint paint = new Paint()
         ..color = new Color(debugPaintPointersColorValue | ((0x04000000 * depth) & 0xFF000000));
        context.canvas.drawRect(offset & size, paint);
      }
      return true;
    });
879
  }
880

881 882 883
  void debugFillDescription(List<String> description) {
    super.debugFillDescription(description);
    description.add('size: ${ hasSize ? size : "MISSING" }');
884
  }
885 886
}

887 888
/// A mixin that provides useful default behaviors for boxes with children
/// managed by the [ContainerRenderObjectMixin] mixin.
Adam Barth's avatar
Adam Barth committed
889 890 891 892
///
/// By convention, this class doesn't override any members of the superclass.
/// Instead, it provides helpful functions that subclasses can call as
/// appropriate.
Hixie's avatar
Hixie committed
893
abstract class RenderBoxContainerDefaultsMixin<ChildType extends RenderBox, ParentDataType extends ContainerBoxParentDataMixin<ChildType>> implements ContainerRenderObjectMixin<ChildType, ParentDataType> {
894

895
  /// Returns the baseline of the first child with a baseline.
Adam Barth's avatar
Adam Barth committed
896 897 898
  ///
  /// Useful when the children are displayed vertically in the same order they
  /// appear in the child list.
899 900 901 902
  double defaultComputeDistanceToFirstActualBaseline(TextBaseline baseline) {
    assert(!needsLayout);
    RenderBox child = firstChild;
    while (child != null) {
Hixie's avatar
Hixie committed
903
      final ParentDataType childParentData = child.parentData;
904 905
      double result = child.getDistanceToActualBaseline(baseline);
      if (result != null)
906
        return result + childParentData.offset.dy;
Hixie's avatar
Hixie committed
907
      child = childParentData.nextSibling;
908 909 910 911
    }
    return null;
  }

912
  /// Returns the minimum baseline value among every child.
Adam Barth's avatar
Adam Barth committed
913 914 915
  ///
  /// Useful when the vertical position of the children isn't determined by the
  /// order in the child list.
916 917 918 919 920
  double defaultComputeDistanceToHighestActualBaseline(TextBaseline baseline) {
    assert(!needsLayout);
    double result;
    RenderBox child = firstChild;
    while (child != null) {
Hixie's avatar
Hixie committed
921
      final ParentDataType childParentData = child.parentData;
922 923
      double candidate = child.getDistanceToActualBaseline(baseline);
      if (candidate != null) {
924
        candidate += childParentData.offset.dy;
925 926 927 928 929
        if (result != null)
          result = math.min(result, candidate);
        else
          result = candidate;
      }
Hixie's avatar
Hixie committed
930
      child = childParentData.nextSibling;
931 932 933 934
    }
    return result;
  }

935
  /// Performs a hit test on each child by walking the child list backwards.
Adam Barth's avatar
Adam Barth committed
936 937 938
  ///
  /// Stops walking once after the first child reports that it contains the
  /// given point. Returns whether any children contain the given point.
939
  bool defaultHitTestChildren(HitTestResult result, { Point position }) {
940 941 942
    // the x, y parameters have the top left of the node's box as the origin
    ChildType child = lastChild;
    while (child != null) {
Hixie's avatar
Hixie committed
943
      final ParentDataType childParentData = child.parentData;
944 945
      Point transformed = new Point(position.x - childParentData.offset.dx,
                                    position.y - childParentData.offset.dy);
946
      if (child.hitTest(result, position: transformed))
947
        return true;
Hixie's avatar
Hixie committed
948
      child = childParentData.previousSibling;
949
    }
950
    return false;
951 952
  }

953
  /// Paints each child by walking the child list forwards.
954
  void defaultPaint(PaintingContext context, Offset offset) {
955 956
    RenderBox child = firstChild;
    while (child != null) {
Hixie's avatar
Hixie committed
957
      final ParentDataType childParentData = child.parentData;
Adam Barth's avatar
Adam Barth committed
958
      context.paintChild(child, childParentData.offset + offset);
Hixie's avatar
Hixie committed
959
      child = childParentData.nextSibling;
960 961 962
    }
  }
}
963

964 965
class FractionalOffsetTween extends Tween<FractionalOffset> {
  FractionalOffsetTween({ FractionalOffset begin, FractionalOffset end }) : super(begin: begin, end: end);
966 967 968

  FractionalOffset lerp(double t) => FractionalOffset.lerp(begin, end, t);
}