fn2.dart 28.2 KB
Newer Older
1 2 3 4 5 6
// 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.

library fn;

7
import 'app.dart';
8 9 10 11
import 'dart:async';
import 'dart:collection';
import 'dart:mirrors';
import 'dart:sky' as sky;
12
import 'package:vector_math/vector_math.dart';
13
import 'reflect.dart' as reflect;
14 15 16
import 'rendering/block.dart';
import 'rendering/box.dart';
import 'rendering/flex.dart';
H
Hixie 已提交
17
import 'rendering/object.dart';
18
import 'rendering/paragraph.dart';
A
Adam Barth 已提交
19
import 'rendering/stack.dart';
20
export 'rendering/object.dart' show Point, Size, Rect, Color, Paint, Path;
21
export 'rendering/box.dart' show BoxConstraints, BoxDecoration, Border, BorderSide, EdgeDims;
22
export 'rendering/flex.dart' show FlexDirection;
23

24
// final sky.Tracing _tracing = sky.window.tracing;
25 26 27 28 29 30 31 32 33 34 35 36 37 38

final bool _shouldLogRenderDuration = false;

/*
 * All Effen nodes derive from UINode. All nodes have a _parent, a _key and
 * can be sync'd.
 */
abstract class UINode {

  UINode({ Object key }) {
    _key = key == null ? "$runtimeType" : "$runtimeType-$key";
    assert(this is App || _inRenderDirtyComponents); // you should not build the UI tree ahead of time, build it only during build()
  }

39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
  String _key;
  String get key => _key;

  UINode _parent;
  UINode get parent => _parent;

  bool _mounted = false;
  bool _wasMounted = false;
  bool get mounted => _mounted;
  static bool _notifyingMountStatus = false;
  static Set<UINode> _mountedChanged = new HashSet<UINode>();

  void setParent(UINode newParent) {
    assert(!_notifyingMountStatus);
    _parent = newParent;
    if (newParent == null) {
      if (_mounted) {
        _mounted = false;
        _mountedChanged.add(this);
      }
    } else {
      assert(newParent._mounted);
      if (_parent._mounted != _mounted) {
        _mounted = _parent._mounted;
        _mountedChanged.add(this);
      }
    }
  }

  static void _notifyMountStatusChanged() {
    try {
      _notifyingMountStatus = true;
      for (UINode node in _mountedChanged) {
        if (node._wasMounted != node._mounted) {
          if (node._mounted)
            node._didMount();
          else
            node._didUnmount();
          node._wasMounted = node._mounted;
        }
79
      }
80 81 82 83 84 85 86 87 88 89
      _mountedChanged.clear();
    } finally {
      _notifyingMountStatus = false;
    }
  }
  void _didMount() { }
  void _didUnmount() { }

  RenderObject root;

90 91 92 93 94 95 96
  // Subclasses which implements Nodes that become stateful may return true
  // if the |old| node has become stateful and should be retained.
  bool _willSync(UINode old) => false;

  bool get interchangeable => false; // if true, then keys can be duplicated

  void _sync(UINode old, dynamic slot);
H
Hixie 已提交
97
  // 'slot' is the identifier that the parent RenderObjectWrapper uses to know
98 99
  // where to put this descendant

A
Adam Barth 已提交
100
  void remove() {
101
    root = null;
102
    setParent(null);
103 104 105 106 107 108 109 110 111
  }

  UINode findAncestor(Type targetType) {
    var ancestor = _parent;
    while (ancestor != null && !reflectClass(ancestor.runtimeType).isSubtypeOf(reflectClass(targetType)))
      ancestor = ancestor._parent;
    return ancestor;
  }

112
  void removeChild(UINode node) {
A
Adam Barth 已提交
113
    node.remove();
114 115 116
  }

  // Returns the child which should be retained as the child of this node.
117
  UINode syncChild(UINode node, UINode oldNode, dynamic slot) {
118

119
    if (node == oldNode) {
120
      assert(node == null || node.mounted);
121 122 123
      return node; // Nothing to do. Subtrees must be identical.
    }

124 125
    if (node == null) {
      // the child in this slot has gone away
126
      assert(oldNode.mounted);
127
      removeChild(oldNode);
128
      assert(!oldNode.mounted);
129 130
      return null;
    }
131

132 133 134
    if (oldNode != null && node._key == oldNode._key && node._willSync(oldNode)) {
      assert(oldNode.mounted);
      assert(!node.mounted);
135
      oldNode._sync(node, slot);
H
Hixie 已提交
136
      assert(oldNode.root is RenderObject);
137 138 139
      return oldNode;
    }

140 141 142 143
    if (oldNode != null && node._key != oldNode._key) {
      assert(oldNode.mounted);
      removeChild(oldNode);
      oldNode = null;
144 145
    }

146 147 148
    assert(!node.mounted);
    node.setParent(this);
    node._sync(oldNode, slot);
H
Hixie 已提交
149
    assert(node.root is RenderObject);
150 151 152 153 154 155 156 157 158 159 160
    return node;
  }
}

