box.dart 35.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.

H
Hixie 已提交
5
import 'dart:math' as math;
6
import 'dart:sky' as sky;
7
import 'dart:typed_data';
H
Hixie 已提交
8
import 'object.dart';
9
import '../painting/shadows.dart';
10
import 'package:vector_math/vector_math.dart';
11
import 'package:sky/framework/net/image_cache.dart' as image_cache;
12 13 14 15 16 17 18

// GENERIC BOX RENDERING
// Anything that has a concept of x, y, width, height is going to derive from this

class EdgeDims {
  // used for e.g. padding
  const EdgeDims(this.top, this.right, this.bottom, this.left);
A
Adam Barth 已提交
19 20
  const EdgeDims.all(double value)
      : top = value, right = value, bottom = value, left = value;
21 22 23 24 25 26 27
  const EdgeDims.only({ this.top: 0.0,
                        this.right: 0.0,
                        this.bottom: 0.0,
                        this.left: 0.0 });
  const EdgeDims.symmetric({ double vertical: 0.0,
                             double horizontal: 0.0 })
    : top = vertical, left = horizontal, bottom = vertical, right = horizontal;
28

29 30 31 32
  final double top;
  final double right;
  final double bottom;
  final double left;
A
Adam Barth 已提交
33

34 35 36 37
  operator ==(EdgeDims other) => (top == other.top) ||
                                 (right == other.right) ||
                                 (bottom == other.bottom) ||
                                 (left == other.left);
38 39

  int get hashCode {
40
    int value = 373;
41 42 43 44 45 46 47
    value = 37 * value + top.hashCode;
    value = 37 * value + left.hashCode;
    value = 37 * value + bottom.hashCode;
    value = 37 * value + right.hashCode;
    return value;
  }
  String toString() => "EdgeDims($top, $right, $bottom, $left)";
48 49 50 51 52 53 54 55 56
}

class BoxConstraints {
  const BoxConstraints({
    this.minWidth: 0.0,
    this.maxWidth: double.INFINITY,
    this.minHeight: 0.0,
    this.maxHeight: double.INFINITY});

57
  BoxConstraints.tight(Size size)
58 59 60 61 62
    : minWidth = size.width,
      maxWidth = size.width,
      minHeight = size.height,
      maxHeight = size.height;

63
  BoxConstraints.loose(Size size)
A
Adam Barth 已提交
64 65 66 67 68
    : minWidth = 0.0,
      maxWidth = size.width,
      minHeight = 0.0,
      maxHeight = size.height;

69 70
  BoxConstraints deflate(EdgeDims edges) {
    assert(edges != null);
H
Hixie 已提交
71 72
    double horizontal = edges.left + edges.right;
    double vertical = edges.top + edges.bottom;
73
    return new BoxConstraints(
74
      minWidth: math.max(0.0, minWidth - horizontal),
H
Hixie 已提交
75
      maxWidth: maxWidth - horizontal,
76
      minHeight: math.max(0.0, minHeight - vertical),
H
Hixie 已提交
77
      maxHeight: maxHeight - vertical
78 79 80
    );
  }

81 82 83 84 85 86 87 88
  BoxConstraints apply(BoxConstraints constraints) {
    return new BoxConstraints(
      minWidth: math.max(minWidth, constraints.minWidth),
      maxWidth: math.min(maxWidth, constraints.maxWidth),
      minHeight: math.max(minHeight, constraints.minHeight),
      maxHeight: math.min(maxHeight, constraints.maxHeight));
  }

A
Adam Barth 已提交
89
  BoxConstraints applyWidth(double width) {
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
    return new BoxConstraints(minWidth: math.max(minWidth, width),
                              maxWidth: math.min(maxWidth, width),
                              minHeight: minHeight,
                              maxHeight: maxHeight);
  }

  BoxConstraints applyMinWidth(double width) {
    return new BoxConstraints(minWidth: math.max(minWidth, width),
                              maxWidth: maxWidth,
                              minHeight: minHeight,
                              maxHeight: maxHeight);
  }

  BoxConstraints applyMaxWidth(double width) {
    return new BoxConstraints(minWidth: minWidth,
                              maxWidth: math.min(maxWidth, width),
A
Adam Barth 已提交
106 107 108 109 110 111 112
                              minHeight: minHeight,
                              maxHeight: maxHeight);
  }

  BoxConstraints applyHeight(double height) {
    return new BoxConstraints(minWidth: minWidth,
                              maxWidth: maxWidth,
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
                              minHeight: math.max(minHeight, height),
                              maxHeight: math.min(maxHeight, height));
  }

  BoxConstraints applyMinHeight(double height) {
    return new BoxConstraints(minWidth: minWidth,
                              maxWidth: maxWidth,
                              minHeight: math.max(minHeight, height),
                              maxHeight: maxHeight);
  }

  BoxConstraints applyMaxHeight(double height) {
    return new BoxConstraints(minWidth: minWidth,
                              maxWidth: maxWidth,
                              minHeight: minHeight,
                              maxHeight: math.min(maxHeight, height));
A
Adam Barth 已提交
129 130
  }

131 132 133 134 135
  final double minWidth;
  final double maxWidth;
  final double minHeight;
  final double maxHeight;

H
Hixie 已提交
136 137 138 139 140 141 142
  static double _clamp({double min: 0.0, double value: 0.0, double max: double.INFINITY}) {
    assert(min != null);
    assert(value != null);
    assert(max != null);
    return math.max(min, math.min(max, value));
  }

143
  double constrainWidth(double width) {
H
Hixie 已提交
144
    return _clamp(min: minWidth, max: maxWidth, value: width);
145 146 147
  }

