ui_node.dart 23.7 KB
Newer Older
1 2 3 4 5 6 7 8
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';
import 'dart:collection';
import 'dart:mirrors';
import 'dart:sky' as sky;
9 10 11 12 13 14 15 16 17

import '../app.dart';
import '../rendering/box.dart';
import '../rendering/object.dart';

export '../rendering/box.dart' show BoxConstraints, BoxDecoration, Border, BorderSide, EdgeDims;
export '../rendering/flex.dart' show FlexDirection;
export '../rendering/object.dart' show Point, Size, Rect, Color, Paint, Path;

18

19
// final sky.Tracing _tracing = sky.window.tracing;
20 21 22 23 24 25 26 27 28 29 30 31 32 33

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()
  }

34 35 36 37 38 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
  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)
69
            node.didMount();
70
          else
71
            node.didUnmount();
72 73
          node._wasMounted = node._mounted;
        }
74
      }
75 76 77 78 79
      _mountedChanged.clear();
    } finally {
      _notifyingMountStatus = false;
    }
  }
80 81
  void didMount() { }
  void didUnmount() { }
82

83 84
  RenderObject _root;
  RenderObject get root => _root;
85

86 87
  // Subclasses which implements Nodes that become stateful may return true
  // if the |old| node has become stateful and should be retained.
88 89 90
  // This is called immediately before _sync().
  // Component._retainStatefulNodeIfPossible() calls syncFields().
  bool _retainStatefulNodeIfPossible(UINode old) => false;
91 92 93 94

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

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

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

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

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

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

117 118
    assert(oldNode is! Component || !oldNode._disqualifiedFromEverAppearingAgain);

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
    if (oldNode != null && node._key == oldNode._key && node._retainStatefulNodeIfPossible(oldNode)) {
133 134
      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
    return node;
  }
}

154

155 156 157 158
// Descendants of TagNode provide a way to tag RenderObjectWrapper and
// Component nodes with annotations, such as event listeners,
// stylistic information, etc.
abstract class TagNode extends UINode {
159

160
  TagNode(UINode content, { Object key }) : this.content = content, super(key: key);
161

H
Hixie 已提交
162 163
  UINode content;

164
  void _sync(UINode old, dynamic slot) {
165
    UINode oldContent = old == null ? null : (old as TagNode).content;
166
    content = syncChild(content, oldContent, slot);
167
    assert(content.root != null);
168 169
    _root = content.root;
    assert(_root == root); // in case a subclass reintroduces it
170 171
  }

A
Adam Barth 已提交
172
  void remove() {
173
    if (content != null)
174
      removeChild(content);
A
Adam Barth 已提交
175
    super.remove();
176
  }
H
Hixie 已提交
177

178 179
}

180
class ParentDataNode extends TagNode {
181
  ParentDataNode(UINode content, this.parentData, { Object key }): super(content, key: key);
H
Hixie 已提交
182
  final ParentData parentData;
183 184
}

185 186 187
typedef void GestureEventListener(sky.GestureEvent e);
typedef void PointerEventListener(sky.PointerEvent e);
typedef void EventListener(sky.Event e);
188

189
class EventListenerNode extends TagNode  {
H
Hixie 已提交
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

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

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 268 269 270 271
  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;
  }

  void _handleEvent(sky.Event e) {
    sky.EventListener listener = listeners[e.type];
    if (listener != null) {
      listener(e);
    }
  }
H
Hixie 已提交
272

273 274
}

275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 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 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458

abstract class Component extends UINode {

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

  static Component _currentlyBuilding;
  bool get _isBuilding => _currentlyBuilding == this;

  bool _stateful;
  bool _dirty = true;
  bool _disqualifiedFromEverAppearingAgain = false;

  UINode _built;
  dynamic _slot; // cached slot from the last time we were synced

  void didMount() {
    assert(!_disqualifiedFromEverAppearingAgain);
    super.didMount();
  }

  void remove() {
    assert(_built != null);
    assert(root != null);
    removeChild(_built);
    _built = null;
    super.remove();
  }