abstract class ContentNode extends UINode {
  UINode content;

  ContentNode(UINode content) : this.content = content, super(key: content._key);

  void _sync(UINode old, dynamic slot) {
    UINode oldContent = old == null ? null : (old as ContentNode).content;
161
    content = syncChild(content, oldContent, slot);
162 163
    assert(content.root != null);
    root = content.root;
164 165
  }

A
Adam Barth 已提交
166
  void remove() {
167
    if (content != null)
168
      removeChild(content);
A
Adam Barth 已提交
169
    super.remove();
170 171 172 173 174 175 176 177 178
  }
}

class ParentDataNode extends ContentNode {
  final ParentData parentData;

  ParentDataNode(UINode content, this.parentData): super(content);
}

179 180 181
typedef void GestureEventListener(sky.GestureEvent e);
typedef void PointerEventListener(sky.PointerEvent e);
typedef void EventListener(sky.Event e);
182 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 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 255 256 257 258 259 260 261 262 263 264 265 266 267

class EventListenerNode extends ContentNode  {
  final Map<String, sky.EventListener> listeners;

  static Map<String, sky.EventListener> _createListeners({
    EventListener onWheel,
    GestureEventListener onGestureFlingCancel,
    GestureEventListener onGestureFlingStart,
    GestureEventListener onGestureScrollStart,
    GestureEventListener onGestureScrollUpdate,
    GestureEventListener onGestureTap,
    GestureEventListener onGestureTapDown,
    PointerEventListener onPointerCancel,
    PointerEventListener onPointerDown,
    PointerEventListener onPointerMove,
    PointerEventListener onPointerUp,
    Map<String, sky.EventListener> custom
  }) {
    var listeners = custom != null ?
        new HashMap<String, sky.EventListener>.from(custom) :
        new HashMap<String, sky.EventListener>();

    if (onWheel != null)
      listeners['wheel'] = onWheel;
    if (onGestureFlingCancel != null)
      listeners['gestureflingcancel'] = onGestureFlingCancel;
    if (onGestureFlingStart != null)
      listeners['gestureflingstart'] = onGestureFlingStart;
    if (onGestureScrollStart != null)
      listeners['gesturescrollstart'] = onGestureScrollStart;
    if (onGestureScrollUpdate != null)
      listeners['gesturescrollupdate'] = onGestureScrollUpdate;
    if (onGestureTap != null)
      listeners['gesturetap'] = onGestureTap;
    if (onGestureTapDown != null)
      listeners['gesturetapdown'] = onGestureTapDown;
    if (onPointerCancel != null)
      listeners['pointercancel'] = onPointerCancel;
    if (onPointerDown != null)
      listeners['pointerdown'] = onPointerDown;
    if (onPointerMove != null)
      listeners['pointermove'] = onPointerMove;
    if (onPointerUp != null)
      listeners['pointerup'] = onPointerUp;

    return listeners;
  }

  EventListenerNode(UINode content, {
    EventListener onWheel,
    GestureEventListener onGestureFlingCancel,
    GestureEventListener onGestureFlingStart,
    GestureEventListener onGestureScrollStart,
    GestureEventListener onGestureScrollUpdate,
    GestureEventListener onGestureTap,
    GestureEventListener onGestureTapDown,
    PointerEventListener onPointerCancel,
    PointerEventListener onPointerDown,
    PointerEventListener onPointerMove,
    PointerEventListener onPointerUp,
    Map<String, sky.EventListener> custom
  }) : listeners = _createListeners(
         onWheel: onWheel,
         onGestureFlingCancel: onGestureFlingCancel,
         onGestureFlingStart: onGestureFlingStart,
         onGestureScrollUpdate: onGestureScrollUpdate,
         onGestureScrollStart: onGestureScrollStart,
         onGestureTap: onGestureTap,
         onGestureTapDown: onGestureTapDown,
         onPointerCancel: onPointerCancel,
         onPointerDown: onPointerDown,
         onPointerMove: onPointerMove,
         onPointerUp: onPointerUp,
         custom: custom
       ),
       super(content);

