box.dart 30.1 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;
7

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

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

15
export 'package:flutter/painting.dart' show TextBaseline;
16 17 18 19 20 21 22 23

// 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;
}

24 25 26 27 28
/// Immutable layout constraints for box layout
///
/// A size respects a BoxConstraints if, and only if, all of the following
/// relations hold:
///
29
/// * `minWidth <= size.width <= maxWidth`
30 31 32 33 34 35 36 37
/// * `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.
38
class BoxConstraints extends Constraints {
39
  /// Constructs box constraints with the given constraints
40 41 42 43 44 45 46
  const BoxConstraints({
    this.minWidth: 0.0,
    this.maxWidth: double.INFINITY,
    this.minHeight: 0.0,
    this.maxHeight: double.INFINITY
  });

47 48 49 50 51 52
  final double minWidth;
  final double maxWidth;
  final double minHeight;
  final double maxHeight;

  /// Constructs box constraints that is respected only by the given size
53 54 55 56 57 58
  BoxConstraints.tight(Size size)
    : minWidth = size.width,
      maxWidth = size.width,
      minHeight = size.height,
      maxHeight = size.height;

59
  /// Constructs box constraints that require the given width or height
60 61 62 63 64 65 66 67
  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;

68
  /// Constructs box constraints that forbid sizes larger than the given size
69 70 71 72 73 74
  BoxConstraints.loose(Size size)
    : minWidth = 0.0,
      maxWidth = size.width,
      minHeight = 0.0,
      maxHeight = size.height;

75 76 77 78 79 80 81 82 83 84 85
  /// Constructs box constraints that expand to fill another box contraints
  ///
  /// 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;
86 87

  /// Returns new box constraints that are smaller by the given edge dimensions
88 89 90 91
  BoxConstraints deflate(EdgeDims edges) {
    assert(edges != null);
    double horizontal = edges.left + edges.right;
    double vertical = edges.top + edges.bottom;
92 93
    double deflatedMinWidth = math.max(0.0, minWidth - horizontal);
    double deflatedMinHeight = math.max(0.0, minHeight - vertical);
94
    return new BoxConstraints(
95 96 97 98
      minWidth: deflatedMinWidth,
      maxWidth: math.max(deflatedMinWidth, maxWidth - horizontal),
      minHeight: deflatedMinHeight,
      maxHeight: math.max(deflatedMinHeight, maxHeight - vertical)
99 100 101
    );
  }

102
  /// Returns new box constraints that remove the minimum width and height requirements
103 104 105 106 107 108 109 110 111
  BoxConstraints loosen() {
    return new BoxConstraints(
      minWidth: 0.0,
      maxWidth: maxWidth,
      minHeight: 0.0,
      maxHeight: maxHeight
    );
  }

112 113
  /// Returns new box constraints that respect the given constraints while being as close as possible to the original constraints
  BoxConstraints enforce(BoxConstraints constraints) {
114 115 116 117 118 119 120 121
    return new BoxConstraints(
      minWidth: clamp(min: constraints.minWidth, max: constraints.maxWidth, value: minWidth),
      maxWidth: clamp(min: constraints.minWidth, max: constraints.maxWidth, value: maxWidth),
      minHeight: clamp(min: constraints.minHeight, max: constraints.maxHeight, value: minHeight),
      maxHeight: clamp(min: constraints.minHeight, max: constraints.maxHeight, value: maxHeight)
    );
  }

122 123
  /// Returns new box constraints with a tight width as close to the given width as possible while still respecting the original box constraints
  BoxConstraints tightenWidth(double width) {
124 125 126 127 128 129
    return new BoxConstraints(minWidth: math.max(math.min(maxWidth, width), minWidth),
                              maxWidth: math.max(math.min(maxWidth, width), minWidth),
                              minHeight: minHeight,
                              maxHeight: maxHeight);
  }

130 131
  /// Returns new box constraints with a tight height as close to the given height as possible while still respecting the original box constraints
  BoxConstraints tightenHeight(double height) {
132 133 134 135 136 137
    return new BoxConstraints(minWidth: minWidth,
                              maxWidth: maxWidth,
                              minHeight: math.max(math.min(maxHeight, height), minHeight),
                              maxHeight: math.max(math.min(maxHeight, height), minHeight));
  }

138
  /// Returns box constraints with the same width constraints but with unconstrainted height
139 140
  BoxConstraints widthConstraints() => new BoxConstraints(minWidth: minWidth, maxWidth: maxWidth);

141
  /// Returns box constraints with the same height constraints but with unconstrainted width
142 143
  BoxConstraints heightConstraints() => new BoxConstraints(minHeight: minHeight, maxHeight: maxHeight);

144
  /// Returns the width that both satisfies the constraints and is as close as possible to the given width
145 146 147 148
  double constrainWidth([double width = double.INFINITY]) {
    return clamp(min: minWidth, max: maxWidth, value: width);
  }

149
  /// Returns the height that both satisfies the constraints and is as close as possible to the given height
150 151 152 153
  double constrainHeight([double height = double.INFINITY]) {
    return clamp(min: minHeight, max: maxHeight, value: height);
  }

154
  /// Returns the size that both satisfies the constraints and is as close as possible to the given size
155 156 157 158 159 160
  Size constrain(Size size) {
    Size result = new Size(constrainWidth(size.width), constrainHeight(size.height));
    if (size is _DebugSize)
      result = new _DebugSize(result, size._owner, size._canBeUsedByParent);
    return result;
  }
161 162