  double constrainHeight(double height) {
H
Hixie 已提交
148
    return _clamp(min: minHeight, max: maxHeight, value: height);
149 150
  }

151 152
  Size constrain(Size size) {
    return new Size(constrainWidth(size.width), constrainHeight(size.height));
153 154 155
  }

  bool get isInfinite => maxWidth >= double.INFINITY || maxHeight >= double.INFINITY;
156 157

  int get hashCode {
158
    int value = 373;
159 160 161 162 163 164 165
    value = 37 * value + minWidth.hashCode;
    value = 37 * value + maxWidth.hashCode;
    value = 37 * value + minHeight.hashCode;
    value = 37 * value + maxHeight.hashCode;
    return value;
  }
  String toString() => "BoxConstraints($minWidth<=w<$maxWidth, $minHeight<=h<$maxHeight)";
166 167
}

168 169 170 171 172 173 174
class BoxHitTestEntry extends HitTestEntry {
  const BoxHitTestEntry(RenderBox target, this.localPosition)
    : super(target);

  final Point localPosition;
}

175
class BoxParentData extends ParentData {
176 177 178 179 180 181
  Point _position = Point.origin;
  Point get position => _position;
  void set position(Point value) {
    assert(RenderObject.debugDoingLayout);
    _position = value;
  }
H
Hixie 已提交
182
  String toString() => 'position=$position';
183 184
}

H
Hixie 已提交
185
abstract class RenderBox extends RenderObject {
186

H
Hixie 已提交
187
  void setParentData(RenderObject child) {
188 189 190 191
    if (child.parentData is! BoxParentData)
      child.parentData = new BoxParentData();
  }

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
  // getMinIntrinsicWidth() should return the minimum width that this box could 
  // be without failing to render its contents within itself.
  double getMinIntrinsicWidth(BoxConstraints constraints) {
    return constraints.constrainWidth(0.0);
  }

  // getMaxIntrinsicWidth() should return the smallest width beyond which 
  // increasing the width never decreases the height.
  double getMaxIntrinsicWidth(BoxConstraints constraints) {
    return constraints.constrainWidth(0.0);
  }

  // getMinIntrinsicHeight() should return the minimum height that this box could 
  // be without failing to render its contents within itself.
  double getMinIntrinsicHeight(BoxConstraints constraints) {
    return constraints.constrainHeight(0.0);
  }

  // getMaxIntrinsicHeight should return 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().
  double getMaxIntrinsicHeight(BoxConstraints constraints) {
    return constraints.constrainHeight(0.0);
217 218
  }

219
  BoxConstraints get constraints { BoxConstraints result = super.constraints; return result; }
220 221
  void performResize() {
    // default behaviour for subclasses that have sizedByParent = true
A
Adam Barth 已提交
222
    size = constraints.constrain(Size.zero);
223 224 225 226 227 228 229 230 231 232
    assert(size.height < double.INFINITY);
    assert(size.width < double.INFINITY);
  }
  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);
  }

233
  bool hitTest(HitTestResult result, { Point position }) {
234
    hitTestChildren(result, position: position);
235
    result.add(new BoxHitTestEntry(this, position));
236 237
    return true;
  }
238
  void hitTestChildren(HitTestResult result, { Point position }) { }
239

240 241 242 243 244 245
  Size _size = Size.zero;
  Size get size => _size;
  void set size(Size value) {
    assert(RenderObject.debugDoingLayout);
    _size = value;
  }
246 247

  String debugDescribeSettings(String prefix) => '${super.debugDescribeSettings(prefix)}${prefix}size: ${size}\n';
248 249
}

H
Hixie 已提交
250
abstract class RenderProxyBox extends RenderBox with RenderObjectWithChildMixin<RenderBox> {
251 252 253 254
  RenderProxyBox(RenderBox child) {
    this.child = child;
  }

255
  double getMinIntrinsicWidth(BoxConstraints constraints) {
256
    if (child != null)
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
      return child.getMinIntrinsicWidth(constraints);
    return super.getMinIntrinsicWidth(constraints);
  }

  double getMaxIntrinsicWidth(BoxConstraints constraints) {
    if (child != null)
      return child.getMaxIntrinsicWidth(constraints);
    return super.getMaxIntrinsicWidth(constraints);
  }

  double getMinIntrinsicHeight(BoxConstraints constraints) {
    if (child != null)
      return child.getMinIntrinsicHeight(constraints);
    return super.getMinIntrinsicHeight(constraints);
  }

  double getMaxIntrinsicHeight(BoxConstraints constraints) {
    if (child != null)
      return child.getMaxIntrinsicHeight(constraints);
    return super.getMaxIntrinsicHeight(constraints);
277 278 279 280 281 282 283 284 285 286 287
  }