  void _handleEvent(sky.Event e) {
    sky.EventListener listener = listeners[e.type];
    if (listener != null) {
      listener(e);
    }
  }
}

/*
H
Hixie 已提交
268
 * RenderObjectWrappers correspond to a desired state of a RenderObject.
269
 * They are fully immutable, with one exception: A UINode which is a
270
 * Component which lives within an MultiChildRenderObjectWrapper's
271 272 273
 * children list, may be replaced with the "old" instance if it has
 * become stateful.
 */
H
Hixie 已提交
274
abstract class RenderObjectWrapper extends UINode {
275

H
Hixie 已提交
276 277
  static final Map<RenderObject, RenderObjectWrapper> _nodeMap =
      new HashMap<RenderObject, RenderObjectWrapper>();
278

H
Hixie 已提交
279
  static RenderObjectWrapper _getMounted(RenderObject node) => _nodeMap[node];
280

H
Hixie 已提交
281
  RenderObjectWrapper({
282
    Object key
283 284
  }) : super(key: key);

H
Hixie 已提交
285
  RenderObject createNode();
286

H
Hixie 已提交
287
  void insert(RenderObjectWrapper child, dynamic slot);
288 289

  void _sync(UINode old, dynamic slot) {
290
    assert(parent != null);
291
    if (old == null) {
292 293
      root = createNode();
      assert(root != null);
H
Hixie 已提交
294 295
      var ancestor = findAncestor(RenderObjectWrapper);
      if (ancestor is RenderObjectWrapper)
296 297
        ancestor.insert(this, slot);
    } else {
298
      root = old.root;
299
    }
300 301
    assert(mounted);
    assert(root != null);
302
    _nodeMap[root] = this;
H
Hixie 已提交
303
    syncRenderObject(old);
304 305
  }

H
Hixie 已提交
306
  void syncRenderObject(RenderObjectWrapper old) {
307
    ParentData parentData = null;
308 309 310
    UINode ancestor = parent;
    while (ancestor != null && ancestor is! RenderObjectWrapper) {
      if (ancestor is ParentDataNode && ancestor.parentData != null) {
311
        if (parentData != null)
312
          parentData.merge(ancestor.parentData); // this will throw if the types aren't the same
313
        else
314
          parentData = ancestor.parentData;
315
      }
316
      ancestor = ancestor.parent;
317 318
    }
    if (parentData != null) {
319
      assert(root.parentData != null);
320 321 322
      root.parentData.merge(parentData); // this will throw if the types aren't appropriate
      if (parent.root != null)
        parent.root.markNeedsLayout();
323 324 325
    }
  }

A
Adam Barth 已提交
326
  void remove() {
327 328
    assert(root != null);
    _nodeMap.remove(root);
A
Adam Barth 已提交
329
    super.remove();
330 331 332
  }
}

H
Hixie 已提交
333
abstract class OneChildRenderObjectWrapper extends RenderObjectWrapper {
A
Adam Barth 已提交
334 335
  final UINode child;

H
Hixie 已提交
336
  OneChildRenderObjectWrapper({ this.child, Object key }) : super(key: key);
A
Adam Barth 已提交
337

A
Adam Barth 已提交
338 339 340
  void syncRenderObject(RenderObjectWrapper old) {
    super.syncRenderObject(old);
    UINode oldChild = old == null ? null : (old as OneChildRenderObjectWrapper).child;
H
Hixie 已提交
341 342 343
    syncChild(child, oldChild, null);
  }

H
Hixie 已提交
344
  void insert(RenderObjectWrapper child, dynamic slot) {
345
    final root = this.root; // TODO(ianh): Remove this once the analyzer is cleverer
A
Adam Barth 已提交
346
    assert(slot == null);
347
    assert(root is RenderObjectWithChildMixin);
A
Adam Barth 已提交
348
    root.child = child.root;
349
    assert(root == this.root); // TODO(ianh): Remove this once the analyzer is cleverer
A
Adam Barth 已提交
350 351
  }

H
Hixie 已提交
352
  void removeChild(UINode node) {
353 354
    final root = this.root; // TODO(ianh): Remove this once the analyzer is cleverer
    assert(root is RenderObjectWithChildMixin);
H
Hixie 已提交
355 356
    root.child = null;
    super.removeChild(node);
357
    assert(root == this.root); // TODO(ianh): Remove this once the analyzer is cleverer
A
Adam Barth 已提交
358 359
  }

A
Adam Barth 已提交
360
  void remove() {
H
Hixie 已提交
361 362
    if (child != null)
      removeChild(child);
A
Adam Barth 已提交
363
    super.remove();
A
Adam Barth 已提交
364 365 366
  }
}