  /// The biggest size that satisifes the constraints
163 164
  Size get biggest => new Size(constrainWidth(), constrainHeight());

165 166
  /// The smallest size that satisfies the constraints
  Size get smallest => new Size(constrainWidth(0.0), constrainHeight(0.0));
167

168
  /// Whether there is exactly one width value that satisfies the constraints
169
  bool get hasTightWidth => minWidth >= maxWidth;
170 171

  /// Whether there is exactly one height value that satisfies the constraints
172
  bool get hasTightHeight => minHeight >= maxHeight;
173 174

  /// Whether there is exactly one size that satifies the constraints
175 176
  bool get isTight => hasTightWidth && hasTightHeight;

177 178
  /// Whether the given size satisfies the constraints
  bool isSatisfiedBy(Size size) {
179 180 181 182
    return (minWidth <= size.width) && (size.width <= math.max(minWidth, maxWidth)) &&
           (minHeight <= size.height) && (size.height <= math.max(minHeight, maxHeight));
  }

Adam Barth's avatar
Adam Barth committed
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
  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
    );
  }

  /// Linearly interpolate between two BoxConstraints
  ///
  /// 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);
    return new BoxConstraints(
230 231 232 233
      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
234 235 236
    );
  }

Hixie's avatar
Hixie committed
237
  bool operator ==(dynamic other) {
238 239
    if (identical(this, other))
      return true;
Hixie's avatar
Hixie committed
240 241 242 243 244 245 246
    if (other is! BoxConstraints)
      return false;
    final BoxConstraints typedOther = other;
    return minWidth == typedOther.minWidth &&
           maxWidth == typedOther.maxWidth &&
           minHeight == typedOther.minHeight &&
           maxHeight == typedOther.maxHeight;
247
  }
Hixie's avatar
Hixie committed
248

249 250 251 252 253 254 255 256 257
  int get hashCode {
    int value = 373;
    value = 37 * value + minWidth.hashCode;
    value = 37 * value + maxWidth.hashCode;
    value = 37 * value + minHeight.hashCode;
    value = 37 * value + maxHeight.hashCode;
    return value;
  }

Hixie's avatar
Hixie committed
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
  String toString() {
    if (minWidth == double.INFINITY && minHeight == double.INFINITY)
      return 'BoxConstraints(biggest)';
    if (minWidth == 0 && maxWidth == double.INFINITY &&
        minHeight == 0 && maxHeight == double.INFINITY)
      return 'BoxConstraints(unconstrained)';
    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');
    return 'BoxConstraints($width, $height)';
  }