  void performLayout() {
    if (child != null) {
      child.layout(constraints, parentUsesSize: true);
      size = child.size;
    } else {
      performResize();
    }
  }

288
  void hitTestChildren(HitTestResult result, { Point position }) {
289 290 291 292 293 294
    if (child != null)
      child.hitTest(result, position: position);
    else
      super.hitTestChildren(result, position: position);
  }

H
Hixie 已提交
295
  void paint(RenderObjectDisplayList canvas) {
296 297 298 299 300 301 302 303
    if (child != null)
      child.paint(canvas);
  }
}

class RenderSizedBox extends RenderProxyBox {

  RenderSizedBox({
304
    RenderBox child,
305
    Size desiredSize: Size.infinite
306
  }) : super(child), _desiredSize = desiredSize {
A
Adam Barth 已提交
307 308 309
    assert(desiredSize != null);
  }

310 311 312
  Size _desiredSize;
  Size get desiredSize => _desiredSize;
  void set desiredSize (Size value) {
A
Adam Barth 已提交
313 314 315 316 317 318
    assert(value != null);
    if (_desiredSize == value)
      return;
    _desiredSize = value;
    markNeedsLayout();
  }
319

320 321 322 323 324 325 326 327 328 329 330 331 332 333
  double getMinIntrinsicWidth(BoxConstraints constraints) {
    return constraints.constrainWidth(_desiredSize.width);
  }

  double getMaxIntrinsicWidth(BoxConstraints constraints) {
    return constraints.constrainWidth(_desiredSize.width);
  }

  double getMinIntrinsicHeight(BoxConstraints constraints) {
    return constraints.constrainHeight(_desiredSize.height);
  }

  double getMaxIntrinsicHeight(BoxConstraints constraints) {
    return constraints.constrainHeight(_desiredSize.height);
334 335 336
  }

  void performLayout() {
A
Adam Barth 已提交
337
    size = constraints.constrain(_desiredSize);
H
Hixie 已提交
338 339
    if (child != null)
      child.layout(new BoxConstraints.tight(size));
340
  }
H
Hixie 已提交
341

342
  String debugDescribeSettings(String prefix) => '${super.debugDescribeSettings(prefix)}${prefix}desiredSize: ${desiredSize}\n';
343 344
}

345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
class RenderConstrainedBox extends RenderProxyBox {
  RenderConstrainedBox({
    RenderBox child,
    BoxConstraints additionalConstraints
  }) : super(child), _additionalConstraints = additionalConstraints {
    assert(additionalConstraints != null);
  }

  BoxConstraints _additionalConstraints;
  BoxConstraints get additionalConstraints => _additionalConstraints;
  void set additionalConstraints (BoxConstraints value) {
    assert(value != null);
    if (_additionalConstraints == value)
      return;
    _additionalConstraints = value;
    markNeedsLayout();
  }

363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
  double getMinIntrinsicWidth(BoxConstraints constraints) {
    if (child != null)
      return child.getMinIntrinsicWidth(constraints.apply(_additionalConstraints));
    return constraints.constrainWidth(0.0);
  }

  double getMaxIntrinsicWidth(BoxConstraints constraints) {
    if (child != null)
      return child.getMaxIntrinsicWidth(constraints.apply(_additionalConstraints));
    return constraints.constrainWidth(0.0);
  }

  double getMinIntrinsicHeight(BoxConstraints constraints) {
    if (child != null)
      return child.getMinIntrinsicHeight(constraints.apply(_additionalConstraints));
    return constraints.constrainHeight(0.0);
  }

  double getMaxIntrinsicHeight(BoxConstraints constraints) {
    if (child != null)
      return child.getMaxIntrinsicHeight(constraints.apply(_additionalConstraints));
    return constraints.constrainHeight(0.0);
385 386 387 388 389 390 391 392 393 394 395 396 397 398
  }

  void performLayout() {
    if (child != null) {
      child.layout(constraints.apply(_additionalConstraints));
      size = child.size;
    } else {
      performResize();
    }
  }

  String debugDescribeSettings(String prefix) => '${super.debugDescribeSettings(prefix)}${prefix}additionalConstraints: ${additionalConstraints}\n';
}

A
Adam Barth 已提交
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
class RenderShrinkWrapWidth extends RenderProxyBox {
  RenderShrinkWrapWidth({ RenderBox child }) : super(child);

  BoxConstraints _getInnerConstraints(BoxConstraints constraints) {
    double width = child.getMaxIntrinsicWidth(constraints);
    assert(width == constraints.constrainWidth(width));
    return constraints.applyWidth(width);
  }

  double getMinIntrinsicWidth(BoxConstraints constraints) {
    if (child != null)
      return child.getMaxIntrinsicWidth(constraints);
    return constraints.constrainWidth(0.0);
  }

  double getMaxIntrinsicWidth(BoxConstraints constraints) {
    if (child != null)
      return child.getMaxIntrinsicWidth(constraints);
    return constraints.constrainWidth(0.0);
  }

  double getMinIntrinsicHeight(BoxConstraints constraints) {
    if (child != null)
      return child.getMinIntrinsicHeight(_getInnerConstraints(constraints));
    return constraints.constrainWidth(0.0);
  }

  double getMaxIntrinsicHeight(BoxConstraints constraints) {
    if (child != null)
      return child.getMaxIntrinsicHeight(_getInnerConstraints(constraints));
    return constraints.constrainWidth(0.0);
  }