367 368 369 370 371 372 373 374 375
class Clip extends OneChildRenderObjectWrapper {
  RenderClip root;

  Clip({ UINode child, Object key })
    : super(child: child, key: key);

  RenderClip createNode() => new RenderClip();
}

H
Hixie 已提交
376
class Padding extends OneChildRenderObjectWrapper {
A
Adam Barth 已提交
377 378 379 380 381 382 383 384
  RenderPadding root;
  final EdgeDims padding;

  Padding({ this.padding, UINode child, Object key })
    : super(child: child, key: key);

  RenderPadding createNode() => new RenderPadding(padding: padding);

H
Hixie 已提交
385 386
  void syncRenderObject(Padding old) {
    super.syncRenderObject(old);
A
Adam Barth 已提交
387 388 389 390
    root.padding = padding;
  }
}

H
Hixie 已提交
391
class DecoratedBox extends OneChildRenderObjectWrapper {
A
Adam Barth 已提交
392 393 394 395 396 397 398 399
  RenderDecoratedBox root;
  final BoxDecoration decoration;

  DecoratedBox({ this.decoration, UINode child, Object key })
    : super(child: child, key: key);

  RenderDecoratedBox createNode() => new RenderDecoratedBox(decoration: decoration);

H
Hixie 已提交
400 401
  void syncRenderObject(DecoratedBox old) {
    super.syncRenderObject(old);
A
Adam Barth 已提交
402 403 404 405
    root.decoration = decoration;
  }
}

H
Hixie 已提交
406
class SizedBox extends OneChildRenderObjectWrapper {
A
Adam Barth 已提交
407
  RenderSizedBox root;
408
  final Size desiredSize;
A
Adam Barth 已提交
409

H
Hixie 已提交
410
  SizedBox({
411 412
    double width: double.INFINITY,
    double height: double.INFINITY,
H
Hixie 已提交
413 414
    UINode child,
    Object key
415
  }) : desiredSize = new Size(width, height), super(child: child, key: key);
A
Adam Barth 已提交
416 417 418

  RenderSizedBox createNode() => new RenderSizedBox(desiredSize: desiredSize);

H
Hixie 已提交
419 420
  void syncRenderObject(SizedBox old) {
    super.syncRenderObject(old);
A
Adam Barth 已提交
421 422 423 424
    root.desiredSize = desiredSize;
  }
}

425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
class ConstrainedBox extends OneChildRenderObjectWrapper {
  RenderConstrainedBox root;
  final BoxConstraints constraints;

  ConstrainedBox({ this.constraints, UINode child, Object key })
    : super(child: child, key: key);

  RenderConstrainedBox createNode() => new RenderConstrainedBox(additionalConstraints: constraints);

  void syncRenderObject(ConstrainedBox old) {
    super.syncRenderObject(old);
    root.additionalConstraints = constraints;
  }
}

H
Hixie 已提交
440
class Transform extends OneChildRenderObjectWrapper {
441 442 443 444 445 446 447 448
  RenderTransform root;
  final Matrix4 transform;

  Transform({ this.transform, UINode child, Object key })
    : super(child: child, key: key);

  RenderTransform createNode() => new RenderTransform(transform: transform);

H
Hixie 已提交
449 450
  void syncRenderObject(Transform old) {
    super.syncRenderObject(old);
451 452 453 454
    root.transform = transform;
  }
}

455 456 457 458 459 460 461 462 463 464 465 466 467 468
class SizeObserver extends OneChildRenderObjectWrapper {
  RenderSizeObserver root;
  final SizeChangedCallback callback;

  SizeObserver({ this.callback, UINode child, Object key })
    : super(child: child, key: key);

  RenderSizeObserver createNode() => new RenderSizeObserver(callback: callback);

  void syncRenderObject(SizeObserver old) {
    super.syncRenderObject(old);
    root.callback = callback;
  }

A
Adam Barth 已提交
469
  void remove() {
470
    root.callback = null;
A
Adam Barth 已提交
471
    super.remove();
472 473 474
  }
}

475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
// TODO(jackson) need a mechanism for marking the RenderCustomPaint as needing paint
class CustomPaint extends OneChildRenderObjectWrapper {
  RenderCustomPaint root;
  final CustomPaintCallback callback;