273 274
}

Adam Barth's avatar
Adam Barth committed
275
/// A hit test entry used by [RenderBox]
276 277
class BoxHitTestEntry extends HitTestEntry {
  const BoxHitTestEntry(HitTestTarget target, this.localPosition) : super(target);
Adam Barth's avatar
Adam Barth committed
278 279

  /// The position of the hit test in the local coordinates of [target]
280 281 282
  final Point localPosition;
}

Adam Barth's avatar
Adam Barth committed
283
/// Parent data used by [RenderBox] and its subclasses
284 285
class BoxParentData extends ParentData {
  Point _position = Point.origin;
Adam Barth's avatar
Adam Barth committed
286
  /// The point at which to paint the child in the parent's coordinate system
287 288 289 290 291 292 293 294
  Point get position => _position;
  void set position(Point value) {
    assert(RenderObject.debugDoingLayout);
    _position = value;
  }
  String toString() => 'position=$position';
}

Hixie's avatar
Hixie committed
295 296 297 298
/// Abstract ParentData subclass for RenderBox subclasses that want the
/// ContainerRenderObjectMixin.
abstract class ContainerBoxParentDataMixin<ChildType extends RenderObject> extends BoxParentData with ContainerParentDataMixin<ChildType> { }

Adam Barth's avatar
Adam Barth committed
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
/// A render object in a 2D cartesian coordinate system
///
/// 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.
317 318 319 320 321 322 323
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
324 325 326 327
  /// Returns the minimum width that this box could be without failing to paint
  /// its contents within itself
  ///
  /// Override in subclasses that implement [performLayout].
328 329 330 331
  double getMinIntrinsicWidth(BoxConstraints constraints) {
    return constraints.constrainWidth(0.0);
  }

Adam Barth's avatar
Adam Barth committed
332 333 334 335
  /// Returns the smallest width beyond which increasing the width never
  /// decreases the height
  ///
  /// Override in subclasses that implement [performLayout].
336 337 338 339
  double getMaxIntrinsicWidth(BoxConstraints constraints) {
    return constraints.constrainWidth(0.0);
  }

Adam Barth's avatar
Adam Barth committed
340 341 342 343
  /// Return the minimum height that this box could be without failing to render
  /// its contents within itself.
  ///
  /// Override in subclasses that implement [performLayout].
344 345 346 347
  double getMinIntrinsicHeight(BoxConstraints constraints) {
    return constraints.constrainHeight(0.0);
  }

Adam Barth's avatar
Adam Barth committed
348 349 350 351 352 353 354 355
  /// 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].
356 357 358 359
  double getMaxIntrinsicHeight(BoxConstraints constraints) {
    return constraints.constrainHeight(0.0);
  }

360 361 362 363 364 365 366 367 368 369 370 371 372 373
  /// The size of this render box computed during layout
  ///
  /// 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
374
        final _DebugSize _size = this._size;
375 376
        assert(_size._owner == this);
        if (RenderObject.debugActiveLayout != null) {
377 378 379 380 381
          // 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().
382 383 384
          assert(debugDoingThisResize || debugDoingThisLayout ||
                 (RenderObject.debugActiveLayout == parent && _size._canBeUsedByParent));
        }
Hixie's avatar
Hixie committed
385
        assert(_size == this._size);
386 387 388 389 390 391 392 393 394 395 396
      }
      return true;
    });
    return _size;
  }
  bool get hasSize => _size != null;
  Size _size;
  void set size(Size value) {
    assert((sizedByParent && debugDoingThisResize) ||
           (!sizedByParent && debugDoingThisLayout));
    assert(() {
397 398 399 400 401 402
      if (value is _DebugSize) {
        if (value._owner != this) {
          assert(value._owner.parent == this);
          assert(value._canBeUsedByParent);
        }
      }
403 404 405 406 407 408 409 410 411 412
      return true;
    });
    _size = value;
    assert(() {
      _size = new _DebugSize(_size, this, debugCanParentUseSize);
      return true;
    });
    assert(debugDoesMeetConstraints());
  }