  bool _retainStatefulNodeIfPossible(UINode old) {
    assert(!_disqualifiedFromEverAppearingAgain);

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

    assert(key == oldComponent.key);

    // Make |this|, the newly-created object, into the "old" Component, and kill it
    _stateful = false;
    _built = oldComponent._built;
    assert(_built != null);
    _disqualifiedFromEverAppearingAgain = true;

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

  // This is called by _retainStatefulNodeIfPossible(), during
  // syncChild(), just before _sync() is called.
  // This must be implemented on any subclass that can become stateful
  // (but don't call super.syncFields() if you inherit directly from
  // Component, since that'll fire an assert).
  // If you don't ever become stateful, then don't override this.
  void syncFields(Component source) {
    assert(false);
  }

  final int _order;
  static int _currentOrder = 0;

  /* 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);
    assert(!_disqualifiedFromEverAppearingAgain);

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

    _built = syncChild(_built, oldBuilt, slot);
    assert(_built != null);
    _dirty = false;
    _root = _built.root;
    assert(_root == root); // in case a subclass reintroduces it
    assert(root != null);
  }

  void _buildIfDirty() {
    assert(!_disqualifiedFromEverAppearingAgain);
    if (!_dirty || !_mounted)
      return;

    assert(root != null);
    _sync(null, _slot);
  }

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

  void setState(Function fn()) {
    assert(!_disqualifiedFromEverAppearingAgain);
    _stateful = true;
    fn();
    if (_isBuilding || _dirty || !_mounted)
      return;

    _dirty = true;
    _scheduleComponentForRender(this);
  }

  UINode build();

}

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

void _buildDirtyComponents() {
  //_tracing.begin('fn::_buildDirtyComponents');

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

  try {
    _inRenderDirtyComponents = true;

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

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

  UINode._notifyMountStatusChanged();

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

  //_tracing.end('fn::_buildDirtyComponents');
}

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

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


459
/*
H
Hixie 已提交
460
 * RenderObjectWrappers correspond to a desired state of a RenderObject.
461
 * They are fully immutable, with one exception: A UINode which is a
462
 * Component which lives within an MultiChildRenderObjectWrapper's
463 464 465
 * children list, may be replaced with the "old" instance if it has
 * become stateful.
 */
H
Hixie 已提交
466
abstract class RenderObjectWrapper extends UINode {
467

H
Hixie 已提交
468
  RenderObjectWrapper({
469
    Object key
470 471
  }) : super(key: key);

H
Hixie 已提交
472
  RenderObject createNode();
473

H
Hixie 已提交
474
  void insert(RenderObjectWrapper child, dynamic slot);
475

H
Hixie 已提交
476 477 478 479 480
  static final Map<RenderObject, RenderObjectWrapper> _nodeMap =
      new HashMap<RenderObject, RenderObjectWrapper>();

  static RenderObjectWrapper _getMounted(RenderObject node) => _nodeMap[node];

481
  void _sync(UINode old, dynamic slot) {
482
    assert(parent != null);
483
    if (old == null) {
484
      _root = createNode();
H
Hixie 已提交
485 486
      var ancestor = findAncestor(RenderObjectWrapper);
      if (ancestor is RenderObjectWrapper)
487 488
        ancestor.insert(this, slot);
    } else {
489
      _root = old.root;
490
    }
491
    assert(_root == root); // in case a subclass reintroduces it
492
    assert(root != null);
493
    assert(mounted);
494
    _nodeMap[root] = this;
H
Hixie 已提交
495
    syncRenderObject(old);
496 497
  }

H
Hixie 已提交
498
  void syncRenderObject(RenderObjectWrapper old) {
499
    ParentData parentData = null;
500 501 502
    UINode ancestor = parent;
    while (ancestor != null && ancestor is! RenderObjectWrapper) {
      if (ancestor is ParentDataNode && ancestor.parentData != null) {
503
        if (parentData != null)
504
          parentData.merge(ancestor.parentData); // this will throw if the types aren't the same
505
        else
506
          parentData = ancestor.parentData;
507
      }
508
      ancestor = ancestor.parent;
509 510
    }
    if (parentData != null) {
511
      assert(root.parentData != null);
512 513 514
      root.parentData.merge(parentData); // this will throw if the types aren't appropriate
      if (parent.root != null)
        parent.root.markNeedsLayout();
515 516 517
    }
  }

A
Adam Barth 已提交
518
  void remove() {
519 520
    assert(root != null);
    _nodeMap.remove(root);
A
Adam Barth 已提交
521
    super.remove();
522 523 524
  }
}

H
Hixie 已提交
525
abstract class OneChildRenderObjectWrapper extends RenderObjectWrapper {
A
Adam Barth 已提交
526

527
  OneChildRenderObjectWrapper({ UINode child, Object key }) : _child = child, super(key: key);
A
Adam Barth 已提交
528

H
Hixie 已提交
529 530 531
  UINode _child;
  UINode get child => _child;

A
Adam Barth 已提交
532 533 534
  void syncRenderObject(RenderObjectWrapper old) {
    super.syncRenderObject(old);
    UINode oldChild = old == null ? null : (old as OneChildRenderObjectWrapper).child;
535
    _child = syncChild(child, oldChild, null);
H
Hixie 已提交
536 537
  }

H
Hixie 已提交
538
  void insert(RenderObjectWrapper child, dynamic slot) {
539
    final root = this.root; // TODO(ianh): Remove this once the analyzer is cleverer
A
Adam Barth 已提交
540
    assert(slot == null);
541
    assert(root is RenderObjectWithChildMixin);
A
Adam Barth 已提交
542
    root.child = child.root;
543
    assert(root == this.root); // TODO(ianh): Remove this once the analyzer is cleverer
A
Adam Barth 已提交
544 545
  }

H
Hixie 已提交
546
  void removeChild(UINode node) {
547 548
    final root = this.root; // TODO(ianh): Remove this once the analyzer is cleverer
    assert(root is RenderObjectWithChildMixin);
H
Hixie 已提交
549 550
    root.child = null;
    super.removeChild(node);
551
    assert(root == this.root); // TODO(ianh): Remove this once the analyzer is cleverer
A
Adam Barth 已提交
552 553
  }

A
Adam Barth 已提交
554
  void remove() {
H
Hixie 已提交
555 556
    if (child != null)
      removeChild(child);
A
Adam Barth 已提交
557
    super.remove();
A
Adam Barth 已提交
558
  }
H
Hixie 已提交
559

A
Adam Barth 已提交
560 561
}

562
abstract class MultiChildRenderObjectWrapper extends RenderObjectWrapper {
A
Adam Barth 已提交
563

564 565
  // In MultiChildRenderObjectWrapper subclasses, slots are RenderObject nodes
  // to use as the "insert before" sibling in ContainerRenderObjectMixin.add() calls
A
Adam Barth 已提交
566

567 568 569 570 571 572
  MultiChildRenderObjectWrapper({
    Object key,
    List<UINode> children
  }) : this.children = children == null ? const [] : children,
       super(key: key) {
    assert(!_debugHasDuplicateIds());
A
Adam Barth 已提交
573
  }
574

575
  final List<UINode> children;
H
Hixie 已提交
576

577 578 579 580 581 582 583
  void insert(RenderObjectWrapper child, dynamic slot) {
    final root = this.root; // TODO(ianh): Remove this once the analyzer is cleverer
    assert(slot == null || slot is RenderObject);
    assert(root is ContainerRenderObjectMixin);
    root.add(child.root, before: slot);
    assert(root == this.root); // TODO(ianh): Remove this once the analyzer is cleverer
  }
584

585 586 587 588 589 590 591 592
  void removeChild(UINode node) {
    final root = this.root; // TODO(ianh): Remove this once the analyzer is cleverer
    assert(root is ContainerRenderObjectMixin);
    assert(node.root.parent == root);
    root.remove(node.root);
    super.removeChild(node);
    assert(root == this.root); // TODO(ianh): Remove this once the analyzer is cleverer
  }
A
Adam Barth 已提交
593

594 595 596 597 598 599 600 601
  void remove() {
    assert(children != null);
    for (var child in children) {
      assert(child != null);
      removeChild(child);
    }
    super.remove();
  }
A
Adam Barth 已提交
602

603 604 605 606 607 608
  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
H
Hixie 已提交
609

610 611 612 613 614 615 616 617
      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;
  }
A
Adam Barth 已提交
618

619
  void syncRenderObject(MultiChildRenderObjectWrapper old) {
H
Hixie 已提交
620
    super.syncRenderObject(old);
H
Hixie 已提交
621

622 623 624
    final root = this.root; // TODO(ianh): Remove this once the analyzer is cleverer
    if (root is! ContainerRenderObjectMixin)
      return;
A
Adam Barth 已提交
625

626 627
    var startIndex = 0;
    var endIndex = children.length;
A
Adam Barth 已提交
628

629 630 631
    var oldChildren = old == null ? [] : old.children;
    var oldStartIndex = 0;
    var oldEndIndex = oldChildren.length;
632

H
Hixie 已提交
633
    RenderObject nextSibling = null;
634 635 636 637
    UINode currentNode = null;
    UINode oldNode = null;

    void sync(int atIndex) {
638
      children[atIndex] = syncChild(currentNode, oldNode, nextSibling);
639 640 641 642 643 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 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
      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 已提交
695
      assert(root is ContainerRenderObjectMixin);
696 697
      assert(old.root is ContainerRenderObjectMixin);
      assert(oldNode.root != null);
698

699
      (old.root as ContainerRenderObjectMixin).remove(oldNode.root); // TODO(ianh): Remove cast once the analyzer is cleverer
700
      root.add(oldNode.root, before: nextSibling);
701 702 703 704 705

      return true;
    }

    // Scan forwards, this time we may re-order;
706
    nextSibling = root.firstChild;
707 708 709 710 711 712
    while (startIndex < endIndex && oldStartIndex < oldEndIndex) {
      currentNode = children[startIndex];
      oldNode = oldChildren[oldStartIndex];

      if (currentNode._key == oldNode._key) {
        assert(currentNode.runtimeType == oldNode.runtimeType);
713
        nextSibling = root.childAfter(nextSibling);
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
        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];
738
      removeChild(oldNode);
739 740
      advanceOldStartIndex();
    }
741 742

    assert(root == this.root); // TODO(ianh): Remove this once the analyzer is cleverer
743
  }
H
Hixie 已提交
744

745 746
}

A
Adam Barth 已提交
747

748
class UINodeAppView extends AppView {
749

750 751 752 753 754 755 756 757 758
  UINodeAppView() {
    assert(_appView == null);
  }