  CustomPaint({ this.callback, UINode child, Object key })
    : super(child: child, key: key);

  RenderCustomPaint createNode() => new RenderCustomPaint(callback: callback);

  void syncRenderObject(CustomPaint old) {
    super.syncRenderObject(old);
    root.callback = callback;
  }

A
Adam Barth 已提交
490
  void remove() {
491
    root.callback = null;
A
Adam Barth 已提交
492
    super.remove();
493 494
  }
}
495

496 497
final List<UINode> _emptyList = new List<UINode>();

498
abstract class MultiChildRenderObjectWrapper extends RenderObjectWrapper {
499

500
  // In MultiChildRenderObjectWrapper subclasses, slots are RenderObject nodes
H
Hixie 已提交
501
  // to use as the "insert before" sibling in ContainerRenderObjectMixin.add() calls
502 503 504

  final List<UINode> children;

505
  MultiChildRenderObjectWrapper({
506
    Object key,
507
    List<UINode> children
508 509
  }) : this.children = children == null ? _emptyList : children,
  super(
510
    key: key
511 512 513 514
  ) {
    assert(!_debugHasDuplicateIds());
  }

H
Hixie 已提交
515
  void insert(RenderObjectWrapper child, dynamic slot) {
516
    final root = this.root; // TODO(ianh): Remove this once the analyzer is cleverer
H
Hixie 已提交
517
    assert(slot == null || slot is RenderObject);
518
    assert(root is ContainerRenderObjectMixin);
519
    root.add(child.root, before: slot);
520
    assert(root == this.root); // TODO(ianh): Remove this once the analyzer is cleverer
521 522
  }

H
Hixie 已提交
523
  void removeChild(UINode node) {
524
    final root = this.root; // TODO(ianh): Remove this once the analyzer is cleverer
A
Adam Barth 已提交
525
    assert(root is ContainerRenderObjectMixin);
H
Hixie 已提交
526 527
    root.remove(node.root);
    super.removeChild(node);
528
    assert(root == this.root); // TODO(ianh): Remove this once the analyzer is cleverer
H
Hixie 已提交
529 530
  }

A
Adam Barth 已提交
531
  void remove() {
532 533 534
    assert(children != null);
    for (var child in children) {
      assert(child != null);
535
      removeChild(child);
536
    }
A
Adam Barth 已提交
537
    super.remove();
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
  }