413 414 415 416 417
  void debugResetSize() {
    // updates the value of size._canBeUsedByParent if necessary
    size = size;
  }

418 419 420 421 422 423 424
  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
425 426 427 428 429 430 431 432 433 434 435 436 437 438

  /// 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.
439 440 441
  double getDistanceToBaseline(TextBaseline baseline, { bool onlyReal: false }) {
    assert(!needsLayout);
    assert(!_debugDoingBaseline);
Hixie's avatar
Hixie committed
442
    final RenderObject parent = this.parent;
443 444 445 446 447 448 449 450 451 452 453
    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
454
    assert(parent == this.parent);
455 456 457 458
    if (result == null && !onlyReal)
      return size.height;
    return result;
  }
Adam Barth's avatar
Adam Barth committed
459 460 461 462 463 464

  /// 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.
465 466 467 468 469 470 471 472
  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
473 474 475 476 477 478 479 480 481 482 483 484 485

  /// 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.
486 487 488 489 490
  double computeDistanceToActualBaseline(TextBaseline baseline) {
    assert(_debugDoingBaseline);
    return null;
  }

Adam Barth's avatar
Adam Barth committed
491
  /// The box constraints most recently received from the parent
492 493 494 495
  BoxConstraints get constraints => super.constraints;
  bool debugDoesMeetConstraints() {
    assert(constraints != null);
    assert(_size != null);
496
    assert(() {
497
      'See https://flutter.github.io/layout/#unbounded-constraints';
498 499
      return !_size.isInfinite;
    });
500
    bool result = constraints.isSatisfiedBy(_size);
501
    if (!result)
502
      debugPrint("${this.runtimeType} does not meet its constraints. Constraints: $constraints, size: $_size");
503 504 505 506 507 508 509
    return result;
  }

  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
510
      final RenderObject parent = this.parent;
511
      parent.markNeedsLayout();
Hixie's avatar
Hixie committed
512
      assert(parent == this.parent);
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
      // 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() {
    // default behaviour for subclasses that have sizedByParent = true
    size = constraints.constrain(Size.zero);
    assert(!size.isInfinite);
  }
  void performLayout() {
    // descendants have to either override performLayout() to set both
    // width and height and lay out children, or, set sizedByParent to
    // true so that performResize()'s logic above does its thing.
    assert(sizedByParent);
  }

Adam Barth's avatar
Adam Barth committed
536 537 538 539 540 541 542 543 544
  /// Determines the set of render objects located at the given position
  ///
  /// 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.
545
  bool hitTest(HitTestResult result, { Point position }) {
546 547 548 549 550 551 552
    if (position.x >= 0.0 && position.x < _size.width &&
        position.y >= 0.0 && position.y < _size.height) {
      hitTestChildren(result, position: position);
      result.add(new BoxHitTestEntry(this, position));
      return true;
    }
    return false;
553
  }
Adam Barth's avatar
Adam Barth committed
554 555 556 557 558 559 560

  /// Override this function to check whether any children are located at the
  /// given position
  ///
  /// 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).
561 562
  void hitTestChildren(HitTestResult result, { Point position }) { }

Adam Barth's avatar
Adam Barth committed
563 564 565 566 567 568
  /// Multiply the transform from the parent's coordinate system to this box's
  /// coordinate system into the given transform
  ///
  /// 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.
569 570 571 572 573 574 575 576 577 578 579 580 581
  void applyPaintTransform(Matrix4 transform) {
    if (parentData is BoxParentData) {
      Point position = (parentData as BoxParentData).position;
      transform.translate(position.x, position.y);
    }
  }

  static Point _transformPoint(Matrix4 transform, Point point) {
    Vector3 position3 = new Vector3(point.x, point.y, 0.0);
    Vector3 transformed3 = transform.transform3(position3);
    return new Point(transformed3.x, transformed3.y);
  }