  static UINodeAppView _appView;
  static void initUINodeAppView() {
    if (_appView == null)
      _appView = new UINodeAppView();
  }
759

A
Adam Barth 已提交
760
  void dispatchEvent(sky.Event event, HitTestResult result) {
761
    assert(_appView == this);
A
Adam Barth 已提交
762
    super.dispatchEvent(event, result);
763 764 765 766 767 768 769 770 771 772
    for (HitTestEntry entry in result.path.reversed) {
      UINode target = RenderObjectWrapper._getMounted(entry.target);
      if (target == null)
        continue;
      RenderObject targetRoot = target.root;
      while (target != null && target.root == targetRoot) {
        if (target is EventListenerNode)
          target._handleEvent(event);
        target = target._parent;
      }      
773 774
    }
  }
775

776 777
}

778
abstract class AbstractUINodeRoot extends Component {
779

780 781
  AbstractUINodeRoot() : super(stateful: true) {
    UINodeAppView.initUINodeAppView();
782
    _mounted = true;
783
    _scheduleComponentForRender(this);
784 785
  }

786 787 788 789
  void syncFields(AbstractUINodeRoot source) {
    assert(false);
    // if we get here, it implies that we have a parent
  }
790

791 792
  void _buildIfDirty() {
    assert(_dirty);
793
    assert(_mounted);
794
    assert(parent == null);
795
    _sync(null, null);
796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
  }

}

abstract class App extends AbstractUINodeRoot {