  bool _debugHasDuplicateIds() {
    var idSet = new HashSet<String>();
    for (var child in children) {
      assert(child != null);
      if (child.interchangeable)
        continue; // when these nodes are reordered, we just reassign the data

      if (!idSet.add(child._key)) {
        throw '''If multiple non-interchangeable nodes of the same type exist as children
                of another node, they must have unique keys.
                Duplicate: "${child._key}"''';
      }
    }
    return false;
  }

556
  void syncRenderObject(MultiChildRenderObjectWrapper old) {
H
Hixie 已提交
557
    super.syncRenderObject(old);
558

559
    final root = this.root; // TODO(ianh): Remove this once the analyzer is cleverer
H
Hixie 已提交
560
    if (root is! ContainerRenderObjectMixin)
561 562 563 564 565
      return;

    var startIndex = 0;
    var endIndex = children.length;

566
    var oldChildren = old == null ? [] : old.children;
567 568 569
    var oldStartIndex = 0;
    var oldEndIndex = oldChildren.length;

H
Hixie 已提交
570
    RenderObject nextSibling = null;
571 572 573 574
    UINode currentNode = null;
    UINode oldNode = null;

    void sync(int atIndex) {
575
      children[atIndex] = syncChild(currentNode, oldNode, nextSibling);
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
      assert(children[atIndex] != null);
    }

    // Scan backwards from end of list while nodes can be directly synced
    // without reordering.
    while (endIndex > startIndex && oldEndIndex > oldStartIndex) {
      currentNode = children[endIndex - 1];
      oldNode = oldChildren[oldEndIndex - 1];

      if (currentNode._key != oldNode._key) {
        break;
      }

      endIndex--;
      oldEndIndex--;
      sync(endIndex);
    }

    HashMap<String, UINode> oldNodeIdMap = null;

    bool oldNodeReordered(String key) {
      return oldNodeIdMap != null &&
             oldNodeIdMap.containsKey(key) &&
             oldNodeIdMap[key] == null;
    }

    void advanceOldStartIndex() {
      oldStartIndex++;
      while (oldStartIndex < oldEndIndex &&
             oldNodeReordered(oldChildren[oldStartIndex]._key)) {
        oldStartIndex++;
      }
    }

    void ensureOldIdMap() {
      if (oldNodeIdMap != null)
        return;

      oldNodeIdMap = new HashMap<String, UINode>();
      for (int i = oldStartIndex; i < oldEndIndex; i++) {
        var node = oldChildren[i];
        if (!node.interchangeable)
          oldNodeIdMap.putIfAbsent(node._key, () => node);
      }
    }

    bool searchForOldNode() {
      if (currentNode.interchangeable)
        return false; // never re-order these nodes

      ensureOldIdMap();
      oldNode = oldNodeIdMap[currentNode._key];
      if (oldNode == null)
        return false;

      oldNodeIdMap[currentNode._key] = null; // mark it reordered
H
Hixie 已提交
632
      assert(root is ContainerRenderObjectMixin);
633 634
      assert(old.root is ContainerRenderObjectMixin);
      assert(oldNode.root != null);
635

636
      (old.root as ContainerRenderObjectMixin).remove(oldNode.root); // TODO(ianh): Remove cast once the analyzer is cleverer
637
      root.add(oldNode.root, before: nextSibling);
638 639 640 641 642

      return true;
    }

    // Scan forwards, this time we may re-order;
643
    nextSibling = root.firstChild;
644 645 646 647 648 649
    while (startIndex < endIndex && oldStartIndex < oldEndIndex) {
      currentNode = children[startIndex];
      oldNode = oldChildren[oldStartIndex];

      if (currentNode._key == oldNode._key) {
        assert(currentNode.runtimeType == oldNode.runtimeType);
650
        nextSibling = root.childAfter(nextSibling);
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
        sync(startIndex);
        startIndex++;
        advanceOldStartIndex();
        continue;
      }

      oldNode = null;
      searchForOldNode();
      sync(startIndex);
      startIndex++;
    }

    // New insertions
    oldNode = null;
    while (startIndex < endIndex) {
      currentNode = children[startIndex];
      sync(startIndex);
      startIndex++;
    }

    // Removals
    currentNode = null;
    while (oldStartIndex < oldEndIndex) {
      oldNode = oldChildren[oldStartIndex];
675
      removeChild(oldNode);
676 677
      advanceOldStartIndex();
    }
678 679

    assert(root == this.root); // TODO(ianh): Remove this once the analyzer is cleverer
680 681 682
  }
}

683
class BlockContainer extends MultiChildRenderObjectWrapper {
A
Adam Barth 已提交
684 685
  RenderBlock root;
  RenderBlock createNode() => new RenderBlock();
686

687 688
  BlockContainer({ Object key, List<UINode> children })
    : super(key: key, children: children);
689 690
}

691
class StackContainer extends MultiChildRenderObjectWrapper {
A
Adam Barth 已提交
692 693 694 695 696 697 698
  RenderStack root;
  RenderStack createNode() => new RenderStack();

  StackContainer({ Object key, List<UINode> children })
    : super(key: key, children: children);
}

H
Hixie 已提交
699
class Paragraph extends RenderObjectWrapper {
700
  RenderParagraph root;
701
  RenderParagraph createNode() => new RenderParagraph(text: text);
702

703
  final String text;
704

705
  Paragraph({ Object key, this.text }) : super(key: key);
706

H
Hixie 已提交
707 708
  void syncRenderObject(UINode old) {
    super.syncRenderObject(old);
709 710
    root.text = text;
  }
711 712 713 714 715

  void insert(RenderObjectWrapper child, dynamic slot) {
    assert(false);
    // Paragraph does not support having children currently
  }
716 717
}

718
class FlexContainer extends MultiChildRenderObjectWrapper {
719
  RenderFlex root;
720
  RenderFlex createNode() => new RenderFlex(direction: this.direction);
721 722

  final FlexDirection direction;
723
  final FlexJustifyContent justifyContent;
724 725 726 727

  FlexContainer({
    Object key,
    List<UINode> children,
728 729
    this.direction: FlexDirection.horizontal,
    this.justifyContent: FlexJustifyContent.flexStart
730
  }) : super(key: key, children: children);
731

H
Hixie 已提交
732 733
  void syncRenderObject(UINode old) {
    super.syncRenderObject(old);
734
    root.direction = direction;
735
    root.justifyContent = justifyContent;
736 737 738
  }
}

739
class FlexExpandingChild extends ParentDataNode {
740 741
  FlexExpandingChild(UINode content, [int flex = 1])
    : super(content, new FlexBoxParentData()..flex = flex);
A
Adam Barth 已提交
742 743
}

