fn2.dart 27.8 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 411 412 413 414
  SizedBox({
    this.desiredSize: sky.Size.infinite,
    UINode child,
    Object key
  }) : super(child: child, key: key);
A
Adam Barth 已提交
415 416 417

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

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

424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
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 已提交
439
class Transform extends OneChildRenderObjectWrapper {
440 441 442 443 444 445 446 447
  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 已提交
448 449
  void syncRenderObject(Transform old) {
    super.syncRenderObject(old);
450 451 452 453
    root.transform = transform;
  }
}

454 455 456 457 458 459 460 461 462 463 464 465 466 467
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 已提交
468
  void remove() {
469
    root.callback = null;
A
Adam Barth 已提交
470
    super.remove();
471 472 473
  }
}

474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
// 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 已提交
489
  void remove() {
490
    root.callback = null;
A
Adam Barth 已提交
491
    super.remove();
492 493
  }
}
494

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

497
abstract class MultiChildRenderObjectWrapper extends RenderObjectWrapper {
498

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

  final List<UINode> children;

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

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

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

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

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

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

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

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

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

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

    void sync(int atIndex) {
574
      children[atIndex] = syncChild(currentNode, oldNode, nextSibling);
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 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
      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 已提交
631
      assert(root is ContainerRenderObjectMixin);
632 633
      assert(old.root is ContainerRenderObjectMixin);
      assert(oldNode.root != null);
634

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

      return true;
    }

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

      if (currentNode._key == oldNode._key) {
        assert(currentNode.runtimeType == oldNode.runtimeType);
649
        nextSibling = root.childAfter(nextSibling);
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
        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];
674
      removeChild(oldNode);
675 676
      advanceOldStartIndex();
    }
677 678

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

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

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

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

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

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

702
  final String text;
703

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

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

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

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

  final FlexDirection direction;

  FlexContainer({
    Object key,
    List<UINode> children,
726
    this.direction: FlexDirection.horizontal
727
  }) : super(key: key, children: children);
728

H
Hixie 已提交
729 730
  void syncRenderObject(UINode old) {
    super.syncRenderObject(old);
731
    root.direction = direction;
732 733 734
  }
}

735
class FlexExpandingChild extends ParentDataNode {
736 737
  FlexExpandingChild(UINode content, [int flex = 1])
    : super(content, new FlexBoxParentData()..flex = flex);
A
Adam Barth 已提交
738 739
}

H
Hixie 已提交
740
class Image extends RenderObjectWrapper {
741 742
  RenderImage root;
  RenderImage createNode() => new RenderImage(this.src, this.size);
743 744

  final String src;
745
  final Size size;
746 747 748

  Image({
    Object key,
749 750
    this.src,
    this.size
751
  }) : super(key: key);
752

H
Hixie 已提交
753 754
  void syncRenderObject(UINode old) {
    super.syncRenderObject(old);
755 756
    root.src = src;
    root.requestedSize = size;
757
  }
758 759 760 761 762

  void insert(RenderObjectWrapper child, dynamic slot) {
    assert(false);
    // Image does not support having children currently
  }
763 764 765 766 767 768 769
}

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

void _buildDirtyComponents() {
770
  //_tracing.begin('fn::_buildDirtyComponents');
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789

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

790
  UINode._notifyMountStatusChanged();
791 792 793 794 795 796

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

797
  //_tracing.end('fn::_buildDirtyComponents');
798 799 800 801 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
}

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() {
846
    super._didMount();
847
    if (_mountCallbacks != null)
848 849
      for (Function fn in _mountCallbacks)
        fn();
850 851 852
  }

  void _didUnmount() {
853
    super._didUnmount();
854
    if (_unmountCallbacks != null)
855 856
      for (Function fn in _unmountCallbacks)
        fn();
857 858 859 860
  }

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

A
Adam Barth 已提交
863
  void remove() {
864
    assert(_built != null);
865 866
    assert(root != null);
    removeChild(_built);
867
    _built = null;
A
Adam Barth 已提交
868
    super.remove();
869 870 871 872 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
  }

  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();
915
    assert(_built != null);
916 917 918
    _currentlyBuilding = null;
    _currentOrder = lastOrder;

919
    _built = syncChild(_built, oldBuilt, slot);
920
    assert(_built != null);
921
    _dirty = false;
922 923
    root = _built.root;
    assert(root != null);
924 925 926
  }

  void _buildIfDirty() {
927
    if (!_dirty || !_mounted)
928 929
      return;

930
    assert(root != null);
931 932 933 934 935 936 937 938 939 940
    _sync(null, _slot);
  }

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

  void setState(Function fn()) {
    _stateful = true;
    fn();
941
    if (_isBuilding || _dirty || !_mounted)
942 943 944 945 946 947 948 949 950
      return;

    _dirty = true;
    _scheduleComponentForRender(this);
  }

  UINode build();
}

A
Adam Barth 已提交
951 952
class Container extends Component {
  final UINode child;
953
  final BoxConstraints constraints;
A
Adam Barth 已提交
954
  final BoxDecoration decoration;
955
  final EdgeDims margin;
A
Adam Barth 已提交
956
  final EdgeDims padding;
957 958
  final Matrix4 transform;
  final Size desiredSize;
A
Adam Barth 已提交
959 960 961 962

  Container({
    Object key,
    this.child,
963
    this.constraints,
A
Adam Barth 已提交
964 965
    this.decoration,
    this.desiredSize,
966 967 968
    this.margin,
    this.padding,
    this.transform
A
Adam Barth 已提交
969 970 971 972 973 974 975 976 977 978 979 980 981 982
  }) : super(key: key);

  UINode build() {
    UINode current = child;

    if (padding != null)
      current = new Padding(padding: padding, child: current);

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

    if (desiredSize != null)
      current = new SizedBox(desiredSize: desiredSize, child: current);

983 984 985
    if (constraints != null)
      current = new ConstrainedBox(constraints: constraints);

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

A
Adam Barth 已提交
989 990 991
    if (transform != null)
      current = new Transform(transform: transform, child: current);

H
Hixie 已提交
992 993 994
    if (current == null)
      current = new SizedBox();

A
Adam Barth 已提交
995 996 997 998
    return current;
  }
}

999 1000 1001
class _AppView extends AppView {
  _AppView() : super(null);

A
Adam Barth 已提交
1002 1003
  void dispatchEvent(sky.Event event, HitTestResult result) {
    super.dispatchEvent(event, result);
1004

H
Hixie 已提交
1005
    UINode target = RenderObjectWrapper._getMounted(result.path.first);
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015

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

1016 1017 1018
abstract class App extends Component {

  App() : super(stateful: true) {
1019
    _appView = new _AppView();
1020
    _scheduleComponentForRender(this);
1021
    _mounted = true;
1022 1023
  }

1024
  AppView _appView;
1025
  AppView get appView => _appView;
1026

1027 1028
  void _buildIfDirty() {
    assert(_dirty);
1029
    assert(_mounted);
1030
    _sync(null, null);
1031
    if (root.parent == null)
1032 1033
      _appView.root = root;
    assert(root.parent is RenderView);
1034 1035 1036 1037 1038 1039 1040
  }
}

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