ContainerNode.cpp 38.2 KB
Newer Older
darin@apple.com's avatar
darin@apple.com committed
1
/*
2 3 4
 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
 *           (C) 1999 Antti Koivisto (koivisto@kde.org)
 *           (C) 2001 Dirk Mueller (mueller@kde.org)
5
 * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
6 7 8 9 10 11 12 13 14 15 16 17 18
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
ddkilzer's avatar
ddkilzer committed
19 20
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
21 22 23
 */

#include "config.h"
darin's avatar
darin committed
24
#include "ContainerNode.h"
25

26
#include "AXObjectCache.h"
27
#include "ChildListMutationScope.h"
28 29
#include "Chrome.h"
#include "ChromeClient.h"
zimmermann@webkit.org's avatar
zimmermann@webkit.org committed
30
#include "ContainerNodeAlgorithms.h"
31
#if ENABLE(DELETION_UI)
thatcher's avatar
thatcher committed
32
#include "DeleteButtonController.h"
33
#endif
34
#include "EventNames.h"
darin's avatar
darin committed
35
#include "ExceptionCode.h"
36
#include "FloatRect.h"
darin@apple.com's avatar
darin@apple.com committed
37
#include "Frame.h"
darin's avatar
darin committed
38
#include "FrameView.h"
39
#include "HTMLNames.h"
darin's avatar
darin committed
40
#include "InlineTextBox.h"
41
#include "InsertionPoint.h"
42
#include "InspectorInstrumentation.h"
43
#include "LoaderStrategy.h"
44
#include "MemoryCache.h"
weinig's avatar
 
weinig committed
45
#include "MutationEvent.h"
46
#include "NodeRenderStyle.h"
47
#include "NodeTraversal.h"
48
#include "ResourceLoadScheduler.h"
mitz@apple.com's avatar
mitz@apple.com committed
49
#include "Page.h"
50
#include "PlatformStrategies.h"
51
#include "RenderBox.h"
darin's avatar
darin committed
52
#include "RenderTheme.h"
53
#include "RenderWidget.h"
54
#include "RootInlineBox.h"
55
#include "TemplateContentDocumentFragment.h"
ap@webkit.org's avatar
ap@webkit.org committed
56
#include <wtf/CurrentTime.h>
57
#include <wtf/Vector.h>
58

59 60
#include "JSNode.h"

61 62
using namespace std;