H
Hixie 已提交
744
class Image extends RenderObjectWrapper {
745 746
  RenderImage root;
  RenderImage createNode() => new RenderImage(this.src, this.size);
747 748

  final String src;
749
  final Size size;
750 751 752

  Image({
    Object key,
753 754
    this.src,
    this.size
755
  }) : super(key: key);
756

H
Hixie 已提交
757 758
  void syncRenderObject(UINode old) {
    super.syncRenderObject(old);
759 760
    root.src = src;
    root.requestedSize = size;
761
  }
762 763 764 765 766

  void insert(RenderObjectWrapper child, dynamic slot) {
    assert(false);
    // Image does not support having children currently
  }
767 768 769 770 771 772 773
}

List<Component> _dirtyComponents = new List<Component>();
bool _buildScheduled = false;
bool _inRenderDirtyComponents = false;

void _buildDirtyComponents() {
774
  //_tracing.begin('fn::_buildDirtyComponents');
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793

  Stopwatch sw;
  if (_shouldLogRenderDuration)
    sw = new Stopwatch()..start();

  try {
    _inRenderDirtyComponents = true;

    _dirtyComponents.sort((a, b) => a._order - b._order);
    for (var comp in _dirtyComponents) {
      comp._buildIfDirty();
    }

    _dirtyComponents.clear();
    _buildScheduled = false;
  } finally {
    _inRenderDirtyComponents = false;
  }

794
  UINode._notifyMountStatusChanged();
795 796 797 798 799 800

  if (_shouldLogRenderDuration) {
    sw.stop();
    print('Render took ${sw.elapsedMicroseconds} microseconds');
  }

801
  //_tracing.end('fn::_buildDirtyComponents');
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
}

void _scheduleComponentForRender(Component c) {
  assert(!_inRenderDirtyComponents);
  _dirtyComponents.add(c);

  if (!_buildScheduled) {
    _buildScheduled = true;
    new Future.microtask(_buildDirtyComponents);
  }
}

abstract class Component extends UINode {
  bool get _isBuilding => _currentlyBuilding == this;
  bool _dirty = true;

  UINode _built;
  final int _order;
  static int _currentOrder = 0;
  bool _stateful;
  static Component _currentlyBuilding;
  List<Function> _mountCallbacks;
  List<Function> _unmountCallbacks;
  dynamic _slot; // cached slot from the last time we were synced

  void onDidMount(Function fn) {
    if (_mountCallbacks == null)
      _mountCallbacks = new List<Function>();

    _mountCallbacks.add(fn);
  }

  void onDidUnmount(Function fn) {
    if (_unmountCallbacks == null)
      _unmountCallbacks = new List<Function>();

    _unmountCallbacks.add(fn);
  }

  Component({ Object key, bool stateful })
      : _stateful = stateful != null ? stateful : false,
        _order = _currentOrder + 1,
        super(key: key);

  Component.fromArgs(Object key, bool stateful)
      : this(key: key, stateful: stateful);

  void _didMount() {
850
    super._didMount();
851
    if (_mountCallbacks != null)
852 853
      for (Function fn in _mountCallbacks)
        fn();
854 855 856
  }

  void _didUnmount() {
857
    super._didUnmount();
858
    if (_unmountCallbacks != null)
859 860
      for (Function fn in _unmountCallbacks)
        fn();
861 862 863 864
  }

  // TODO(rafaelw): It seems wrong to expose DOM at all. This is presently
  // needed to get sizing info.
H
Hixie 已提交
865
  RenderObject getRoot() => root;
866

A
Adam Barth 已提交
867
  void remove() {
868
    assert(_built != null);
869 870
    assert(root != null);
    removeChild(_built);
871
    _built = null;
A
Adam Barth 已提交
872
    super.remove();
873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
  }

  bool _willSync(UINode old) {
    Component oldComponent = old as Component;
    if (oldComponent == null || !oldComponent._stateful)
      return false;

    // Make |this| the "old" Component
    _stateful = false;
    _built = oldComponent._built;
    assert(_built != null);

    // Make |oldComponent| the "new" component
    reflect.copyPublicFields(this, oldComponent);
    oldComponent._built = null;
    oldComponent._dirty = true;
    return true;
  }