  void performLayout() {
    if (child != null) {
      child.layout(_getInnerConstraints(constraints));
      size = child.size;
    } else {
      performResize();
    }
  }
}

A
Adam Barth 已提交
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
class RenderOpacity extends RenderProxyBox {
  RenderOpacity({ RenderBox child, double opacity })
    : this._opacity = opacity, super(child) {
    assert(opacity >= 0.0 && opacity <= 1.0);
  }

  double _opacity;
  double get opacity => _opacity;
  void set opacity (double value) {
    assert(value != null);
    assert(value >= 0.0 && value <= 1.0);
    if (_opacity == value)
      return;
    _opacity = value;
    markNeedsPaint();
  }

  void paint(RenderObjectDisplayList canvas) {
    if (child != null) {
      int a = (_opacity * 255).round();

      if (a == 0)
        return;

      if (a == 255) {
        child.paint(canvas);
        return;
      }

      Paint paint = new Paint()
        ..color = new Color.fromARGB(a, 0, 0, 0)
        ..setTransferMode(sky.TransferMode.srcOverMode);
      canvas.saveLayer(null, paint);
      child.paint(canvas);
      canvas.restore();
    }
  }
}

481 482
class RenderClipRect extends RenderProxyBox {
  RenderClipRect({ RenderBox child }) : super(child);
483 484 485 486

  void paint(RenderObjectDisplayList canvas) {
    if (child != null) {
      canvas.save();
487
      canvas.clipRect(new Rect.fromSize(size));
488 489 490 491 492 493
      child.paint(canvas);
      canvas.restore();
    }
  }
}

494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
class RenderClipOval extends RenderProxyBox {
  RenderClipOval({ RenderBox child }) : super(child);

  void paint(RenderObjectDisplayList canvas) {
    if (child != null) {
      Rect rect = new Rect.fromSize(size);
      canvas.saveLayer(rect, new Paint());
      Path path = new Path();
      path.addOval(rect);
      canvas.clipPath(path);
      child.paint(canvas);
      canvas.restore();
    }
  }
}

H
Hixie 已提交
510
class RenderPadding extends RenderBox with RenderObjectWithChildMixin<RenderBox> {
511

A
Adam Barth 已提交
512
  RenderPadding({ EdgeDims padding, RenderBox child }) {
513 514 515 516 517 518 519 520 521
    assert(padding != null);
    this.padding = padding;
    this.child = child;
  }

  EdgeDims _padding;
  EdgeDims get padding => _padding;
  void set padding (EdgeDims value) {
    assert(value != null);
A
Adam Barth 已提交
522 523 524 525
    if (_padding == value)
      return;
    _padding = value;
    markNeedsLayout();
526 527
  }

528
  double getMinIntrinsicWidth(BoxConstraints constraints) {
A
Adam Barth 已提交
529
    double totalPadding = padding.left + padding.right;
530
    if (child != null)
A
Adam Barth 已提交
531 532
      return child.getMinIntrinsicWidth(constraints.deflate(padding)) + totalPadding;
    return constraints.constrainWidth(totalPadding);
533 534 535
  }

  double getMaxIntrinsicWidth(BoxConstraints constraints) {
A
Adam Barth 已提交
536
    double totalPadding = padding.left + padding.right;
537
    if (child != null)
A
Adam Barth 已提交
538 539
      return child.getMaxIntrinsicWidth(constraints.deflate(padding)) + totalPadding;
    return constraints.constrainWidth(totalPadding);
540 541 542
  }

  double getMinIntrinsicHeight(BoxConstraints constraints) {
A
Adam Barth 已提交
543
    double totalPadding = padding.top + padding.bottom;
544
    if (child != null)
A
Adam Barth 已提交
545 546
      return child.getMinIntrinsicHeight(constraints.deflate(padding)) + totalPadding;
    return constraints.constrainHeight(totalPadding);
547 548 549
  }

  double getMaxIntrinsicHeight(BoxConstraints constraints) {
A
Adam Barth 已提交
550
    double totalPadding = padding.top + padding.bottom;
551
    if (child != null)
A
Adam Barth 已提交
552 553
      return child.getMaxIntrinsicHeight(constraints.deflate(padding)) + totalPadding;
    return constraints.constrainHeight(totalPadding);
554 555 556 557 558 559 560
  }

  void performLayout() {
    assert(padding != null);
    BoxConstraints innerConstraints = constraints.deflate(padding);
    if (child == null) {
      size = innerConstraints.constrain(
561
          new Size(padding.left + padding.right, padding.top + padding.bottom));
562 563 564 565
      return;
    }
    child.layout(innerConstraints, parentUsesSize: true);
    assert(child.parentData is BoxParentData);
566 567
    child.parentData.position = new Point(padding.left, padding.top);
    size = constraints.constrain(new Size(padding.left + child.size.width + padding.right,
568 569 570
                                              padding.top + child.size.height + padding.bottom));
  }

H
Hixie 已提交
571
  void paint(RenderObjectDisplayList canvas) {
572 573 574 575
    if (child != null)
      canvas.paintChild(child, child.parentData.position);
  }

576
  void hitTestChildren(HitTestResult result, { Point position }) {
577 578
    if (child != null) {
      assert(child.parentData is BoxParentData);
579
      Rect childBounds = new Rect.fromPointAndSize(child.parentData.position, child.size);
580
      if (childBounds.contains(position)) {
581
        child.hitTest(result, position: new Point(position.x - child.parentData.position.x,
582 583 584 585 586
                                                      position.y - child.parentData.position.y));
      }
    }
  }

587
  String debugDescribeSettings(String prefix) => '${super.debugDescribeSettings(prefix)}${prefix}padding: ${padding}\n';
588 589
}