Adam Barth's avatar
Adam Barth committed
582 583
  /// Convert the given point from the global coodinate system to the local
  /// coordinate system for this box
584 585 586 587 588 589 590 591 592 593 594 595 596
  Point globalToLocal(Point point) {
    assert(attached);
    Matrix4 transform = new Matrix4.identity();
    RenderObject renderer = this;
    while(renderer != null) {
      renderer.applyPaintTransform(transform);
      renderer = renderer.parent;
    }
    /* double det = */ transform.invert();
    // TODO(abarth): Check the determinant for degeneracy.
    return _transformPoint(transform, point);
  }

Adam Barth's avatar
Adam Barth committed
597 598
  /// Convert the given point from the local coordiante system for this box to
  /// the global coordinate sytem
599 600 601 602 603 604 605 606 607 608
  Point localToGlobal(Point point) {
    List <RenderObject> renderers = <RenderObject>[];
    for (RenderObject renderer = this; renderer != null; renderer = renderer.parent)
      renderers.add(renderer);
    Matrix4 transform = new Matrix4.identity();
    for (RenderObject renderer in renderers.reversed)
      renderer.applyPaintTransform(transform);
    return _transformPoint(transform, point);
  }

Adam Barth's avatar
Adam Barth committed
609 610 611 612 613 614 615 616 617 618 619 620 621
  /// Returns a rectangle that contains all the pixels painted by this box
  ///
  /// 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.
622
  Rect get paintBounds => Point.origin & size;
Adam Barth's avatar
Adam Barth committed
623

624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
  int _debugActivePointers = 0;
  void handleEvent(InputEvent event, HitTestEntry entry) {
    super.handleEvent(event, entry);
    assert(() {
      if (debugPaintPointersEnabled) {
        if (event.type == 'pointerdown')
          _debugActivePointers += 1;
        if (event.type == 'pointerup' || event.type == 'pointercancel')
          _debugActivePointers -= 1;
        markNeedsPaint();
      }
      return true;
    });
  }

639
  void debugPaint(PaintingContext context, Offset offset) {
640
    if (debugPaintSizeEnabled)
641
      debugPaintSize(context, offset);
642
    if (debugPaintBaselinesEnabled)
643
      debugPaintBaselines(context, offset);
644 645
    if (debugPaintPointersEnabled)
      debugPaintPointers(context, offset);
646
  }
647
  void debugPaintSize(PaintingContext context, Offset offset) {
648 649 650 651
    Paint paint = new Paint()
     ..style = ui.PaintingStyle.stroke
     ..strokeWidth = 1.0
     ..color = debugPaintSizeColor;
652
    context.canvas.drawRect(offset & size, paint);
653
  }
654
  void debugPaintBaselines(PaintingContext context, Offset offset) {
655 656 657
    Paint paint = new Paint()
     ..style = ui.PaintingStyle.stroke
     ..strokeWidth = 0.25;
658 659 660 661 662 663 664 665
    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);
666
      context.canvas.drawPath(path, paint);
667 668 669 670 671 672 673 674
    }
    // 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);
675
      context.canvas.drawPath(path, paint);
676 677
    }
  }
678 679 680 681 682 683 684
  void debugPaintPointers(PaintingContext context, Offset offset) {
    if (_debugActivePointers > 0) {
      Paint paint = new Paint()
       ..color = new Color(debugPaintPointersColorValue | ((0x04000000 * depth) & 0xFF000000));
      context.canvas.drawRect(offset & size, paint);
    }
  }
685

Hixie's avatar
Hixie committed
686
  String debugDescribeSettings(String prefix) => '${super.debugDescribeSettings(prefix)}${prefix}size: ${ hasSize ? size : "MISSING" }\n';
687 688
}