  App();

  AppView get appView => UINodeAppView._appView;

  void _buildIfDirty() {
    super._buildIfDirty();

    if (root.parent == null) {
      // we haven't attached it yet
      UINodeAppView._appView.root = root;
    }
813
    assert(root.parent is RenderView);
814
  }
H
Hixie 已提交
815

816 817
}

818 819
typedef UINode Builder();

820
class RenderObjectToUINodeAdapter extends AbstractUINodeRoot {
821

822
  RenderObjectToUINodeAdapter(
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 850 851 852 853 854 855 856 857 858 859
    RenderObjectWithChildMixin<RenderBox> container,
    this.builder
  ) : _container = container {
    assert(builder != null);
  }

  RenderObjectWithChildMixin<RenderBox> _container;
  RenderObjectWithChildMixin<RenderBox> get container => _container;
  void set container(RenderObjectWithChildMixin<RenderBox> value) {
    if (_container != value) {
      assert(value.child == null);
      if (root != null) {
        assert(_container.child == root);
        _container.child = null;
      }
      _container = value;
      if (root != null) {
        _container.child = root;
        assert(_container.child == root);
      }
    }
  }

  final Builder builder;

  void _buildIfDirty() {
    super._buildIfDirty();
    if (root.parent == null) {
      // we haven't attached it yet
      assert(_container.child == null);
      _container.child = root;
    }
    assert(root.parent == _container);
  }

  UINode build() => builder();

860
}