590 591
class RenderImage extends RenderBox {

592
  RenderImage(String url, Size dimensions) {
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
    requestedSize = dimensions;
    src = url;
  }

  sky.Image _image;
  String _src;
  String get src => _src;
  void set src (String value) {
    if (value == _src)
      return;
    _src = value;
    image_cache.load(_src, (result) {
      _image = result;
      if (requestedSize.width == null || requestedSize.height == null)
        markNeedsLayout();
      markNeedsPaint();
    });
  }

612 613 614
  Size _requestedSize;
  Size get requestedSize => _requestedSize;
  void set requestedSize (Size value) {
615 616 617 618 619 620
    if (value == _requestedSize)
      return;
    _requestedSize = value;
    markNeedsLayout();
  }

621
  Size _sizeForConstraints(BoxConstraints innerConstraints) {
622 623 624 625
    // If there's no image, we can't size ourselves automatically
    if (_image == null) {
      double width = requestedSize.width == null ? 0.0 : requestedSize.width;
      double height = requestedSize.height == null ? 0.0 : requestedSize.height;
626
      return constraints.constrain(new Size(width, height));
627 628 629 630 631 632 633
    }

    // If neither height nor width are specified, use inherent image dimensions
    // If only one dimension is specified, adjust the other dimension to
    // maintain the aspect ratio
    if (requestedSize.width == null) {
      if (requestedSize.height == null) {
634
        return constraints.constrain(new Size(_image.width.toDouble(), _image.height.toDouble()));
635 636
      } else {
        double width = requestedSize.height * _image.width / _image.height;
637
        return constraints.constrain(new Size(width, requestedSize.height));
638 639 640
      }
    } else if (requestedSize.height == null) {
      double height = requestedSize.width * _image.height / _image.width;
641
      return constraints.constrain(new Size(requestedSize.width, height));
642
    } else {
643
      return constraints.constrain(requestedSize);
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 670
  double getMinIntrinsicWidth(BoxConstraints constraints) {
    if (requestedSize.width == null && requestedSize.height == null)
      return constraints.constrainWidth(0.0);
    return _sizeForConstraints(constraints).width;
  }

  double getMaxIntrinsicWidth(BoxConstraints constraints) {
    return _sizeForConstraints(constraints).width;
  }

  double getMinIntrinsicHeight(BoxConstraints constraints) {
    if (requestedSize.width == null && requestedSize.height == null)
      return constraints.constrainHeight(0.0);
    return _sizeForConstraints(constraints).height;
  }

  double getMaxIntrinsicHeight(BoxConstraints constraints) {
    return _sizeForConstraints(constraints).height;
  }

  void performLayout() {
    size = _sizeForConstraints(constraints);
  }

H
Hixie 已提交
671
  void paint(RenderObjectDisplayList canvas) {
672 673 674 675 676 677 678 679
    if (_image == null) return;
    bool needsScale = size.width != _image.width || size.height != _image.height;
    if (needsScale) {
      double widthScale = size.width / _image.width;
      double heightScale = size.height / _image.height;
      canvas.save();
      canvas.scale(widthScale, heightScale);
    }
680
    Paint paint = new Paint();
681 682 683 684
    canvas.drawImage(_image, 0.0, 0.0, paint);
    if (needsScale)
      canvas.restore();
  }
H
Hixie 已提交
685

686
  String debugDescribeSettings(String prefix) => '${super.debugDescribeSettings(prefix)}${prefix}url: ${src}\n${prefix}dimensions: ${requestedSize}\n';
687 688
}

689 690
class BorderSide {
  const BorderSide({
691
    this.color: const Color(0xFF000000),
692 693
    this.width: 1.0
  });
694
  final Color color;
695 696
  final double width;

697
  static const none = const BorderSide(width: 0.0);
698 699 700 701 702 703 704 705 706 707 708 709

  int get hashCode {
    int value = 373;
    value = 37 * value * color.hashCode;
    value = 37 * value * width.hashCode;
    return value;
  }
  String toString() => 'BorderSide($color, $width)';
}

class Border {
  const Border({
710 711 712 713
    this.top: BorderSide.none,
    this.right: BorderSide.none,
    this.bottom: BorderSide.none,
    this.left: BorderSide.none
714
  });
H
Hixie 已提交
715

716 717 718 719 720
  const Border.all(BorderSide side) :
    top = side,
    right = side,
    bottom = side,
    left = side;
H
Hixie 已提交
721

722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
  final BorderSide top;
  final BorderSide right;
  final BorderSide bottom;
  final BorderSide left;

  int get hashCode {
    int value = 373;
    value = 37 * value * top.hashCode;
    value = 37 * value * right.hashCode;
    value = 37 * value * bottom.hashCode;
    value = 37 * value * left.hashCode;
    return value;
  }
  String toString() => 'Border($top, $right, $bottom, $left)';
}

738 739 740 741 742 743 744 745 746 747 748 749 750 751
class BoxShadow {
  const BoxShadow({
    this.color,
    this.offset,
    this.blur
  });

  final Color color;
  final Size offset;
  final double blur;

  String toString() => 'BoxShadow($color, $offset, $blur)';
}

752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
abstract class Gradient {
  sky.Shader createShader();
}

class LinearGradient extends Gradient {
  LinearGradient({
    this.endPoints,
    this.colors,
    this.colorStops,
    this.tileMode: sky.TileMode.clamp
  });

  String toString() =>
      'LinearGradient($endPoints, $colors, $colorStops, $tileMode)';

  sky.Shader createShader() {
    return new sky.Gradient.Linear(this.endPoints, this.colors, this.colorStops,
                                   this.tileMode);
  }

  final List<Point> endPoints;
  final List<Color> colors;
  final List<double> colorStops;
  final sky.TileMode tileMode;
}

class RadialGradient extends Gradient {
  RadialGradient({
    this.center,
    this.radius,
    this.colors,
    this.colorStops,
    this.tileMode: sky.TileMode.clamp
  });

  String toString() =>
      'RadialGradient($center, $radius, $colors, $colorStops, $tileMode)';

  sky.Shader createShader() {
    return new sky.Gradient.Radial(this.center, this.radius, this.colors,
                                   this.colorStops, this.tileMode);
  }

  final Point center;
  final double radius;
  final List<Color> colors;
  final List<double> colorStops;
  final sky.TileMode tileMode;
}

802 803
// This must be immutable, because we won't notice when it changes
class BoxDecoration {
804 805
  const BoxDecoration({
    this.backgroundColor,
806
    this.border,
807
    this.borderRadius,
808 809
    this.boxShadow,
    this.gradient
810
  });
811

812
  final Color backgroundColor;
813
  final double borderRadius;
814
  final Border border;
815
  final List<BoxShadow> boxShadow;
816
  final Gradient gradient;
H
Hixie 已提交
817 818 819 820 821 822 823

  String toString([String prefix = '']) {
    List<String> result = [];
    if (backgroundColor != null)
      result.add('${prefix}backgroundColor: $backgroundColor');
    if (border != null)
      result.add('${prefix}border: $border');
824 825 826 827
    if (borderRadius != null)
      result.add('${prefix}borderRadius: $borderRadius');
    if (boxShadow != null)
      result.add('${prefix}boxShadow: ${boxShadow.map((shadow) => shadow.toString())}');
828 829
    if (gradient != null)
      result.add('${prefix}gradient: $gradient');
H
Hixie 已提交
830 831 832 833
    if (result.isEmpty)
      return '${prefix}<no decorations specified>';
    return result.join('\n');
  }
834 835 836 837 838 839 840
}

class RenderDecoratedBox extends RenderProxyBox {

  RenderDecoratedBox({
    BoxDecoration decoration,
    RenderBox child
841 842 843
  }) : _decoration = decoration, super(child) {
    assert(_decoration != null);
  }
844 845 846 847

  BoxDecoration _decoration;
  BoxDecoration get decoration => _decoration;
  void set decoration (BoxDecoration value) {
848
    assert(value != null);
849 850 851
    if (value == _decoration)
      return;
    _decoration = value;
852
    _cachedBackgroundPaint = null;
853 854 855
    markNeedsPaint();
  }

856 857 858 859 860 861 862 863 864
  Paint _cachedBackgroundPaint;
  Paint get _backgroundPaint {
    if (_cachedBackgroundPaint == null) {
      Paint paint = new Paint();

      if (_decoration.backgroundColor != null)
        paint.color = _decoration.backgroundColor;

      if (_decoration.boxShadow != null) {
865 866 867
        var builder = new ShadowDrawLooperBuilder();
        for (BoxShadow boxShadow in _decoration.boxShadow)
          builder.addShadow(boxShadow.offset, boxShadow.color, boxShadow.blur);
868 869 870
        paint.setDrawLooper(builder.build());
      }

871 872 873
      if (_decoration.gradient != null)
        paint.setShader(_decoration.gradient.createShader());

874 875 876 877 878 879
      _cachedBackgroundPaint = paint;
    }

    return _cachedBackgroundPaint;
  }

H
Hixie 已提交
880
  void paint(RenderObjectDisplayList canvas) {
881 882 883
    assert(size.width != null);
    assert(size.height != null);

884
    if (_decoration.backgroundColor != null || _decoration.boxShadow != null ||
885
        _decoration.gradient != null) {
886 887 888 889 890 891
      Rect rect = new Rect.fromLTRB(0.0, 0.0, size.width, size.height);
      if (_decoration.borderRadius == null)
        canvas.drawRect(rect, _backgroundPaint);
      else
        canvas.drawRRect(new sky.RRect()..setRectXY(rect, _decoration.borderRadius, _decoration.borderRadius), _backgroundPaint);
    }
892 893

    if (_decoration.border != null) {
894 895
      assert(_decoration.borderRadius == null); // TODO(abarth): Implement borders with border radius.

896 897 898 899 900
      assert(_decoration.border.top != null);
      assert(_decoration.border.right != null);
      assert(_decoration.border.bottom != null);
      assert(_decoration.border.left != null);

901 902
      Paint paint = new Paint();
      Path path;
903 904

      paint.color = _decoration.border.top.color;
905
      path = new Path();
906 907 908 909 910 911 912 913
      path.moveTo(0.0,0.0);
      path.lineTo(_decoration.border.left.width, _decoration.border.top.width);
      path.lineTo(size.width - _decoration.border.right.width, _decoration.border.top.width);
      path.lineTo(size.width, 0.0);
      path.close();
      canvas.drawPath(path, paint);

      paint.color = _decoration.border.right.color;
914
      path = new Path();
915 916 917 918 919 920 921 922
      path.moveTo(size.width, 0.0);
      path.lineTo(size.width - _decoration.border.right.width, _decoration.border.top.width);
      path.lineTo(size.width - _decoration.border.right.width, size.height - _decoration.border.bottom.width);
      path.lineTo(size.width, size.height);
      path.close();
      canvas.drawPath(path, paint);

      paint.color = _decoration.border.bottom.color;
923
      path = new Path();
924 925 926 927 928 929 930 931
      path.moveTo(size.width, size.height);
      path.lineTo(size.width - _decoration.border.right.width, size.height - _decoration.border.bottom.width);
      path.lineTo(_decoration.border.left.width, size.height - _decoration.border.bottom.width);
      path.lineTo(0.0, size.height);
      path.close();
      canvas.drawPath(path, paint);

      paint.color = _decoration.border.left.color;
932
      path = new Path();
933 934 935 936 937 938 939 940
      path.moveTo(0.0, size.height);
      path.lineTo(_decoration.border.left.width, size.height - _decoration.border.bottom.width);
      path.lineTo(_decoration.border.left.width, _decoration.border.top.width);
      path.lineTo(0.0,0.0);
      path.close();
      canvas.drawPath(path, paint);
    }

941 942
    super.paint(canvas);
  }
H
Hixie 已提交
943

944
  String debugDescribeSettings(String prefix) => '${super.debugDescribeSettings(prefix)}${prefix}decoration:\n${decoration.toString(prefix + "  ")}\n';
945 946 947 948 949 950 951 952 953 954 955 956 957
}

class RenderTransform extends RenderProxyBox {
  RenderTransform({
    Matrix4 transform,
    RenderBox child
  }) : super(child) {
    assert(transform != null);
    this.transform = transform;
  }

  Matrix4 _transform;

958
  void set transform(Matrix4 value) {
959 960 961 962 963 964 965
    assert(value != null);
    if (_transform == value)
      return;
    _transform = new Matrix4.copy(value);
    markNeedsPaint();
  }

966 967 968 969 970
  void setIdentity() {
    _transform.setIdentity();
    markNeedsPaint();
  }

971 972 973 974 975 976 977 978 979 980 981 982 983 984
  void rotateX(double radians) {
    _transform.rotateX(radians);
    markNeedsPaint();
  }

  void rotateY(double radians) {
    _transform.rotateY(radians);
    markNeedsPaint();
  }

  void rotateZ(double radians) {
    _transform.rotateZ(radians);
    markNeedsPaint();
  }
985

986 987 988 989 990 991 992 993 994 995
  void translate(x, [double y = 0.0, double z = 0.0]) {
    _transform.translate(x, y, z);
    markNeedsPaint();
  }

  void scale(x, [double y, double z]) {
    _transform.scale(x, y, z);
    markNeedsPaint();
  }

996
  void hitTestChildren(HitTestResult result, { Point position }) {
997 998 999 1000 1001 1002
    Matrix4 inverse = new Matrix4.zero();
    double det = inverse.copyInverse(_transform);
    // TODO(abarth): Check the determinant for degeneracy.

    Vector3 position3 = new Vector3(position.x, position.y, 0.0);
    Vector3 transformed3 = inverse.transform3(position3);
1003
    Point transformed = new Point(transformed3.x, transformed3.y);
1004 1005 1006
    super.hitTestChildren(result, position: transformed);
  }

H
Hixie 已提交
1007
  void paint(RenderObjectDisplayList canvas) {
1008
    canvas.save();
1009
    canvas.concat(_transform.storage);
1010 1011 1012
    super.paint(canvas);
    canvas.restore();
  }
1013 1014 1015 1016 1017 1018

  String debugDescribeSettings(String prefix) {
    List<String> result = _transform.toString().split('\n').map((s) => '$prefix  $s\n').toList();
    result.removeLast();
    return '${super.debugDescribeSettings(prefix)}${prefix}transform matrix:\n${result.join()}';
  }
1019 1020
}

1021
typedef void SizeChangedCallback(Size newSize);
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033

class RenderSizeObserver extends RenderProxyBox {
  RenderSizeObserver({
    this.callback,
    RenderBox child
  }) : super(child) {
    assert(callback != null);
  }

  SizeChangedCallback callback;

  void performLayout() {
1034
    Size oldSize = size;
1035 1036 1037 1038 1039 1040 1041 1042

    super.performLayout();

    if (oldSize != size)
      callback(size);
  }
}

1043
typedef void CustomPaintCallback(sky.Canvas canvas);
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056

class RenderCustomPaint extends RenderProxyBox {

  RenderCustomPaint({
    CustomPaintCallback callback,
    RenderBox child
  }) : super(child) {
    assert(callback != null);
    _callback = callback;
  }

  CustomPaintCallback _callback;
  void set callback (CustomPaintCallback value) {
1057
    assert(value != null || !attached);
1058 1059 1060 1061 1062 1063
    if (_callback == value)
      return;
    _callback = value;
    markNeedsPaint();
  }

1064 1065 1066 1067 1068
  void attach() {
    assert(_callback != null);
    super.attach();
  }

1069
  void paint(RenderObjectDisplayList canvas) {
1070
    assert(_callback != null);
1071 1072 1073 1074 1075
    _callback(canvas);
    super.paint(canvas);
  }
}

1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
// RENDER VIEW LAYOUT MANAGER

class ViewConstraints {

  const ViewConstraints({
    this.width: 0.0, this.height: 0.0, this.orientation: null
  });

  final double width;
  final double height;
  final int orientation;

}

H
Hixie 已提交
1090
class RenderView extends RenderObject with RenderObjectWithChildMixin<RenderBox> {
1091 1092 1093 1094 1095 1096 1097 1098

  RenderView({
    RenderBox child,
    this.timeForRotation: const Duration(microseconds: 83333)
  }) {
    this.child = child;
  }

A
Adam Barth 已提交
1099
  Size _size = Size.zero;
1100 1101 1102 1103 1104 1105 1106
  double get width => _size.width;
  double get height => _size.height;

  int _orientation; // 0..3
  int get orientation => _orientation;
  Duration timeForRotation;

1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
  ViewConstraints _rootConstraints;
  ViewConstraints get rootConstraints => _rootConstraints;
  void set rootConstraints(ViewConstraints value) {
    if (_rootConstraints == value)
      return;
    _rootConstraints = value;
    markNeedsLayout();
  }

  void performLayout() {
    if (_rootConstraints.orientation != _orientation) {
1118
      if (_orientation != null && child != null)
1119 1120
        child.rotate(oldAngle: _orientation, newAngle: _rootConstraints.orientation, time: timeForRotation);
      _orientation = _rootConstraints.orientation;
1121
    }
1122
    _size = new Size(_rootConstraints.width, _rootConstraints.height);
1123 1124
    assert(_size.height < double.INFINITY);
    assert(_size.width < double.INFINITY);
1125

1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
    if (child != null) {
      child.layout(new BoxConstraints.tight(_size));
      assert(child.size.width == width);
      assert(child.size.height == height);
    }
  }

  void rotate({ int oldAngle, int newAngle, Duration time }) {
    assert(false); // nobody tells the screen to rotate, the whole rotate() dance is started from our performResize()
  }

1137
  bool hitTest(HitTestResult result, { Point position }) {
1138
    if (child != null) {
1139
      Rect childBounds = new Rect.fromSize(child.size);
1140 1141 1142
      if (childBounds.contains(position))
        child.hitTest(result, position: position);
    }
1143
    result.add(new HitTestEntry(this));
1144 1145 1146
    return true;
  }

H
Hixie 已提交
1147
  void paint(RenderObjectDisplayList canvas) {
1148
    if (child != null)
1149
      canvas.paintChild(child, Point.origin);
1150 1151 1152
  }

  void paintFrame() {
H
Hixie 已提交
1153 1154
    RenderObject.debugDoingPaint = true;
    RenderObjectDisplayList canvas = new RenderObjectDisplayList(sky.view.width, sky.view.height);
1155 1156
    paint(canvas);
    sky.view.picture = canvas.endRecording();
H
Hixie 已提交
1157
    RenderObject.debugDoingPaint = false;
1158 1159 1160 1161 1162
  }

}

// DEFAULT BEHAVIORS FOR RENDERBOX CONTAINERS
H
Hixie 已提交
1163
abstract class RenderBoxContainerDefaultsMixin<ChildType extends RenderBox, ParentDataType extends ContainerParentDataMixin<ChildType>> implements ContainerRenderObjectMixin<ChildType, ParentDataType> {
1164

1165
  void defaultHitTestChildren(HitTestResult result, { Point position }) {
1166 1167 1168 1169
    // the x, y parameters have the top left of the node's box as the origin
    ChildType child = lastChild;
    while (child != null) {
      assert(child.parentData is ParentDataType);
1170
      Rect childBounds = new Rect.fromPointAndSize(child.parentData.position, child.size);
1171
      if (childBounds.contains(position)) {
1172
        if (child.hitTest(result, position: new Point(position.x - child.parentData.position.x,
1173 1174 1175 1176 1177 1178 1179
                                                          position.y - child.parentData.position.y)))
          break;
      }
      child = child.parentData.previousSibling;
    }
  }

H
Hixie 已提交
1180
  void defaultPaint(RenderObjectDisplayList canvas) {
1181 1182 1183 1184 1185 1186 1187 1188
    RenderBox child = firstChild;
    while (child != null) {
      assert(child.parentData is ParentDataType);
      canvas.paintChild(child, child.parentData.position);
      child = child.parentData.nextSibling;
    }
  }
}