  /* There are three cases here:
   * 1) Building for the first time:
   *      assert(_built == null && old == null)
   * 2) Re-building (because a dirty flag got set):
   *      assert(_built != null && old == null)
   * 3) Syncing against an old version
   *      assert(_built == null && old != null)
   */
  void _sync(UINode old, dynamic slot) {
    assert(_built == null || old == null);

    Component oldComponent = old as Component;

    _slot = slot;

    var oldBuilt;
    if (oldComponent == null) {
      oldBuilt = _built;
    } else {
      assert(_built == null);
      oldBuilt = oldComponent._built;
    }

    int lastOrder = _currentOrder;
    _currentOrder = _order;
    _currentlyBuilding = this;
    _built = build();
919
    assert(_built != null);
920 921 922
    _currentlyBuilding = null;
    _currentOrder = lastOrder;

923
    _built = syncChild(_built, oldBuilt, slot);
924
    assert(_built != null);
925
    _dirty = false;
926 927
    root = _built.root;
    assert(root != null);
928 929 930
  }

  void _buildIfDirty() {
931
    if (!_dirty || !_mounted)
932 933
      return;

934
    assert(root != null);
935 936 937 938 939 940 941 942 943 944
    _sync(null, _slot);
  }

  void scheduleBuild() {
    setState(() {});
  }

  void setState(Function fn()) {
    _stateful = true;
    fn();
945
    if (_isBuilding || _dirty || !_mounted)
946 947 948 949 950 951 952 953 954
      return;

    _dirty = true;
    _scheduleComponentForRender(this);
  }

  UINode build();
}

A
Adam Barth 已提交
955 956
class Container extends Component {
  final UINode child;
957
  final BoxConstraints constraints;
A
Adam Barth 已提交
958
  final BoxDecoration decoration;
959
  final EdgeDims margin;
A
Adam Barth 已提交
960
  final EdgeDims padding;
961
  final Matrix4 transform;
962 963
  final double width;
  final double height;
A
Adam Barth 已提交
964 965 966 967

  Container({
    Object key,
    this.child,
968
    this.constraints,
A
Adam Barth 已提交
969
    this.decoration,
970 971
    this.width,
    this.height,
972 973 974
    this.margin,
    this.padding,
    this.transform
A
Adam Barth 已提交
975 976 977 978 979
  }) : super(key: key);

  UINode build() {
    UINode current = child;

980 981 982
    if (child == null && width == null && height == null)
      current = new SizedBox();

A
Adam Barth 已提交
983 984 985 986 987 988
    if (padding != null)
      current = new Padding(padding: padding, child: current);

    if (decoration != null)
      current = new DecoratedBox(decoration: decoration, child: current);

989 990 991 992 993 994
    if (width != null || height != null)
      current = new SizedBox(
        width: width == null ? double.INFINITY : width,
        height: height == null ? double.INFINITY : height,
        child: current
      );
A
Adam Barth 已提交
995

996
    if (constraints != null)
997
      current = new ConstrainedBox(constraints: constraints, child: current);
998

A
Adam Barth 已提交
999 1000 1001
    if (margin != null)
      current = new Padding(padding: margin, child: current);

A
Adam Barth 已提交
1002 1003 1004
    if (transform != null)
      current = new Transform(transform: transform, child: current);

A
Adam Barth 已提交
1005 1006 1007 1008
    return current;
  }
}

1009 1010 1011
class _AppView extends AppView {
  _AppView() : super(null);

A
Adam Barth 已提交
1012 1013
  void dispatchEvent(sky.Event event, HitTestResult result) {
    super.dispatchEvent(event, result);
1014

H
Hixie 已提交
1015
    UINode target = RenderObjectWrapper._getMounted(result.path.first);
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025

    // TODO(rafaelw): StopPropagation?
    while (target != null) {
      if (target is EventListenerNode)
        target._handleEvent(event);
      target = target._parent;
    }
  }
}

1026 1027 1028
abstract class App extends Component {

  App() : super(stateful: true) {
1029
    _appView = new _AppView();
1030
    _scheduleComponentForRender(this);
1031
    _mounted = true;
1032 1033
  }

1034
  AppView _appView;
1035
  AppView get appView => _appView;
1036

1037 1038
  void _buildIfDirty() {
    assert(_dirty);
1039
    assert(_mounted);
1040
    _sync(null, null);
1041
    if (root.parent == null)
1042 1043
      _appView.root = root;
    assert(root.parent is RenderView);
1044 1045 1046 1047 1048 1049 1050
  }
}

class Text extends Component {
  Text(this.data) : super(key: '*text*');
  final String data;
  bool get interchangeable => true;
1051
  UINode build() => new Paragraph(text: data);
1052
}