darin's avatar
darin committed
63
namespace WebCore {
64

65 66
static void dispatchChildInsertionEvents(Node*);
static void dispatchChildRemovalEvents(Node*);
67
static void updateTreeAfterInsertion(ContainerNode*, Node*, AttachBehavior);
darin's avatar
darin committed
68

69 70 71 72
typedef pair<RefPtr<Node>, unsigned> CallbackParameters;
typedef pair<NodeCallback, CallbackParameters> CallbackInfo;
typedef Vector<CallbackInfo> NodeCallbackQueue;

mitz@apple.com's avatar
mitz@apple.com committed
73
static NodeCallbackQueue* s_postAttachCallbackQueue;
ggaren's avatar
ggaren committed
74

mitz@apple.com's avatar
mitz@apple.com committed
75 76
static size_t s_attachDepth;
static bool s_shouldReEnableMemoryCacheCallsAfterAttach;
ggaren's avatar
ggaren committed
77

78 79
ChildNodesLazySnapshot* ChildNodesLazySnapshot::latestSnapshot = 0;

80
#ifndef NDEBUG
81
unsigned NoEventDispatchAssertion::s_count = 0;
82 83
#endif

84 85 86 87 88 89 90 91 92 93 94 95
static void collectChildrenAndRemoveFromOldParent(Node* node, NodeVector& nodes, ExceptionCode& ec)
{
    if (node->nodeType() != Node::DOCUMENT_FRAGMENT_NODE) {
        nodes.append(node);
        if (ContainerNode* oldParent = node->parentNode())
            oldParent->removeChild(node, ec);
        return;
    }
    getChildNodes(node, nodes);
    toContainerNode(node)->removeChildren();
}

96
void ContainerNode::removeDetachedChildren()
97
{
98 99 100 101
    if (connectedSubframeCount()) {
        for (Node* child = firstChild(); child; child = child->nextSibling())
            child->updateAncestorConnectedSubframeCountForRemoval();
    }
102 103
    // FIXME: We should be able to ASSERT(!attached()) here: https://bugs.webkit.org/show_bug.cgi?id=107801
    removeDetachedChildrenInContainer<Node, ContainerNode>(this);
104 105
}

106 107 108
void ContainerNode::takeAllChildrenFrom(ContainerNode* oldParent)
{
    NodeVector children;
109
    getChildNodes(oldParent, children);
110 111 112 113 114 115 116 117 118 119

    if (oldParent->document()->hasMutationObserversOfType(MutationObserver::ChildList)) {
        ChildListMutationScope mutation(oldParent);
        for (unsigned i = 0; i < children.size(); ++i)
            mutation.willRemoveChild(children[i].get());
    }

    // FIXME: We need to do notifyMutationObserversNodeWillDetach() for each child,
    // probably inside removeDetachedChildrenInContainer.

120
    oldParent->removeDetachedChildren();
121 122

    for (unsigned i = 0; i < children.size(); ++i) {
123 124
        if (children[i]->attached())
            children[i]->detach();
125
        // FIXME: We need a no mutation event version of adoptNode.
126
        RefPtr<Node> child = document()->adoptNode(children[i].release(), ASSERT_NO_EXCEPTION);
127
        parserAppendChild(child.get());
128 129 130
        // FIXME: Together with adoptNode above, the tree scope might get updated recursively twice
        // (if the document changed or oldParent was in a shadow tree, AND *this is in a shadow tree).
        // Can we do better?
131
        treeScope()->adoptIfNeeded(child.get());
132 133
        if (attached() && !child->attached())
            child->attach();
134 135 136
    }
}

darin's avatar
darin committed
137
ContainerNode::~ContainerNode()
138
{
139 140
    if (Document* document = documentInternal())
        willBeDeletedFrom(document);
141
    removeDetachedChildren();
142 143
}

144 145 146 147 148 149 150 151 152 153 154 155
static inline bool isChildTypeAllowed(ContainerNode* newParent, Node* child)
{
    if (!child->isDocumentFragment())
        return newParent->childTypeAllowed(child->nodeType());

    for (Node* node = child->firstChild(); node; node = node->nextSibling()) {
        if (!newParent->childTypeAllowed(node->nodeType()))
            return false;
    }
    return true;
}

156 157 158 159
static inline bool isInTemplateContent(const Node* node)
{
#if ENABLE(TEMPLATE_ELEMENT)
    Document* document = node->document();
160
    return document && document == document->templateDocument();
161
#else
adamk@chromium.org's avatar
adamk@chromium.org committed
162
    UNUSED_PARAM(node);
163 164 165 166 167 168 169 170 171 172 173
    return false;
#endif
}

static inline bool containsConsideringHostElements(const Node* newChild, const Node* newParent)
{
    return (newParent->isInShadowTree() || isInTemplateContent(newParent))
        ? newChild->containsIncludingHostElements(newParent)
        : newChild->contains(newParent);
}

174 175 176 177 178 179
static inline ExceptionCode checkAcceptChild(ContainerNode* newParent, Node* newChild, Node* oldChild)
{
    // Not mentioned in spec: throw NOT_FOUND_ERR if newChild is null
    if (!newChild)
        return NOT_FOUND_ERR;

180
    // Use common case fast path if possible.
181 182 183 184
    if ((newChild->isElementNode() || newChild->isTextNode()) && newParent->isElementNode()) {
        ASSERT(!newParent->isReadOnlyNode());
        ASSERT(!newParent->isDocumentTypeNode());
        ASSERT(isChildTypeAllowed(newParent, newChild));
185
        if (containsConsideringHostElements(newChild, newParent))
186 187 188 189
            return HIERARCHY_REQUEST_ERR;
        return 0;
    }

190 191 192 193 194
    // This should never happen, but also protect release builds from tree corruption.
    ASSERT(!newChild->isPseudoElement());
    if (newChild->isPseudoElement())
        return HIERARCHY_REQUEST_ERR;

195 196 197 198
    if (newParent->isReadOnlyNode())
        return NO_MODIFICATION_ALLOWED_ERR;
    if (newChild->inDocument() && newChild->isDocumentTypeNode())
        return HIERARCHY_REQUEST_ERR;
199
    if (containsConsideringHostElements(newChild, newParent))
200 201 202
        return HIERARCHY_REQUEST_ERR;

    if (oldChild && newParent->isDocumentNode()) {
203
        if (!toDocument(newParent)->canReplaceChild(newChild, oldChild))
204 205 206 207 208 209 210
            return HIERARCHY_REQUEST_ERR;
    } else if (!isChildTypeAllowed(newParent, newChild))
        return HIERARCHY_REQUEST_ERR;

    return 0;
}

211 212 213 214 215 216 217 218 219 220 221 222 223
static inline bool checkAcceptChildGuaranteedNodeTypes(ContainerNode* newParent, Node* newChild, ExceptionCode& ec)
{
    ASSERT(!newParent->isReadOnlyNode());
    ASSERT(!newParent->isDocumentTypeNode());
    ASSERT(isChildTypeAllowed(newParent, newChild));
    if (newChild->contains(newParent)) {
        ec = HIERARCHY_REQUEST_ERR;
        return false;
    }

    return true;
}

224 225
static inline bool checkAddChild(ContainerNode* newParent, Node* newChild, ExceptionCode& ec)
{
226 227
    ec = checkAcceptChild(newParent, newChild, 0);
    if (ec)
228 229 230 231 232 233 234
        return false;

    return true;
}

static inline bool checkReplaceChild(ContainerNode* newParent, Node* newChild, Node* oldChild, ExceptionCode& ec)
{
235 236
    ec = checkAcceptChild(newParent, newChild, oldChild);
    if (ec)
237
        return false;
238

239 240 241
    return true;
}

242
bool ContainerNode::insertBefore(PassRefPtr<Node> newChild, Node* refChild, ExceptionCode& ec, AttachBehavior attachBehavior)
243
{
darin's avatar
darin committed
244 245
    // Check that this node is not "floating".
    // If it is, it can be deleted as a side effect of sending mutation events.
246
    ASSERT(refCount() || parentOrShadowHostNode());
darin's avatar
darin committed
247

248
    RefPtr<Node> protect(this);
249

darin's avatar
darin committed
250
    ec = 0;
251

darin's avatar
darin committed
252 253
    // insertBefore(node, 0) is equivalent to appendChild(node)
    if (!refChild)
254
        return appendChild(newChild, ec, attachBehavior);
255

darin's avatar
darin committed
256
    // Make sure adding the new child is OK.
257
    if (!checkAddChild(this, newChild.get(), ec))
mjs's avatar
mjs committed
258
        return false;
259 260 261

    // NOT_FOUND_ERR: Raised if refChild is not a child of this node
    if (refChild->parentNode() != this) {
darin's avatar
darin committed
262
        ec = NOT_FOUND_ERR;
mjs's avatar
mjs committed
263
        return false;
264 265
    }

266
    if (refChild->previousSibling() == newChild || refChild == newChild) // nothing to do
mjs's avatar
mjs committed
267
        return true;
268

269 270
    RefPtr<Node> next = refChild;

271 272 273 274 275
    NodeVector targets;
    collectChildrenAndRemoveFromOldParent(newChild.get(), targets, ec);
    if (ec)
        return false;
    if (targets.isEmpty())
mjs's avatar
mjs committed
276
        return true;
darin's avatar
darin committed
277

278 279 280 281
    // We need this extra check because collectChildrenAndRemoveFromOldParent() can fire mutation events.
    if (!checkAcceptChildGuaranteedNodeTypes(this, newChild.get(), ec))
        return false;

282 283
    InspectorInstrumentation::willInsertDOMNode(document(), this);

284 285 286
    ChildListMutationScope mutation(this);
    for (NodeVector::const_iterator it = targets.begin(); it != targets.end(); ++it) {
        Node* child = it->get();
287

darin's avatar
darin committed
288
        // Due to arbitrary code running in response to a DOM mutation event it's
289 290 291 292 293 294
        // possible that "next" is no longer a child of "this".
        // It's also possible that "child" has been inserted elsewhere.
        // In either of those cases, we'll just stop.
        if (next->parentNode() != this)
            break;
        if (child->parentNode())
darin's avatar
darin committed
295 296
            break;

297
        treeScope()->adoptIfNeeded(child);
298

299
        insertBeforeCommon(next.get(), child);
300

301
        updateTreeAfterInsertion(this, child, attachBehavior);
302 303
    }

304
    dispatchSubtreeModifiedEvent();
mjs's avatar
mjs committed
305
    return true;
306 307
}

308 309
void ContainerNode::insertBeforeCommon(Node* nextChild, Node* newChild)
{
310
    NoEventDispatchAssertion assertNoEventDispatch;
311

312
    ASSERT(newChild);
313
    ASSERT(!newChild->parentNode()); // Use insertBefore if you need to handle reparenting (and want DOM mutation events).
314 315
    ASSERT(!newChild->nextSibling());
    ASSERT(!newChild->previousSibling());
316
    ASSERT(!newChild->isShadowRoot());
317 318 319 320 321 322 323 324 325 326 327 328

    Node* prev = nextChild->previousSibling();
    ASSERT(m_lastChild != prev);
    nextChild->setPreviousSibling(newChild);
    if (prev) {
        ASSERT(m_firstChild != nextChild);
        ASSERT(prev->nextSibling() == nextChild);
        prev->setNextSibling(newChild);
    } else {
        ASSERT(m_firstChild == nextChild);
        m_firstChild = newChild;
    }
329
    newChild->setParentOrShadowHostNode(this);
330 331 332 333 334 335 336 337 338
    newChild->setPreviousSibling(prev);
    newChild->setNextSibling(nextChild);
}

void ContainerNode::parserInsertBefore(PassRefPtr<Node> newChild, Node* nextChild)
{
    ASSERT(newChild);
    ASSERT(nextChild);
    ASSERT(nextChild->parentNode() == this);
339
    ASSERT(!newChild->isDocumentFragment());
340 341 342
#if ENABLE(TEMPLATE_ELEMENT)
    ASSERT(!hasTagName(HTMLNames::templateTag));
#endif
343 344 345 346

    if (nextChild->previousSibling() == newChild || nextChild == newChild) // nothing to do
        return;

347 348 349
    if (document() != newChild->document())
        document()->adoptNode(newChild.get(), ASSERT_NO_EXCEPTION);

350
    insertBeforeCommon(nextChild, newChild.get());
351

352
    newChild->updateAncestorConnectedSubframeCountForInsertion();
353

354 355
    ChildListMutationScope(this).childAdded(newChild.get());

356 357
    childrenChanged(true, newChild->previousSibling(), nextChild, 1);
    ChildNodeInsertionNotifier(this).notify(newChild.get());
358 359
}

360
bool ContainerNode::replaceChild(PassRefPtr<Node> newChild, Node* oldChild, ExceptionCode& ec, AttachBehavior attachBehavior)
361
{
darin's avatar
darin committed
362 363
    // Check that this node is not "floating".
    // If it is, it can be deleted as a side effect of sending mutation events.
364
    ASSERT(refCount() || parentOrShadowHostNode());
darin's avatar
darin committed
365

366
    RefPtr<Node> protect(this);
367

darin's avatar
darin committed
368
    ec = 0;
369

darin's avatar
darin committed
370
    if (oldChild == newChild) // nothing to do
mjs's avatar
mjs committed
371
        return true;
372

373 374 375 376 377
    if (!oldChild) {
        ec = NOT_FOUND_ERR;
        return false;
    }

andersca's avatar
andersca committed
378
    // Make sure replacing the old child with the new is ok
379
    if (!checkReplaceChild(this, newChild.get(), oldChild, ec))
mjs's avatar
mjs committed
380
        return false;
381 382

    // NOT_FOUND_ERR: Raised if oldChild is not a child of this node.
383
    if (oldChild->parentNode() != this) {
darin's avatar
darin committed
384
        ec = NOT_FOUND_ERR;
mjs's avatar
mjs committed
385
        return false;
386 387
    }

388 389
    ChildListMutationScope mutation(this);

390
    RefPtr<Node> next = oldChild->nextSibling();
391

darin's avatar
darin committed
392
    // Remove the node we're replacing
darin's avatar
darin committed
393
    RefPtr<Node> removedChild = oldChild;
mjs's avatar
mjs committed
394
    removeChild(oldChild, ec);
darin's avatar
darin committed
395
    if (ec)
mjs's avatar
mjs committed
396
        return false;
397

398 399 400
    if (next && (next->previousSibling() == newChild || next == newChild)) // nothing to do
        return true;

401
    // Does this one more time because removeChild() fires a MutationEvent.
402
    if (!checkReplaceChild(this, newChild.get(), oldChild, ec))
403 404
        return false;

405
    NodeVector targets;
406 407 408
    collectChildrenAndRemoveFromOldParent(newChild.get(), targets, ec);
    if (ec)
        return false;
darin's avatar
darin committed
409

410
    // Does this yet another check because collectChildrenAndRemoveFromOldParent() fires a MutationEvent.
411
    if (!checkReplaceChild(this, newChild.get(), oldChild, ec))
412 413
        return false;

414 415
    InspectorInstrumentation::willInsertDOMNode(document(), this);

416 417 418
    // Add the new child(ren)
    for (NodeVector::const_iterator it = targets.begin(); it != targets.end(); ++it) {
        Node* child = it->get();
419

darin's avatar
darin committed
420
        // Due to arbitrary code running in response to a DOM mutation event it's
421 422 423 424 425 426
        // possible that "next" is no longer a child of "this".
        // It's also possible that "child" has been inserted elsewhere.
        // In either of those cases, we'll just stop.
        if (next && next->parentNode() != this)
            break;
        if (child->parentNode())
darin's avatar
darin committed
427 428
            break;

429
        treeScope()->adoptIfNeeded(child);
430

431
        // Add child before "next".
432
        {
433
            NoEventDispatchAssertion assertNoEventDispatch;
434 435 436 437 438
            if (next)
                insertBeforeCommon(next.get(), child);
            else
                appendChildToContainer(child, this);
        }
439

440
        updateTreeAfterInsertion(this, child, attachBehavior);
441 442
    }

443
    dispatchSubtreeModifiedEvent();
mjs's avatar
mjs committed
444
    return true;
445 446
}

ap@apple.com's avatar
ap@apple.com committed
447
static void willRemoveChild(Node* child)
448
{
449 450 451
    ASSERT(child->parentNode());
    ChildListMutationScope(child->parentNode()).willRemoveChild(child);
    child->notifyMutationObserversNodeWillDetach();
452
    dispatchChildRemovalEvents(child);
453
    child->document()->nodeWillBeRemoved(child); // e.g. mutation event listener can create a new range.
454
    ChildFrameDisconnector(child).disconnect();
ap@apple.com's avatar
ap@apple.com committed
455 456 457 458
}

static void willRemoveChildren(ContainerNode* container)
{
459
    NodeVector children;
460
    getChildNodes(container, children);
461

462 463
    container->document()->nodeChildrenWillBeRemoved(container);

464
    ChildListMutationScope mutation(container);
465
    for (NodeVector::const_iterator it = children.begin(); it != children.end(); ++it) {
466
        Node* child = it->get();
467 468 469
        mutation.willRemoveChild(child);
        child->notifyMutationObserversNodeWillDetach();

ap@apple.com's avatar
ap@apple.com committed
470
        // fire removed from document mutation events.
471
        dispatchChildRemovalEvents(child);
ap@apple.com's avatar
ap@apple.com committed
472
    }
473

474
    ChildFrameDisconnector(container).disconnect(ChildFrameDisconnector::DescendantsOnly);
475 476
}

477 478 479 480 481
void ContainerNode::disconnectDescendantFrames()
{
    ChildFrameDisconnector(this).disconnect();
}

darin's avatar
darin committed
482
bool ContainerNode::removeChild(Node* oldChild, ExceptionCode& ec)
483
{
darin's avatar
darin committed
484 485
    // Check that this node is not "floating".
    // If it is, it can be deleted as a side effect of sending mutation events.
486
    ASSERT(refCount() || parentOrShadowHostNode());
darin's avatar
darin committed
487

488 489
    RefPtr<Node> protect(this);

darin's avatar
darin committed
490
    ec = 0;
491 492

    // NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly.
adele's avatar
adele committed
493
    if (isReadOnlyNode()) {
darin's avatar
darin committed
494
        ec = NO_MODIFICATION_ALLOWED_ERR;
mjs's avatar
mjs committed
495
        return false;
496 497 498 499
    }

    // NOT_FOUND_ERR: Raised if oldChild is not a child of this node.
    if (!oldChild || oldChild->parentNode() != this) {
darin's avatar
darin committed
500
        ec = NOT_FOUND_ERR;
mjs's avatar
mjs committed
501
        return false;
502 503
    }

darin's avatar
darin committed
504
    RefPtr<Node> child = oldChild;
darin's avatar
darin committed
505

alice.liu@apple.com's avatar
alice.liu@apple.com committed
506
    document()->removeFocusedNodeOfSubtree(child.get());
507

508 509 510 511
#if ENABLE(FULLSCREEN_API)
    document()->removeFullScreenElementOfSubtree(child.get());
#endif

512 513 514 515 516 517 518
    // Events fired when blurring currently focused node might have moved this
    // child into a different parent.
    if (child->parentNode() != this) {
        ec = NOT_FOUND_ERR;
        return false;
    }

519 520 521 522 523 524 525 526
    willRemoveChild(child.get());

    // Mutation events might have moved this child into a different parent.
    if (child->parentNode() != this) {
        ec = NOT_FOUND_ERR;
        return false;
    }

527 528 529 530 531 532 533 534 535
    {
        WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;

        Node* prev = child->previousSibling();
        Node* next = child->nextSibling();
        removeBetween(prev, next, child.get());
        childrenChanged(false, prev, next, -1);
        ChildNodeRemovalNotifier(this).notify(child.get());
    }
536 537
    dispatchSubtreeModifiedEvent();

darin's avatar
darin committed
538
    return child;
539 540
}

541 542
void ContainerNode::removeBetween(Node* previousChild, Node* nextChild, Node* oldChild)
{
543
    NoEventDispatchAssertion assertNoEventDispatch;
544

545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
    ASSERT(oldChild);
    ASSERT(oldChild->parentNode() == this);

    // Remove from rendering tree
    if (oldChild->attached())
        oldChild->detach();

    if (nextChild)
        nextChild->setPreviousSibling(previousChild);
    if (previousChild)
        previousChild->setNextSibling(nextChild);
    if (m_firstChild == oldChild)
        m_firstChild = nextChild;
    if (m_lastChild == oldChild)
        m_lastChild = previousChild;

    oldChild->setPreviousSibling(0);
    oldChild->setNextSibling(0);
563
    oldChild->setParentOrShadowHostNode(0);
564

565
    document()->adoptIfNeeded(oldChild);
566 567 568 569 570 571
}

void ContainerNode::parserRemoveChild(Node* oldChild)
{
    ASSERT(oldChild);
    ASSERT(oldChild->parentNode() == this);
572
    ASSERT(!oldChild->isDocumentFragment());
573 574 575 576

    Node* prev = oldChild->previousSibling();
    Node* next = oldChild->nextSibling();

577
    oldChild->updateAncestorConnectedSubframeCountForRemoval();
578

579 580 581
    ChildListMutationScope(this).willRemoveChild(oldChild);
    oldChild->notifyMutationObserversNodeWillDetach();

582 583 584
    removeBetween(prev, next, oldChild);

    childrenChanged(true, prev, next, -1);
585
    ChildNodeRemovalNotifier(this).notify(oldChild);
586 587
}

588 589
// this differs from other remove functions because it forcibly removes all the children,
// regardless of read-only status or event exceptions, e.g.
590
void ContainerNode::removeChildren()
591
{
darin's avatar
darin committed
592
    if (!m_firstChild)
593
        return;
594

595
    // The container node can be removed from event handlers.
ap@apple.com's avatar
ap@apple.com committed
596 597
    RefPtr<ContainerNode> protect(this);

alice.liu@apple.com's avatar
alice.liu@apple.com committed
598 599 600
    // exclude this node when looking for removed focusedNode since only children will be removed
    document()->removeFocusedNodeOfSubtree(this, true);

601 602 603 604
#if ENABLE(FULLSCREEN_API)
    document()->removeFullScreenElementOfSubtree(this, true);
#endif

605 606 607 608
    // Do any prep work needed before actually starting to detach
    // and remove... e.g. stop loading frames, fire unload events.
    willRemoveChildren(protect.get());

609
    Vector<RefPtr<Node>, 10> removedChildren;
610 611
    {
        WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
612 613 614 615 616 617 618 619 620 621 622
        {
            NoEventDispatchAssertion assertNoEventDispatch;
            removedChildren.reserveInitialCapacity(childNodeCount());
            while (RefPtr<Node> n = m_firstChild) {
                Node* next = n->nextSibling();

                // Remove the node from the tree before calling detach or removedFromDocument (4427024, 4129744).
                // removeChild() does this after calling detach(). There is no explanation for
                // this discrepancy between removeChild() and its optimized version removeChildren().
                n->setPreviousSibling(0);
                n->setNextSibling(0);
623
                n->setParentOrShadowHostNode(0);
624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
                document()->adoptIfNeeded(n.get());

                m_firstChild = next;
                if (n == m_lastChild)
                    m_lastChild = 0;
                removedChildren.append(n.release());
            }

            // Detach the nodes only after properly removed from the tree because
            // a. detaching requires a proper DOM tree (for counters and quotes for
            // example) and during the previous loop the next sibling still points to
            // the node being removed while the node being removed does not point back
            // and does not point to the same parent as its next sibling.
            // b. destroying Renderers of standalone nodes is sometimes faster.
            for (size_t i = 0; i < removedChildren.size(); ++i) {
                Node* removedChild = removedChildren[i].get();
                if (removedChild->attached())
                    removedChild->detach();
            }
643 644
        }

645 646 647
        childrenChanged(false, 0, 0, -static_cast<int>(removedChildren.size()));
        
        for (size_t i = 0; i < removedChildren.size(); ++i)
648
            ChildNodeRemovalNotifier(this).notify(removedChildren[i].get());
649
    }
650

651
    dispatchSubtreeModifiedEvent();
darin@apple.com's avatar
darin@apple.com committed
652
}
653

654
bool ContainerNode::appendChild(PassRefPtr<Node> newChild, ExceptionCode& ec, AttachBehavior attachBehavior)
655
{
656
    RefPtr<ContainerNode> protect(this);
657

darin's avatar
darin committed
658 659
    // Check that this node is not "floating".
    // If it is, it can be deleted as a side effect of sending mutation events.
660
    ASSERT(refCount() || parentOrShadowHostNode());
darin's avatar
darin committed
661

darin's avatar
darin committed
662
    ec = 0;
663 664

    // Make sure adding the new child is ok
665
    if (!checkAddChild(this, newChild.get(), ec))
666 667
        return false;

darin's avatar
darin committed
668
    if (newChild == m_lastChild) // nothing to do
669 670
        return newChild;

671
    NodeVector targets;
672 673 674 675
    collectChildrenAndRemoveFromOldParent(newChild.get(), targets, ec);
    if (ec)
        return false;

676
    if (targets.isEmpty())
mjs's avatar
mjs committed
677
        return true;
678

679 680 681 682
    // We need this extra check because collectChildrenAndRemoveFromOldParent() can fire mutation events.
    if (!checkAcceptChildGuaranteedNodeTypes(this, newChild.get(), ec))
        return false;

683 684
    InspectorInstrumentation::willInsertDOMNode(document(), this);

685
    // Now actually add the child(ren)
686
    ChildListMutationScope mutation(this);
687 688
    for (NodeVector::const_iterator it = targets.begin(); it != targets.end(); ++it) {
        Node* child = it->get();
689 690 691 692

        // If the child has a parent again, just stop what we're doing, because
        // that means someone is doing something with DOM mutation -- can't re-parent
        // a child that already has a parent.
693
        if (child->parentNode())
694
            break;
695

696
        treeScope()->adoptIfNeeded(child);
697

698
        // Append child to the end of the list
699
        {
700
            NoEventDispatchAssertion assertNoEventDispatch;
701 702
            appendChildToContainer(child, this);
        }
703

704
        updateTreeAfterInsertion(this, child, attachBehavior);
705 706
    }

707
    dispatchSubtreeModifiedEvent();
mjs's avatar
mjs committed
708
    return true;
709 710
}

711
void ContainerNode::parserAppendChild(PassRefPtr<Node> newChild)
712
{
713
    ASSERT(newChild);
714
    ASSERT(!newChild->parentNode()); // Use appendChild if you need to handle reparenting (and want DOM mutation events).
715
    ASSERT(!newChild->isDocumentFragment());
716 717 718
#if ENABLE(TEMPLATE_ELEMENT)
    ASSERT(!hasTagName(HTMLNames::templateTag));
#endif
719 720 721

    if (document() != newChild->document())
        document()->adoptNode(newChild.get(), ASSERT_NO_EXCEPTION);
722

723
    Node* last = m_lastChild;
724
    {
725
        NoEventDispatchAssertion assertNoEventDispatch;
726 727 728 729
        // FIXME: This method should take a PassRefPtr.
        appendChildToContainer(newChild.get(), this);
        treeScope()->adoptIfNeeded(newChild.get());
    }
730

731
    newChild->updateAncestorConnectedSubframeCountForInsertion();
732

733 734
    ChildListMutationScope(this).childAdded(newChild.get());

735
    childrenChanged(true, last, 0, 1);
736
    ChildNodeInsertionNotifier(this).notify(newChild.get());
737 738
}

mitz@apple.com's avatar
mitz@apple.com committed
739 740
void ContainerNode::suspendPostAttachCallbacks()
{
mitz@apple.com's avatar
mitz@apple.com committed
741 742 743
    if (!s_attachDepth) {
        ASSERT(!s_shouldReEnableMemoryCacheCallsAfterAttach);
        if (Page* page = document()->page()) {
744 745
            // FIXME: How can this call be specific to one Page, while the
            // s_attachDepth is a global? Doesn't make sense.
mitz@apple.com's avatar
mitz@apple.com committed
746 747 748 749 750
            if (page->areMemoryCacheClientCallsEnabled()) {
                page->setMemoryCacheClientCallsEnabled(false);
                s_shouldReEnableMemoryCacheCallsAfterAttach = true;
            }
        }
751 752 753
#if USE(PLATFORM_STRATEGIES)
        platformStrategies()->loaderStrategy()->resourceLoadScheduler()->suspendPendingRequests();
#else
754
        resourceLoadScheduler()->suspendPendingRequests();
755
#endif
mitz@apple.com's avatar
mitz@apple.com committed
756
    }
mitz@apple.com's avatar
mitz@apple.com committed
757 758 759 760 761
    ++s_attachDepth;
}

void ContainerNode::resumePostAttachCallbacks()
{
mitz@apple.com's avatar
mitz@apple.com committed
762
    if (s_attachDepth == 1) {
763 764
        RefPtr<ContainerNode> protect(this);

mitz@apple.com's avatar
mitz@apple.com committed
765 766 767 768 769 770 771
        if (s_postAttachCallbackQueue)
            dispatchPostAttachCallbacks();
        if (s_shouldReEnableMemoryCacheCallsAfterAttach) {
            s_shouldReEnableMemoryCacheCallsAfterAttach = false;
            if (Page* page = document()->page())
                page->setMemoryCacheClientCallsEnabled(true);
        }
772 773 774
#if USE(PLATFORM_STRATEGIES)
        platformStrategies()->loaderStrategy()->resourceLoadScheduler()->resumePendingRequests();
#else
775
        resourceLoadScheduler()->resumePendingRequests();
776
#endif
mitz@apple.com's avatar
mitz@apple.com committed
777
    }
mitz@apple.com's avatar
mitz@apple.com committed
778 779 780
    --s_attachDepth;
}

781
void ContainerNode::queuePostAttachCallback(NodeCallback callback, Node* node, unsigned callbackData)
ggaren's avatar
ggaren committed
782 783 784 785
{
    if (!s_postAttachCallbackQueue)
        s_postAttachCallbackQueue = new NodeCallbackQueue;
    
786
    s_postAttachCallbackQueue->append(CallbackInfo(callback, CallbackParameters(node, callbackData)));
mitz@apple.com's avatar
mitz@apple.com committed
787 788
}

789 790 791 792 793
bool ContainerNode::postAttachCallbacksAreSuspended()
{
    return s_attachDepth;
}

mitz@apple.com's avatar
mitz@apple.com committed
794 795 796 797 798
void ContainerNode::dispatchPostAttachCallbacks()
{
    // We recalculate size() each time through the loop because a callback
    // can add more callbacks to the end of the queue.
    for (size_t i = 0; i < s_postAttachCallbackQueue->size(); ++i) {
799 800 801
        const CallbackInfo& info = (*s_postAttachCallbackQueue)[i];
        NodeCallback callback = info.first;
        CallbackParameters params = info.second;
mitz@apple.com's avatar
mitz@apple.com committed
802

803
        callback(params.first.get(), params.second);
mitz@apple.com's avatar
mitz@apple.com committed
804 805
    }
    s_postAttachCallbackQueue->clear();
ggaren's avatar
ggaren committed
806 807
}

808 809 810 811 812 813 814 815 816 817 818 819 820
static void needsStyleRecalcCallback(Node* node, unsigned data)
{
    node->setNeedsStyleRecalc(static_cast<StyleChangeType>(data));
}

void ContainerNode::scheduleSetNeedsStyleRecalc(StyleChangeType changeType)
{
    if (postAttachCallbacksAreSuspended())
        queuePostAttachCallback(needsStyleRecalcCallback, this, static_cast<unsigned>(changeType));
    else
        setNeedsStyleRecalc(changeType);
}

darin's avatar
darin committed
821
void ContainerNode::attach()
822
{
823
    attachChildren();
824
    Node::attach();
825 826
}

darin's avatar
darin committed
827
void ContainerNode::detach()
828
{
829
    detachChildren();
830
    clearChildNeedsStyleRecalc();
831
    Node::detach();
832 833
}

834
void ContainerNode::childrenChanged(bool changedByParser, Node*, Node*, int childCountDelta)
835
{