689 690
/// A mixin that provides useful default behaviors for boxes with children
/// managed by the [ContainerRenderObjectMixin] mixin.
Adam Barth's avatar
Adam Barth committed
691 692 693 694
///
/// 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
695
abstract class RenderBoxContainerDefaultsMixin<ChildType extends RenderBox, ParentDataType extends ContainerBoxParentDataMixin<ChildType>> implements ContainerRenderObjectMixin<ChildType, ParentDataType> {
696

Adam Barth's avatar
Adam Barth committed
697 698 699 700
  /// Returns the baseline of the first child with a baseline
  ///
  /// Useful when the children are displayed vertically in the same order they
  /// appear in the child list.
701 702 703 704
  double defaultComputeDistanceToFirstActualBaseline(TextBaseline baseline) {
    assert(!needsLayout);
    RenderBox child = firstChild;
    while (child != null) {
Hixie's avatar
Hixie committed
705
      final ParentDataType childParentData = child.parentData;
706 707
      double result = child.getDistanceToActualBaseline(baseline);
      if (result != null)
Hixie's avatar
Hixie committed
708 709
        return result + childParentData.position.y;
      child = childParentData.nextSibling;
710 711 712 713
    }
    return null;
  }

Adam Barth's avatar
Adam Barth committed
714 715 716 717
  /// Returns the minimum baseline value among every child
  ///
  /// Useful when the vertical position of the children isn't determined by the
  /// order in the child list.
718 719 720 721 722
  double defaultComputeDistanceToHighestActualBaseline(TextBaseline baseline) {
    assert(!needsLayout);
    double result;
    RenderBox child = firstChild;
    while (child != null) {
Hixie's avatar
Hixie committed
723
      final ParentDataType childParentData = child.parentData;
724 725
      double candidate = child.getDistanceToActualBaseline(baseline);
      if (candidate != null) {
Hixie's avatar
Hixie committed
726
        candidate += childParentData.position.y;
727 728 729 730 731
        if (result != null)
          result = math.min(result, candidate);
        else
          result = candidate;
      }
Hixie's avatar
Hixie committed
732
      child = childParentData.nextSibling;
733 734 735 736
    }
    return result;
  }

Adam Barth's avatar
Adam Barth committed
737 738 739 740
  /// Performs a hit test on each child by walking the child list backwards
  ///
  /// Stops walking once after the first child reports that it contains the
  /// given point. Returns whether any children contain the given point.
741
  bool defaultHitTestChildren(HitTestResult result, { Point position }) {
742 743 744
    // 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
745 746 747
      final ParentDataType childParentData = child.parentData;
      Point transformed = new Point(position.x - childParentData.position.x,
                                    position.y - childParentData.position.y);
748
      if (child.hitTest(result, position: transformed))
749
        return true;
Hixie's avatar
Hixie committed
750
      child = childParentData.previousSibling;
751
    }
752
    return false;
753 754
  }

Adam Barth's avatar
Adam Barth committed
755
  /// Paints each child by walking the child list forwards
756
  void defaultPaint(PaintingContext context, Offset offset) {
757 758
    RenderBox child = firstChild;
    while (child != null) {
Hixie's avatar
Hixie committed
759 760 761
      final ParentDataType childParentData = child.parentData;
      context.paintChild(child, childParentData.position + offset);
      child = childParentData.nextSibling;
762 763 764
    }
  }
}
765 766 767

/// An offset that's expressed as a fraction of a Size.
///
768 769
/// FractionalOffset(1.0, 0.0) represents the top right of the Size,
/// FractionalOffset(0.0, 1.0) represents the bottom left of the Size,
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
class FractionalOffset {
  const FractionalOffset(this.x, this.y);
  final double x;
  final double y;
  bool operator ==(dynamic other) {
    if (other is! FractionalOffset)
      return false;
    final FractionalOffset typedOther = other;
    return x == typedOther.x &&
           y == typedOther.y;
  }
  int get hashCode {
    int value = 373;
    value = 37 * value + x.hashCode;
    value = 37 * value + y.hashCode;
    return value;
  }
  String toString() => '$runtimeType($x, $y)';
}