Upstream version 7.35.139.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / dom / Node.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
4  *           (C) 2001 Dirk Mueller (mueller@kde.org)
5  * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
6  * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
7  * Copyright (C) 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public License
20  * along with this library; see the file COPYING.LIB.  If not, write to
21  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22  * Boston, MA 02110-1301, USA.
23  */
24
25 #include "config.h"
26 #include "core/dom/Node.h"
27
28 #include "HTMLNames.h"
29 #include "XMLNames.h"
30 #include "bindings/v8/ExceptionState.h"
31 #include "bindings/v8/ScriptCallStackFactory.h"
32 #include "core/accessibility/AXObjectCache.h"
33 #include "core/dom/Attr.h"
34 #include "core/dom/Attribute.h"
35 #include "core/dom/ChildListMutationScope.h"
36 #include "core/dom/ChildNodeList.h"
37 #include "core/dom/DOMImplementation.h"
38 #include "core/dom/Document.h"
39 #include "core/dom/DocumentFragment.h"
40 #include "core/dom/DocumentMarkerController.h"
41 #include "core/dom/DocumentType.h"
42 #include "core/dom/Element.h"
43 #include "core/dom/ElementRareData.h"
44 #include "core/dom/ElementTraversal.h"
45 #include "core/dom/ExceptionCode.h"
46 #include "core/dom/LiveNodeList.h"
47 #include "core/dom/NodeRareData.h"
48 #include "core/dom/NodeRenderingTraversal.h"
49 #include "core/dom/NodeTraversal.h"
50 #include "core/dom/ProcessingInstruction.h"
51 #include "core/dom/Range.h"
52 #include "core/dom/StaticNodeList.h"
53 #include "core/dom/TemplateContentDocumentFragment.h"
54 #include "core/dom/Text.h"
55 #include "core/dom/TreeScopeAdopter.h"
56 #include "core/dom/UserActionElementSet.h"
57 #include "core/dom/WheelController.h"
58 #include "core/dom/shadow/ElementShadow.h"
59 #include "core/dom/shadow/InsertionPoint.h"
60 #include "core/dom/shadow/ShadowRoot.h"
61 #include "core/editing/htmlediting.h"
62 #include "core/editing/markup.h"
63 #include "core/events/Event.h"
64 #include "core/events/EventDispatchMediator.h"
65 #include "core/events/EventDispatcher.h"
66 #include "core/events/EventListener.h"
67 #include "core/events/GestureEvent.h"
68 #include "core/events/KeyboardEvent.h"
69 #include "core/events/MouseEvent.h"
70 #include "core/events/MutationEvent.h"
71 #include "core/events/TextEvent.h"
72 #include "core/events/TouchEvent.h"
73 #include "core/events/UIEvent.h"
74 #include "core/events/WheelEvent.h"
75 #include "core/frame/LocalFrame.h"
76 #include "core/html/HTMLAnchorElement.h"
77 #include "core/html/HTMLDialogElement.h"
78 #include "core/html/HTMLFrameOwnerElement.h"
79 #include "core/html/HTMLStyleElement.h"
80 #include "core/page/ContextMenuController.h"
81 #include "core/page/EventHandler.h"
82 #include "core/page/Page.h"
83 #include "core/frame/Settings.h"
84 #include "core/rendering/FlowThreadController.h"
85 #include "core/rendering/RenderBox.h"
86 #include "core/svg/graphics/SVGImage.h"
87 #include "platform/Partitions.h"
88 #include "wtf/HashSet.h"
89 #include "wtf/PassOwnPtr.h"
90 #include "wtf/RefCountedLeakCounter.h"
91 #include "wtf/Vector.h"
92 #include "wtf/text/CString.h"
93 #include "wtf/text/StringBuilder.h"
94
95 using namespace std;
96
97 namespace WebCore {
98
99 using namespace HTMLNames;
100
101 void* Node::operator new(size_t size)
102 {
103     ASSERT(isMainThread());
104     return partitionAlloc(Partitions::getObjectModelPartition(), size);
105 }
106
107 void Node::operator delete(void* ptr)
108 {
109     ASSERT(isMainThread());
110     partitionFree(ptr);
111 }
112
113 #if DUMP_NODE_STATISTICS
114 static HashSet<Node*> liveNodeSet;
115 #endif
116
117 void Node::dumpStatistics()
118 {
119 #if DUMP_NODE_STATISTICS
120     size_t nodesWithRareData = 0;
121
122     size_t elementNodes = 0;
123     size_t attrNodes = 0;
124     size_t textNodes = 0;
125     size_t cdataNodes = 0;
126     size_t commentNodes = 0;
127     size_t piNodes = 0;
128     size_t documentNodes = 0;
129     size_t docTypeNodes = 0;
130     size_t fragmentNodes = 0;
131     size_t shadowRootNodes = 0;
132
133     HashMap<String, size_t> perTagCount;
134
135     size_t attributes = 0;
136     size_t attributesWithAttr = 0;
137     size_t elementsWithAttributeStorage = 0;
138     size_t elementsWithRareData = 0;
139     size_t elementsWithNamedNodeMap = 0;
140
141     for (HashSet<Node*>::iterator it = liveNodeSet.begin(); it != liveNodeSet.end(); ++it) {
142         Node* node = *it;
143
144         if (node->hasRareData()) {
145             ++nodesWithRareData;
146             if (node->isElementNode()) {
147                 ++elementsWithRareData;
148                 if (toElement(node)->hasNamedNodeMap())
149                     ++elementsWithNamedNodeMap;
150             }
151         }
152
153         switch (node->nodeType()) {
154             case ELEMENT_NODE: {
155                 ++elementNodes;
156
157                 // Tag stats
158                 Element* element = toElement(node);
159                 HashMap<String, size_t>::AddResult result = perTagCount.add(element->tagName(), 1);
160                 if (!result.isNewEntry)
161                     result.storedValue->value++;
162
163                 if (ElementData* elementData = element->elementData()) {
164                     attributes += elementData->length();
165                     ++elementsWithAttributeStorage;
166                     for (unsigned i = 0; i < elementData->length(); ++i) {
167                         Attribute* attr = elementData->attributeItem(i);
168                         if (attr->attr())
169                             ++attributesWithAttr;
170                     }
171                 }
172                 break;
173             }
174             case ATTRIBUTE_NODE: {
175                 ++attrNodes;
176                 break;
177             }
178             case TEXT_NODE: {
179                 ++textNodes;
180                 break;
181             }
182             case CDATA_SECTION_NODE: {
183                 ++cdataNodes;
184                 break;
185             }
186             case COMMENT_NODE: {
187                 ++commentNodes;
188                 break;
189             }
190             case PROCESSING_INSTRUCTION_NODE: {
191                 ++piNodes;
192                 break;
193             }
194             case DOCUMENT_NODE: {
195                 ++documentNodes;
196                 break;
197             }
198             case DOCUMENT_TYPE_NODE: {
199                 ++docTypeNodes;
200                 break;
201             }
202             case DOCUMENT_FRAGMENT_NODE: {
203                 if (node->isShadowRoot())
204                     ++shadowRootNodes;
205                 else
206                     ++fragmentNodes;
207                 break;
208             }
209         }
210     }
211
212     printf("Number of Nodes: %d\n\n", liveNodeSet.size());
213     printf("Number of Nodes with RareData: %zu\n\n", nodesWithRareData);
214
215     printf("NodeType distribution:\n");
216     printf("  Number of Element nodes: %zu\n", elementNodes);
217     printf("  Number of Attribute nodes: %zu\n", attrNodes);
218     printf("  Number of Text nodes: %zu\n", textNodes);
219     printf("  Number of CDATASection nodes: %zu\n", cdataNodes);
220     printf("  Number of Comment nodes: %zu\n", commentNodes);
221     printf("  Number of ProcessingInstruction nodes: %zu\n", piNodes);
222     printf("  Number of Document nodes: %zu\n", documentNodes);
223     printf("  Number of DocumentType nodes: %zu\n", docTypeNodes);
224     printf("  Number of DocumentFragment nodes: %zu\n", fragmentNodes);
225     printf("  Number of ShadowRoot nodes: %zu\n", shadowRootNodes);
226
227     printf("Element tag name distibution:\n");
228     for (HashMap<String, size_t>::iterator it = perTagCount.begin(); it != perTagCount.end(); ++it)
229         printf("  Number of <%s> tags: %zu\n", it->key.utf8().data(), it->value);
230
231     printf("Attributes:\n");
232     printf("  Number of Attributes (non-Node and Node): %zu [%zu]\n", attributes, sizeof(Attribute));
233     printf("  Number of Attributes with an Attr: %zu\n", attributesWithAttr);
234     printf("  Number of Elements with attribute storage: %zu [%zu]\n", elementsWithAttributeStorage, sizeof(ElementData));
235     printf("  Number of Elements with RareData: %zu\n", elementsWithRareData);
236     printf("  Number of Elements with NamedNodeMap: %zu [%zu]\n", elementsWithNamedNodeMap, sizeof(NamedNodeMap));
237 #endif
238 }
239
240 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, nodeCounter, ("WebCoreNode"));
241
242 void Node::trackForDebugging()
243 {
244 #ifndef NDEBUG
245     nodeCounter.increment();
246 #endif
247
248 #if DUMP_NODE_STATISTICS
249     liveNodeSet.add(this);
250 #endif
251 }
252
253 Node::~Node()
254 {
255 #ifndef NDEBUG
256     nodeCounter.decrement();
257 #endif
258
259 #if DUMP_NODE_STATISTICS
260     liveNodeSet.remove(this);
261 #endif
262
263     if (hasRareData())
264         clearRareData();
265
266     RELEASE_ASSERT(!renderer());
267
268     if (!isContainerNode())
269         willBeDeletedFromDocument();
270
271     if (m_previous)
272         m_previous->setNextSibling(0);
273     if (m_next)
274         m_next->setPreviousSibling(0);
275
276     if (m_treeScope)
277         m_treeScope->guardDeref();
278
279     InspectorCounters::decrementCounter(InspectorCounters::NodeCounter);
280 }
281
282 void Node::willBeDeletedFromDocument()
283 {
284     if (!isTreeScopeInitialized())
285         return;
286
287     Document& document = this->document();
288
289     if (hasEventTargetData()) {
290         clearEventTargetData();
291         document.didClearTouchEventHandlers(this);
292     }
293
294     if (AXObjectCache* cache = document.existingAXObjectCache())
295         cache->remove(this);
296
297     document.markers().removeMarkers(this);
298 }
299
300 NodeRareData* Node::rareData() const
301 {
302     ASSERT_WITH_SECURITY_IMPLICATION(hasRareData());
303     return static_cast<NodeRareData*>(m_data.m_rareData);
304 }
305
306 NodeRareData& Node::ensureRareData()
307 {
308     if (hasRareData())
309         return *rareData();
310
311     NodeRareData* data;
312     if (isElementNode())
313         data = ElementRareData::create(m_data.m_renderer).leakPtr();
314     else
315         data = NodeRareData::create(m_data.m_renderer).leakPtr();
316     ASSERT(data);
317
318     m_data.m_rareData = data;
319     setFlag(HasRareDataFlag);
320     return *data;
321 }
322
323 void Node::clearRareData()
324 {
325     ASSERT(hasRareData());
326     ASSERT(!transientMutationObserverRegistry() || transientMutationObserverRegistry()->isEmpty());
327
328     RenderObject* renderer = m_data.m_rareData->renderer();
329     if (isElementNode())
330         delete static_cast<ElementRareData*>(m_data.m_rareData);
331     else
332         delete static_cast<NodeRareData*>(m_data.m_rareData);
333     m_data.m_renderer = renderer;
334     clearFlag(HasRareDataFlag);
335 }
336
337 Node* Node::toNode()
338 {
339     return this;
340 }
341
342 short Node::tabIndex() const
343 {
344     return 0;
345 }
346
347 String Node::nodeValue() const
348 {
349     return String();
350 }
351
352 void Node::setNodeValue(const String&)
353 {
354     // By default, setting nodeValue has no effect.
355 }
356
357 PassRefPtr<NodeList> Node::childNodes()
358 {
359     if (isContainerNode())
360         return ensureRareData().ensureNodeLists().ensureChildNodeList(toContainerNode(*this));
361     return ensureRareData().ensureNodeLists().ensureEmptyChildNodeList(*this);
362 }
363
364 Node& Node::lastDescendant() const
365 {
366     Node* n = const_cast<Node*>(this);
367     while (n && n->lastChild())
368         n = n->lastChild();
369     ASSERT(n);
370     return *n;
371 }
372
373 Node* Node::pseudoAwarePreviousSibling() const
374 {
375     if (parentElement() && !previousSibling()) {
376         Element* parent = parentElement();
377         if (isAfterPseudoElement() && parent->lastChild())
378             return parent->lastChild();
379         if (!isBeforePseudoElement())
380             return parent->pseudoElement(BEFORE);
381     }
382     return previousSibling();
383 }
384
385 Node* Node::pseudoAwareNextSibling() const
386 {
387     if (parentElement() && !nextSibling()) {
388         Element* parent = parentElement();
389         if (isBeforePseudoElement() && parent->firstChild())
390             return parent->firstChild();
391         if (!isAfterPseudoElement())
392             return parent->pseudoElement(AFTER);
393     }
394     return nextSibling();
395 }
396
397 Node* Node::pseudoAwareFirstChild() const
398 {
399     if (isElementNode()) {
400         const Element* currentElement = toElement(this);
401         Node* first = currentElement->pseudoElement(BEFORE);
402         if (first)
403             return first;
404         first = currentElement->firstChild();
405         if (!first)
406             first = currentElement->pseudoElement(AFTER);
407         return first;
408     }
409
410     return firstChild();
411 }
412
413 Node* Node::pseudoAwareLastChild() const
414 {
415     if (isElementNode()) {
416         const Element* currentElement = toElement(this);
417         Node* last = currentElement->pseudoElement(AFTER);
418         if (last)
419             return last;
420         last = currentElement->lastChild();
421         if (!last)
422             last = currentElement->pseudoElement(BEFORE);
423         return last;
424     }
425
426     return lastChild();
427 }
428
429 void Node::insertBefore(PassRefPtr<Node> newChild, Node* refChild, ExceptionState& exceptionState)
430 {
431     if (isContainerNode())
432         toContainerNode(this)->insertBefore(newChild, refChild, exceptionState);
433     else
434         exceptionState.throwDOMException(HierarchyRequestError, "This node type does not support this method.");
435 }
436
437 void Node::replaceChild(PassRefPtr<Node> newChild, Node* oldChild, ExceptionState& exceptionState)
438 {
439     if (isContainerNode())
440         toContainerNode(this)->replaceChild(newChild, oldChild, exceptionState);
441     else
442         exceptionState.throwDOMException(HierarchyRequestError,  "This node type does not support this method.");
443 }
444
445 void Node::removeChild(Node* oldChild, ExceptionState& exceptionState)
446 {
447     if (isContainerNode())
448         toContainerNode(this)->removeChild(oldChild, exceptionState);
449     else
450         exceptionState.throwDOMException(NotFoundError, "This node type does not support this method.");
451 }
452
453 void Node::appendChild(PassRefPtr<Node> newChild, ExceptionState& exceptionState)
454 {
455     if (isContainerNode())
456         toContainerNode(this)->appendChild(newChild, exceptionState);
457     else
458         exceptionState.throwDOMException(HierarchyRequestError, "This node type does not support this method.");
459 }
460
461 void Node::remove(ExceptionState& exceptionState)
462 {
463     if (ContainerNode* parent = parentNode())
464         parent->removeChild(this, exceptionState);
465 }
466
467 void Node::normalize()
468 {
469     // Go through the subtree beneath us, normalizing all nodes. This means that
470     // any two adjacent text nodes are merged and any empty text nodes are removed.
471
472     RefPtr<Node> node = this;
473     while (Node* firstChild = node->firstChild())
474         node = firstChild;
475     while (node) {
476         NodeType type = node->nodeType();
477         if (type == ELEMENT_NODE)
478             toElement(node)->normalizeAttributes();
479
480         if (node == this)
481             break;
482
483         if (type == TEXT_NODE)
484             node = toText(node)->mergeNextSiblingNodesIfPossible();
485         else
486             node = NodeTraversal::nextPostOrder(*node);
487     }
488 }
489
490 const AtomicString& Node::localName() const
491 {
492     return nullAtom;
493 }
494
495 const AtomicString& Node::namespaceURI() const
496 {
497     return nullAtom;
498 }
499
500 bool Node::isContentEditable(UserSelectAllTreatment treatment)
501 {
502     document().updateRenderTreeIfNeeded();
503     return rendererIsEditable(Editable, treatment);
504 }
505
506 bool Node::isContentRichlyEditable()
507 {
508     document().updateRenderTreeIfNeeded();
509     return rendererIsEditable(RichlyEditable, UserSelectAllIsAlwaysNonEditable);
510 }
511
512 bool Node::rendererIsEditable(EditableLevel editableLevel, UserSelectAllTreatment treatment) const
513 {
514     if (isPseudoElement())
515         return false;
516
517     // Ideally we'd call ASSERT(!needsStyleRecalc()) here, but
518     // ContainerNode::setFocus() calls setNeedsStyleRecalc(), so the assertion
519     // would fire in the middle of Document::setFocusedNode().
520
521     for (const Node* node = this; node; node = node->parentNode()) {
522         if ((node->isHTMLElement() || node->isDocumentNode()) && node->renderer()) {
523             // Elements with user-select: all style are considered atomic
524             // therefore non editable.
525             if (Position::nodeIsUserSelectAll(node) && treatment == UserSelectAllIsAlwaysNonEditable)
526                 return false;
527             switch (node->renderer()->style()->userModify()) {
528             case READ_ONLY:
529                 return false;
530             case READ_WRITE:
531                 return true;
532             case READ_WRITE_PLAINTEXT_ONLY:
533                 return editableLevel != RichlyEditable;
534             }
535             ASSERT_NOT_REACHED();
536             return false;
537         }
538     }
539
540     return false;
541 }
542
543 bool Node::isEditableToAccessibility(EditableLevel editableLevel) const
544 {
545     if (rendererIsEditable(editableLevel))
546         return true;
547
548     // FIXME: Respect editableLevel for ARIA editable elements.
549     if (editableLevel == RichlyEditable)
550         return false;
551
552     ASSERT(AXObjectCache::accessibilityEnabled());
553     ASSERT(document().existingAXObjectCache());
554
555     if (AXObjectCache* cache = document().existingAXObjectCache())
556         return cache->rootAXEditableElement(this);
557
558     return false;
559 }
560
561 bool Node::shouldUseInputMethod()
562 {
563     return isContentEditable(UserSelectAllIsAlwaysNonEditable);
564 }
565
566 RenderBox* Node::renderBox() const
567 {
568     RenderObject* renderer = this->renderer();
569     return renderer && renderer->isBox() ? toRenderBox(renderer) : 0;
570 }
571
572 RenderBoxModelObject* Node::renderBoxModelObject() const
573 {
574     RenderObject* renderer = this->renderer();
575     return renderer && renderer->isBoxModelObject() ? toRenderBoxModelObject(renderer) : 0;
576 }
577
578 LayoutRect Node::boundingBox() const
579 {
580     if (renderer())
581         return renderer()->absoluteBoundingBoxRect();
582     return LayoutRect();
583 }
584
585 bool Node::hasNonEmptyBoundingBox() const
586 {
587     // Before calling absoluteRects, check for the common case where the renderer
588     // is non-empty, since this is a faster check and almost always returns true.
589     RenderBoxModelObject* box = renderBoxModelObject();
590     if (!box)
591         return false;
592     if (!box->borderBoundingBox().isEmpty())
593         return true;
594
595     Vector<IntRect> rects;
596     FloatPoint absPos = renderer()->localToAbsolute();
597     renderer()->absoluteRects(rects, flooredLayoutPoint(absPos));
598     size_t n = rects.size();
599     for (size_t i = 0; i < n; ++i)
600         if (!rects[i].isEmpty())
601             return true;
602
603     return false;
604 }
605
606 #ifndef NDEBUG
607 inline static ShadowRoot* oldestShadowRootFor(const Node* node)
608 {
609     if (!node->isElementNode())
610         return 0;
611     if (ElementShadow* shadow = toElement(node)->shadow())
612         return shadow->oldestShadowRoot();
613     return 0;
614 }
615 #endif
616
617 void Node::recalcDistribution()
618 {
619     if (isElementNode()) {
620         if (ElementShadow* shadow = toElement(this)->shadow())
621             shadow->distributeIfNeeded();
622     }
623
624     for (Node* child = firstChild(); child; child = child->nextSibling()) {
625         if (child->childNeedsDistributionRecalc())
626             child->recalcDistribution();
627     }
628
629     for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot()) {
630         if (root->childNeedsDistributionRecalc())
631             root->recalcDistribution();
632     }
633
634     clearChildNeedsDistributionRecalc();
635 }
636
637 void Node::setIsLink(bool isLink)
638 {
639     setFlag(isLink && !SVGImage::isInSVGImage(toElement(this)), IsLinkFlag);
640 }
641
642 void Node::setNeedsStyleInvalidation()
643 {
644     setFlag(NeedsStyleInvalidation);
645     markAncestorsWithChildNeedsStyleInvalidation();
646 }
647
648 void Node::markAncestorsWithChildNeedsStyleInvalidation()
649 {
650     for (Node* node = parentOrShadowHostNode(); node && !node->childNeedsStyleInvalidation(); node = node->parentOrShadowHostNode())
651         node->setChildNeedsStyleInvalidation();
652     if (document().childNeedsStyleInvalidation())
653         document().scheduleRenderTreeUpdate();
654 }
655
656 void Node::markAncestorsWithChildNeedsDistributionRecalc()
657 {
658     for (Node* node = this; node && !node->childNeedsDistributionRecalc(); node = node->parentOrShadowHostNode())
659         node->setChildNeedsDistributionRecalc();
660     if (document().childNeedsDistributionRecalc())
661         document().scheduleRenderTreeUpdate();
662 }
663
664 namespace {
665
666 unsigned styledSubtreeSize(const Node*);
667
668 unsigned styledSubtreeSizeIgnoringSelfAndShadowRoots(const Node* rootNode)
669 {
670     unsigned nodeCount = 0;
671     for (Node* child = rootNode->firstChild(); child; child = child->nextSibling())
672         nodeCount += styledSubtreeSize(child);
673     return nodeCount;
674 }
675
676 unsigned styledSubtreeSize(const Node* rootNode)
677 {
678     if (rootNode->isTextNode())
679         return 1;
680     if (!rootNode->isElementNode())
681         return 0;
682
683     // FIXME: We should use a shadow-tree aware node-iterator when such exists.
684     unsigned nodeCount = 1 + styledSubtreeSizeIgnoringSelfAndShadowRoots(rootNode);
685
686     // ShadowRoots don't have style (so don't count them), but their children might.
687     for (ShadowRoot* shadowRoot = rootNode->youngestShadowRoot(); shadowRoot; shadowRoot = shadowRoot->olderShadowRoot())
688         nodeCount += styledSubtreeSizeIgnoringSelfAndShadowRoots(shadowRoot);
689
690     return nodeCount;
691 }
692
693 PassRefPtr<JSONArray> jsStackAsJSONArray()
694 {
695     RefPtr<JSONArray> jsonArray = JSONArray::create();
696     RefPtr<ScriptCallStack> stack = createScriptCallStack(10);
697     if (!stack)
698         return jsonArray.release();
699     for (size_t i = 0; i < stack->size(); i++)
700         jsonArray->pushString(stack->at(i).functionName());
701     return jsonArray.release();
702 }
703
704 PassRefPtr<JSONObject> jsonObjectForStyleInvalidation(unsigned nodeCount, const Node* rootNode)
705 {
706     RefPtr<JSONObject> jsonObject = JSONObject::create();
707     jsonObject->setNumber("node_count", nodeCount);
708     jsonObject->setString("root_node", rootNode->debugName());
709     jsonObject->setArray("js_stack", jsStackAsJSONArray());
710     return jsonObject.release();
711 }
712
713 } // anonymous namespace'd functions supporting traceStyleChange
714
715 void Node::traceStyleChange(StyleChangeType changeType)
716 {
717     static const unsigned kMinLoggedSize = 100;
718     unsigned nodeCount = styledSubtreeSize(this);
719     if (nodeCount < kMinLoggedSize)
720         return;
721
722     TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("style.debug"),
723         "Node::setNeedsStyleRecalc",
724         "data", jsonObjectForStyleInvalidation(nodeCount, this)->toJSONString().ascii()
725     );
726 }
727
728 void Node::traceStyleChangeIfNeeded(StyleChangeType changeType)
729 {
730     // TRACE_EVENT_CATEGORY_GROUP_ENABLED macro loads a global static bool into our local bool.
731     bool styleTracingEnabled;
732     TRACE_EVENT_CATEGORY_GROUP_ENABLED(TRACE_DISABLED_BY_DEFAULT("style.debug"), &styleTracingEnabled);
733     if (UNLIKELY(styleTracingEnabled))
734         traceStyleChange(changeType);
735 }
736
737 inline void Node::setStyleChange(StyleChangeType changeType)
738 {
739     m_nodeFlags = (m_nodeFlags & ~StyleChangeMask) | changeType;
740 }
741
742 void Node::markAncestorsWithChildNeedsStyleRecalc()
743 {
744     for (ContainerNode* p = parentOrShadowHostNode(); p && !p->childNeedsStyleRecalc(); p = p->parentOrShadowHostNode())
745         p->setChildNeedsStyleRecalc();
746
747     if (document().needsStyleRecalc() || document().childNeedsStyleRecalc())
748         document().scheduleRenderTreeUpdate();
749 }
750
751 void Node::setNeedsStyleRecalc(StyleChangeType changeType)
752 {
753     ASSERT(changeType != NoStyleChange);
754     if (!inActiveDocument())
755         return;
756
757     StyleChangeType existingChangeType = styleChangeType();
758     if (changeType > existingChangeType) {
759         setStyleChange(changeType);
760         if (changeType >= SubtreeStyleChange)
761             traceStyleChangeIfNeeded(changeType);
762     }
763
764     if (existingChangeType == NoStyleChange)
765         markAncestorsWithChildNeedsStyleRecalc();
766
767     if (isElementNode() && hasRareData())
768         toElement(*this).setAnimationStyleChange(false);
769 }
770
771 void Node::clearNeedsStyleRecalc()
772 {
773     m_nodeFlags &= ~StyleChangeMask;
774
775     clearNeedsLayerUpdate();
776
777     if (isElementNode() && hasRareData())
778         toElement(*this).setAnimationStyleChange(false);
779 }
780
781 bool Node::inActiveDocument() const
782 {
783     return inDocument() && document().isActive();
784 }
785
786 Node* Node::focusDelegate()
787 {
788     return this;
789 }
790
791 bool Node::shouldHaveFocusAppearance() const
792 {
793     ASSERT(focused());
794     return true;
795 }
796
797 bool Node::isInert() const
798 {
799     const HTMLDialogElement* dialog = document().activeModalDialog();
800     if (dialog && this != document() && !NodeRenderingTraversal::contains(dialog, this))
801         return true;
802     return document().ownerElement() && document().ownerElement()->isInert();
803 }
804
805 unsigned Node::nodeIndex() const
806 {
807     Node *_tempNode = previousSibling();
808     unsigned count=0;
809     for ( count=0; _tempNode; count++ )
810         _tempNode = _tempNode->previousSibling();
811     return count;
812 }
813
814 void Node::invalidateNodeListCachesInAncestors(const QualifiedName* attrName, Element* attributeOwnerElement)
815 {
816     if (hasRareData() && (!attrName || isAttributeNode())) {
817         if (NodeListsNodeData* lists = rareData()->nodeLists())
818             lists->clearChildNodeListCache();
819     }
820
821     // Modifications to attributes that are not associated with an Element can't invalidate NodeList caches.
822     if (attrName && !attributeOwnerElement)
823         return;
824
825     if (!document().shouldInvalidateNodeListCaches(attrName))
826         return;
827
828     document().invalidateNodeListCaches(attrName);
829
830     for (Node* node = this; node; node = node->parentNode()) {
831         if (NodeListsNodeData* lists = node->nodeLists())
832             lists->invalidateCaches(attrName);
833     }
834 }
835
836 NodeListsNodeData* Node::nodeLists()
837 {
838     return hasRareData() ? rareData()->nodeLists() : 0;
839 }
840
841 void Node::clearNodeLists()
842 {
843     rareData()->clearNodeLists();
844 }
845
846 bool Node::isDescendantOf(const Node *other) const
847 {
848     // Return true if other is an ancestor of this, otherwise false
849     if (!other || !other->hasChildren() || inDocument() != other->inDocument())
850         return false;
851     if (other->treeScope() != treeScope())
852         return false;
853     if (other->isTreeScope())
854         return !isTreeScope();
855     for (const ContainerNode* n = parentNode(); n; n = n->parentNode()) {
856         if (n == other)
857             return true;
858     }
859     return false;
860 }
861
862 bool Node::contains(const Node* node) const
863 {
864     if (!node)
865         return false;
866     return this == node || node->isDescendantOf(this);
867 }
868
869 bool Node::containsIncludingShadowDOM(const Node* node) const
870 {
871     if (!node)
872         return false;
873
874     if (this == node)
875         return true;
876
877     if (document() != node->document())
878         return false;
879
880     if (inDocument() != node->inDocument())
881         return false;
882
883     bool hasChildren = isContainerNode() && toContainerNode(this)->hasChildren();
884     bool hasShadow = isElementNode() && toElement(this)->shadow();
885     if (!hasChildren && !hasShadow)
886         return false;
887
888     for (; node; node = node->shadowHost()) {
889         if (treeScope() == node->treeScope())
890             return contains(node);
891     }
892
893     return false;
894 }
895
896 bool Node::containsIncludingHostElements(const Node& node) const
897 {
898     const Node* current = &node;
899     do {
900         if (current == this)
901             return true;
902         if (current->isDocumentFragment() && toDocumentFragment(current)->isTemplateContent())
903             current = static_cast<const TemplateContentDocumentFragment*>(current)->host();
904         else
905             current = current->parentOrShadowHostNode();
906     } while (current);
907     return false;
908 }
909
910 Node* Node::commonAncestor(const Node& other, Node* (*parent)(const Node&))
911 {
912     if (this == other)
913         return this;
914     if (document() != other.document())
915         return 0;
916     int thisDepth = 0;
917     for (Node* node = this; node; node = parent(*node)) {
918         if (node == &other)
919             return node;
920         thisDepth++;
921     }
922     int otherDepth = 0;
923     for (const Node* node = &other; node; node = parent(*node)) {
924         if (node == this)
925             return this;
926         otherDepth++;
927     }
928     Node* thisIterator = this;
929     const Node* otherIterator = &other;
930     if (thisDepth > otherDepth) {
931         for (int i = thisDepth; i > otherDepth; --i)
932             thisIterator = parent(*thisIterator);
933     } else if (otherDepth > thisDepth) {
934         for (int i = otherDepth; i > thisDepth; --i)
935             otherIterator = parent(*otherIterator);
936     }
937     while (thisIterator) {
938         if (thisIterator == otherIterator)
939             return thisIterator;
940         thisIterator = parent(*thisIterator);
941         otherIterator = parent(*otherIterator);
942     }
943     ASSERT(!otherIterator);
944     return 0;
945 }
946
947 void Node::reattach(const AttachContext& context)
948 {
949     AttachContext reattachContext(context);
950     reattachContext.performingReattach = true;
951
952     // We only need to detach if the node has already been through attach().
953     if (styleChangeType() < NeedsReattachStyleChange)
954         detach(reattachContext);
955     attach(reattachContext);
956 }
957
958 void Node::attach(const AttachContext&)
959 {
960     ASSERT(document().inStyleRecalc() || isDocumentNode());
961     ASSERT(needsAttach());
962     ASSERT(!renderer() || (renderer()->style() && (renderer()->parent() || renderer()->isRenderView())));
963
964     clearNeedsStyleRecalc();
965
966     if (AXObjectCache* cache = document().axObjectCache())
967         cache->updateCacheAfterNodeIsAttached(this);
968 }
969
970 #ifndef NDEBUG
971 static Node* detachingNode;
972
973 bool Node::inDetach() const
974 {
975     return detachingNode == this;
976 }
977 #endif
978
979 void Node::detach(const AttachContext& context)
980 {
981 #ifndef NDEBUG
982     ASSERT(!detachingNode);
983     detachingNode = this;
984 #endif
985
986     if (renderer())
987         renderer()->destroyAndCleanupAnonymousWrappers();
988     setRenderer(0);
989
990     // Do not remove the element's hovered and active status
991     // if performing a reattach.
992     if (!context.performingReattach) {
993         Document& doc = document();
994         if (isUserActionElement()) {
995             if (hovered())
996                 doc.hoveredNodeDetached(this);
997             if (inActiveChain())
998                 doc.activeChainNodeDetached(this);
999             doc.userActionElements().didDetach(this);
1000         }
1001     }
1002
1003     setStyleChange(NeedsReattachStyleChange);
1004     setChildNeedsStyleRecalc();
1005
1006     if (StyleResolver* resolver = document().styleResolver())
1007         resolver->ruleFeatureSet().clearStyleInvalidation(this);
1008
1009 #ifndef NDEBUG
1010     detachingNode = 0;
1011 #endif
1012 }
1013
1014 void Node::reattachWhitespaceSiblings(Text* start)
1015 {
1016     for (Node* sibling = start; sibling; sibling = sibling->nextSibling()) {
1017         if (sibling->isTextNode() && toText(sibling)->containsOnlyWhitespace()) {
1018             bool hadRenderer = sibling->hasRenderer();
1019             sibling->reattach();
1020             // If the reattach didn't toggle the visibility of the whitespace we don't
1021             // need to continue reattaching siblings since they won't toggle visibility
1022             // either.
1023             if (hadRenderer == sibling->hasRenderer())
1024                 return;
1025         } else if (sibling->renderer()) {
1026             return;
1027         }
1028     }
1029 }
1030
1031 // FIXME: This code is used by editing.  Seems like it could move over there and not pollute Node.
1032 Node *Node::previousNodeConsideringAtomicNodes() const
1033 {
1034     if (previousSibling()) {
1035         Node *n = previousSibling();
1036         while (!isAtomicNode(n) && n->lastChild())
1037             n = n->lastChild();
1038         return n;
1039     }
1040     else if (parentNode()) {
1041         return parentNode();
1042     }
1043     else {
1044         return 0;
1045     }
1046 }
1047
1048 Node *Node::nextNodeConsideringAtomicNodes() const
1049 {
1050     if (!isAtomicNode(this) && firstChild())
1051         return firstChild();
1052     if (nextSibling())
1053         return nextSibling();
1054     const Node *n = this;
1055     while (n && !n->nextSibling())
1056         n = n->parentNode();
1057     if (n)
1058         return n->nextSibling();
1059     return 0;
1060 }
1061
1062 Node *Node::previousLeafNode() const
1063 {
1064     Node *node = previousNodeConsideringAtomicNodes();
1065     while (node) {
1066         if (isAtomicNode(node))
1067             return node;
1068         node = node->previousNodeConsideringAtomicNodes();
1069     }
1070     return 0;
1071 }
1072
1073 Node *Node::nextLeafNode() const
1074 {
1075     Node *node = nextNodeConsideringAtomicNodes();
1076     while (node) {
1077         if (isAtomicNode(node))
1078             return node;
1079         node = node->nextNodeConsideringAtomicNodes();
1080     }
1081     return 0;
1082 }
1083
1084 RenderStyle* Node::virtualComputedStyle(PseudoId pseudoElementSpecifier)
1085 {
1086     return parentOrShadowHostNode() ? parentOrShadowHostNode()->computedStyle(pseudoElementSpecifier) : 0;
1087 }
1088
1089 int Node::maxCharacterOffset() const
1090 {
1091     ASSERT_NOT_REACHED();
1092     return 0;
1093 }
1094
1095 // FIXME: Shouldn't these functions be in the editing code?  Code that asks questions about HTML in the core DOM class
1096 // is obviously misplaced.
1097 bool Node::canStartSelection() const
1098 {
1099     if (rendererIsEditable())
1100         return true;
1101
1102     if (renderer()) {
1103         RenderStyle* style = renderer()->style();
1104         // We allow selections to begin within an element that has -webkit-user-select: none set,
1105         // but if the element is draggable then dragging should take priority over selection.
1106         if (style->userDrag() == DRAG_ELEMENT && style->userSelect() == SELECT_NONE)
1107             return false;
1108     }
1109     return parentOrShadowHostNode() ? parentOrShadowHostNode()->canStartSelection() : true;
1110 }
1111
1112 Element* Node::shadowHost() const
1113 {
1114     if (ShadowRoot* root = containingShadowRoot())
1115         return root->host();
1116     return 0;
1117 }
1118
1119 Node* Node::deprecatedShadowAncestorNode() const
1120 {
1121     if (ShadowRoot* root = containingShadowRoot())
1122         return root->host();
1123
1124     return const_cast<Node*>(this);
1125 }
1126
1127 ShadowRoot* Node::containingShadowRoot() const
1128 {
1129     Node& root = treeScope().rootNode();
1130     return root.isShadowRoot() ? toShadowRoot(&root) : 0;
1131 }
1132
1133 Node* Node::nonBoundaryShadowTreeRootNode()
1134 {
1135     ASSERT(!isShadowRoot());
1136     Node* root = this;
1137     while (root) {
1138         if (root->isShadowRoot())
1139             return root;
1140         Node* parent = root->parentOrShadowHostNode();
1141         if (parent && parent->isShadowRoot())
1142             return root;
1143         root = parent;
1144     }
1145     return 0;
1146 }
1147
1148 ContainerNode* Node::nonShadowBoundaryParentNode() const
1149 {
1150     ContainerNode* parent = parentNode();
1151     return parent && !parent->isShadowRoot() ? parent : 0;
1152 }
1153
1154 Element* Node::parentOrShadowHostElement() const
1155 {
1156     ContainerNode* parent = parentOrShadowHostNode();
1157     if (!parent)
1158         return 0;
1159
1160     if (parent->isShadowRoot())
1161         return toShadowRoot(parent)->host();
1162
1163     if (!parent->isElementNode())
1164         return 0;
1165
1166     return toElement(parent);
1167 }
1168
1169 ContainerNode* Node::parentOrShadowHostOrTemplateHostNode() const
1170 {
1171     if (isDocumentFragment() && toDocumentFragment(this)->isTemplateContent())
1172         return static_cast<const TemplateContentDocumentFragment*>(this)->host();
1173     return parentOrShadowHostNode();
1174 }
1175
1176 bool Node::isBlockFlowElement() const
1177 {
1178     return isElementNode() && renderer() && renderer()->isRenderBlockFlow();
1179 }
1180
1181 Element *Node::enclosingBlockFlowElement() const
1182 {
1183     Node *n = const_cast<Node *>(this);
1184     if (isBlockFlowElement())
1185         return toElement(n);
1186
1187     while (1) {
1188         n = n->parentNode();
1189         if (!n)
1190             break;
1191         if (n->isBlockFlowElement() || isHTMLBodyElement(*n))
1192             return toElement(n);
1193     }
1194     return 0;
1195 }
1196
1197 bool Node::isRootEditableElement() const
1198 {
1199     return rendererIsEditable() && isElementNode() && (!parentNode() || !parentNode()->rendererIsEditable()
1200         || !parentNode()->isElementNode() || isHTMLBodyElement((*this)));
1201 }
1202
1203 Element* Node::rootEditableElement(EditableType editableType) const
1204 {
1205     if (editableType == HasEditableAXRole) {
1206         if (AXObjectCache* cache = document().existingAXObjectCache())
1207             return const_cast<Element*>(cache->rootAXEditableElement(this));
1208     }
1209
1210     return rootEditableElement();
1211 }
1212
1213 Element* Node::rootEditableElement() const
1214 {
1215     Element* result = 0;
1216     for (Node* n = const_cast<Node*>(this); n && n->rendererIsEditable(); n = n->parentNode()) {
1217         if (n->isElementNode())
1218             result = toElement(n);
1219         if (isHTMLBodyElement(*n))
1220             break;
1221     }
1222     return result;
1223 }
1224
1225 bool Node::inSameContainingBlockFlowElement(Node *n)
1226 {
1227     return n ? enclosingBlockFlowElement() == n->enclosingBlockFlowElement() : false;
1228 }
1229
1230 // FIXME: End of obviously misplaced HTML editing functions.  Try to move these out of Node.
1231
1232 Document* Node::ownerDocument() const
1233 {
1234     Document* doc = &document();
1235     return doc == this ? 0 : doc;
1236 }
1237
1238 KURL Node::baseURI() const
1239 {
1240     return parentNode() ? parentNode()->baseURI() : KURL();
1241 }
1242
1243 bool Node::isEqualNode(Node* other) const
1244 {
1245     if (!other)
1246         return false;
1247
1248     NodeType nodeType = this->nodeType();
1249     if (nodeType != other->nodeType())
1250         return false;
1251
1252     if (nodeName() != other->nodeName())
1253         return false;
1254
1255     if (localName() != other->localName())
1256         return false;
1257
1258     if (namespaceURI() != other->namespaceURI())
1259         return false;
1260
1261     if (nodeValue() != other->nodeValue())
1262         return false;
1263
1264     if (isElementNode() && !toElement(this)->hasEquivalentAttributes(toElement(other)))
1265         return false;
1266
1267     Node* child = firstChild();
1268     Node* otherChild = other->firstChild();
1269
1270     while (child) {
1271         if (!child->isEqualNode(otherChild))
1272             return false;
1273
1274         child = child->nextSibling();
1275         otherChild = otherChild->nextSibling();
1276     }
1277
1278     if (otherChild)
1279         return false;
1280
1281     if (isDocumentTypeNode()) {
1282         const DocumentType* documentTypeThis = toDocumentType(this);
1283         const DocumentType* documentTypeOther = toDocumentType(other);
1284
1285         if (documentTypeThis->publicId() != documentTypeOther->publicId())
1286             return false;
1287
1288         if (documentTypeThis->systemId() != documentTypeOther->systemId())
1289             return false;
1290
1291         if (documentTypeThis->internalSubset() != documentTypeOther->internalSubset())
1292             return false;
1293     }
1294
1295     return true;
1296 }
1297
1298 bool Node::isDefaultNamespace(const AtomicString& namespaceURIMaybeEmpty) const
1299 {
1300     const AtomicString& namespaceURI = namespaceURIMaybeEmpty.isEmpty() ? nullAtom : namespaceURIMaybeEmpty;
1301
1302     switch (nodeType()) {
1303         case ELEMENT_NODE: {
1304             const Element* elem = toElement(this);
1305
1306             if (elem->prefix().isNull())
1307                 return elem->namespaceURI() == namespaceURI;
1308
1309             if (elem->hasAttributes()) {
1310                 unsigned attributeCount = elem->attributeCount();
1311                 for (unsigned i = 0; i < attributeCount; ++i) {
1312                     const Attribute& attr = elem->attributeItem(i);
1313
1314                     if (attr.localName() == xmlnsAtom)
1315                         return attr.value() == namespaceURI;
1316                 }
1317             }
1318
1319             if (Element* parent = parentElement())
1320                 return parent->isDefaultNamespace(namespaceURI);
1321
1322             return false;
1323         }
1324         case DOCUMENT_NODE:
1325             if (Element* de = toDocument(this)->documentElement())
1326                 return de->isDefaultNamespace(namespaceURI);
1327             return false;
1328         case DOCUMENT_TYPE_NODE:
1329         case DOCUMENT_FRAGMENT_NODE:
1330             return false;
1331         case ATTRIBUTE_NODE: {
1332             const Attr* attr = toAttr(this);
1333             if (attr->ownerElement())
1334                 return attr->ownerElement()->isDefaultNamespace(namespaceURI);
1335             return false;
1336         }
1337         default:
1338             if (Element* parent = parentElement())
1339                 return parent->isDefaultNamespace(namespaceURI);
1340             return false;
1341     }
1342 }
1343
1344 const AtomicString& Node::lookupPrefix(const AtomicString& namespaceURI) const
1345 {
1346     // Implemented according to
1347     // http://dom.spec.whatwg.org/#dom-node-lookupprefix
1348
1349     if (namespaceURI.isEmpty() || namespaceURI.isNull())
1350         return nullAtom;
1351
1352     const Element* context;
1353
1354     switch (nodeType()) {
1355         case ELEMENT_NODE:
1356             context = toElement(this);
1357             break;
1358         case DOCUMENT_NODE:
1359             context = toDocument(this)->documentElement();
1360             break;
1361         case DOCUMENT_FRAGMENT_NODE:
1362         case DOCUMENT_TYPE_NODE:
1363             context = 0;
1364             break;
1365         // FIXME: Remove this when Attr no longer extends Node (CR305105)
1366         case ATTRIBUTE_NODE:
1367             context = toAttr(this)->ownerElement();
1368             break;
1369         default:
1370             context = parentElement();
1371             break;
1372     }
1373
1374     if (!context)
1375         return nullAtom;
1376
1377     return context->locateNamespacePrefix(namespaceURI);
1378 }
1379
1380 const AtomicString& Node::lookupNamespaceURI(const String& prefix) const
1381 {
1382     // Implemented according to
1383     // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/namespaces-algorithms.html#lookupNamespaceURIAlgo
1384
1385     if (!prefix.isNull() && prefix.isEmpty())
1386         return nullAtom;
1387
1388     switch (nodeType()) {
1389         case ELEMENT_NODE: {
1390             const Element *elem = toElement(this);
1391
1392             if (!elem->namespaceURI().isNull() && elem->prefix() == prefix)
1393                 return elem->namespaceURI();
1394
1395             if (elem->hasAttributes()) {
1396                 unsigned attributeCount = elem->attributeCount();
1397                 for (unsigned i = 0; i < attributeCount; ++i) {
1398                     const Attribute& attr = elem->attributeItem(i);
1399
1400                     if (attr.prefix() == xmlnsAtom && attr.localName() == prefix) {
1401                         if (!attr.value().isEmpty())
1402                             return attr.value();
1403
1404                         return nullAtom;
1405                     }
1406                     if (attr.localName() == xmlnsAtom && prefix.isNull()) {
1407                         if (!attr.value().isEmpty())
1408                             return attr.value();
1409
1410                         return nullAtom;
1411                     }
1412                 }
1413             }
1414             if (Element* parent = parentElement())
1415                 return parent->lookupNamespaceURI(prefix);
1416             return nullAtom;
1417         }
1418         case DOCUMENT_NODE:
1419             if (Element* de = toDocument(this)->documentElement())
1420                 return de->lookupNamespaceURI(prefix);
1421             return nullAtom;
1422         case DOCUMENT_TYPE_NODE:
1423         case DOCUMENT_FRAGMENT_NODE:
1424             return nullAtom;
1425         case ATTRIBUTE_NODE: {
1426             const Attr *attr = toAttr(this);
1427             if (attr->ownerElement())
1428                 return attr->ownerElement()->lookupNamespaceURI(prefix);
1429             else
1430                 return nullAtom;
1431         }
1432         default:
1433             if (Element* parent = parentElement())
1434                 return parent->lookupNamespaceURI(prefix);
1435             return nullAtom;
1436     }
1437 }
1438
1439 static void appendTextContent(const Node* node, bool convertBRsToNewlines, bool& isNullString, StringBuilder& content)
1440 {
1441     switch (node->nodeType()) {
1442     case Node::TEXT_NODE:
1443     case Node::CDATA_SECTION_NODE:
1444     case Node::COMMENT_NODE:
1445         isNullString = false;
1446         content.append(toCharacterData(node)->data());
1447         break;
1448
1449     case Node::PROCESSING_INSTRUCTION_NODE:
1450         isNullString = false;
1451         content.append(toProcessingInstruction(node)->data());
1452         break;
1453
1454     case Node::ELEMENT_NODE:
1455         if (isHTMLBRElement(*node) && convertBRsToNewlines) {
1456             isNullString = false;
1457             content.append('\n');
1458             break;
1459         }
1460     // Fall through.
1461     case Node::ATTRIBUTE_NODE:
1462     case Node::DOCUMENT_FRAGMENT_NODE:
1463         isNullString = false;
1464         for (Node* child = node->firstChild(); child; child = child->nextSibling()) {
1465             if (child->nodeType() == Node::COMMENT_NODE || child->nodeType() == Node::PROCESSING_INSTRUCTION_NODE)
1466                 continue;
1467             appendTextContent(child, convertBRsToNewlines, isNullString, content);
1468         }
1469         break;
1470
1471     case Node::DOCUMENT_NODE:
1472     case Node::DOCUMENT_TYPE_NODE:
1473         break;
1474     }
1475 }
1476
1477 String Node::textContent(bool convertBRsToNewlines) const
1478 {
1479     StringBuilder content;
1480     bool isNullString = true;
1481     appendTextContent(this, convertBRsToNewlines, isNullString, content);
1482     return isNullString ? String() : content.toString();
1483 }
1484
1485 void Node::setTextContent(const String& text)
1486 {
1487     switch (nodeType()) {
1488         case TEXT_NODE:
1489         case CDATA_SECTION_NODE:
1490         case COMMENT_NODE:
1491         case PROCESSING_INSTRUCTION_NODE:
1492             setNodeValue(text);
1493             return;
1494         case ELEMENT_NODE:
1495         case ATTRIBUTE_NODE:
1496         case DOCUMENT_FRAGMENT_NODE: {
1497             // FIXME: Merge this logic into replaceChildrenWithText.
1498             RefPtr<ContainerNode> container = toContainerNode(this);
1499             // No need to do anything if the text is identical.
1500             if (container->hasOneTextChild() && toText(container->firstChild())->data() == text)
1501                 return;
1502             ChildListMutationScope mutation(*this);
1503             container->removeChildren();
1504             // Note: This API will not insert empty text nodes:
1505             // http://dom.spec.whatwg.org/#dom-node-textcontent
1506             if (!text.isEmpty())
1507                 container->appendChild(document().createTextNode(text), ASSERT_NO_EXCEPTION);
1508             return;
1509         }
1510         case DOCUMENT_NODE:
1511         case DOCUMENT_TYPE_NODE:
1512             // Do nothing.
1513             return;
1514     }
1515     ASSERT_NOT_REACHED();
1516 }
1517
1518 bool Node::offsetInCharacters() const
1519 {
1520     return false;
1521 }
1522
1523 unsigned short Node::compareDocumentPosition(const Node* otherNode) const
1524 {
1525     return compareDocumentPositionInternal(otherNode, TreatShadowTreesAsDisconnected);
1526 }
1527
1528 unsigned short Node::compareDocumentPositionInternal(const Node* otherNode, ShadowTreesTreatment treatment) const
1529 {
1530     // It is not clear what should be done if |otherNode| is 0.
1531     if (!otherNode)
1532         return DOCUMENT_POSITION_DISCONNECTED;
1533
1534     if (otherNode == this)
1535         return DOCUMENT_POSITION_EQUIVALENT;
1536
1537     const Attr* attr1 = nodeType() == ATTRIBUTE_NODE ? toAttr(this) : 0;
1538     const Attr* attr2 = otherNode->nodeType() == ATTRIBUTE_NODE ? toAttr(otherNode) : 0;
1539
1540     const Node* start1 = attr1 ? attr1->ownerElement() : this;
1541     const Node* start2 = attr2 ? attr2->ownerElement() : otherNode;
1542
1543     // If either of start1 or start2 is null, then we are disconnected, since one of the nodes is
1544     // an orphaned attribute node.
1545     if (!start1 || !start2) {
1546         unsigned short direction = (this > otherNode) ? DOCUMENT_POSITION_PRECEDING : DOCUMENT_POSITION_FOLLOWING;
1547         return DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | direction;
1548     }
1549
1550     Vector<const Node*, 16> chain1;
1551     Vector<const Node*, 16> chain2;
1552     if (attr1)
1553         chain1.append(attr1);
1554     if (attr2)
1555         chain2.append(attr2);
1556
1557     if (attr1 && attr2 && start1 == start2 && start1) {
1558         // We are comparing two attributes on the same node. Crawl our attribute map and see which one we hit first.
1559         const Element* owner1 = attr1->ownerElement();
1560         owner1->synchronizeAllAttributes();
1561         unsigned length = owner1->attributeCount();
1562         for (unsigned i = 0; i < length; ++i) {
1563             // If neither of the two determining nodes is a child node and nodeType is the same for both determining nodes, then an
1564             // implementation-dependent order between the determining nodes is returned. This order is stable as long as no nodes of
1565             // the same nodeType are inserted into or removed from the direct container. This would be the case, for example,
1566             // when comparing two attributes of the same element, and inserting or removing additional attributes might change
1567             // the order between existing attributes.
1568             const Attribute& attribute = owner1->attributeItem(i);
1569             if (attr1->qualifiedName() == attribute.name())
1570                 return DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | DOCUMENT_POSITION_FOLLOWING;
1571             if (attr2->qualifiedName() == attribute.name())
1572                 return DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | DOCUMENT_POSITION_PRECEDING;
1573         }
1574
1575         ASSERT_NOT_REACHED();
1576         return DOCUMENT_POSITION_DISCONNECTED;
1577     }
1578
1579     // If one node is in the document and the other is not, we must be disconnected.
1580     // If the nodes have different owning documents, they must be disconnected.  Note that we avoid
1581     // comparing Attr nodes here, since they return false from inDocument() all the time (which seems like a bug).
1582     if (start1->inDocument() != start2->inDocument() || (treatment == TreatShadowTreesAsDisconnected && start1->treeScope() != start2->treeScope())) {
1583         unsigned short direction = (this > otherNode) ? DOCUMENT_POSITION_PRECEDING : DOCUMENT_POSITION_FOLLOWING;
1584         return DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | direction;
1585     }
1586
1587     // We need to find a common ancestor container, and then compare the indices of the two immediate children.
1588     const Node* current;
1589     for (current = start1; current; current = current->parentOrShadowHostNode())
1590         chain1.append(current);
1591     for (current = start2; current; current = current->parentOrShadowHostNode())
1592         chain2.append(current);
1593
1594     unsigned index1 = chain1.size();
1595     unsigned index2 = chain2.size();
1596
1597     // If the two elements don't have a common root, they're not in the same tree.
1598     if (chain1[index1 - 1] != chain2[index2 - 1]) {
1599         unsigned short direction = (this > otherNode) ? DOCUMENT_POSITION_PRECEDING : DOCUMENT_POSITION_FOLLOWING;
1600         return DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | direction;
1601     }
1602
1603     unsigned connection = start1->treeScope() != start2->treeScope() ? DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC : 0;
1604
1605     // Walk the two chains backwards and look for the first difference.
1606     for (unsigned i = min(index1, index2); i; --i) {
1607         const Node* child1 = chain1[--index1];
1608         const Node* child2 = chain2[--index2];
1609         if (child1 != child2) {
1610             // If one of the children is an attribute, it wins.
1611             if (child1->nodeType() == ATTRIBUTE_NODE)
1612                 return DOCUMENT_POSITION_FOLLOWING | connection;
1613             if (child2->nodeType() == ATTRIBUTE_NODE)
1614                 return DOCUMENT_POSITION_PRECEDING | connection;
1615
1616             // If one of the children is a shadow root,
1617             if (child1->isShadowRoot() || child2->isShadowRoot()) {
1618                 if (!child2->isShadowRoot())
1619                     return Node::DOCUMENT_POSITION_FOLLOWING | connection;
1620                 if (!child1->isShadowRoot())
1621                     return Node::DOCUMENT_POSITION_PRECEDING | connection;
1622
1623                 for (ShadowRoot* child = toShadowRoot(child2)->olderShadowRoot(); child; child = child->olderShadowRoot())
1624                     if (child == child1)
1625                         return Node::DOCUMENT_POSITION_FOLLOWING | connection;
1626
1627                 return Node::DOCUMENT_POSITION_PRECEDING | connection;
1628             }
1629
1630             if (!child2->nextSibling())
1631                 return DOCUMENT_POSITION_FOLLOWING | connection;
1632             if (!child1->nextSibling())
1633                 return DOCUMENT_POSITION_PRECEDING | connection;
1634
1635             // Otherwise we need to see which node occurs first.  Crawl backwards from child2 looking for child1.
1636             for (Node* child = child2->previousSibling(); child; child = child->previousSibling()) {
1637                 if (child == child1)
1638                     return DOCUMENT_POSITION_FOLLOWING | connection;
1639             }
1640             return DOCUMENT_POSITION_PRECEDING | connection;
1641         }
1642     }
1643
1644     // There was no difference between the two parent chains, i.e., one was a subset of the other.  The shorter
1645     // chain is the ancestor.
1646     return index1 < index2 ?
1647                DOCUMENT_POSITION_FOLLOWING | DOCUMENT_POSITION_CONTAINED_BY | connection :
1648                DOCUMENT_POSITION_PRECEDING | DOCUMENT_POSITION_CONTAINS | connection;
1649 }
1650
1651 FloatPoint Node::convertToPage(const FloatPoint& p) const
1652 {
1653     // If there is a renderer, just ask it to do the conversion
1654     if (renderer())
1655         return renderer()->localToAbsolute(p, UseTransforms);
1656
1657     // Otherwise go up the tree looking for a renderer
1658     if (Element* parent = parentElement())
1659         return parent->convertToPage(p);
1660
1661     // No parent - no conversion needed
1662     return p;
1663 }
1664
1665 FloatPoint Node::convertFromPage(const FloatPoint& p) const
1666 {
1667     // If there is a renderer, just ask it to do the conversion
1668     if (renderer())
1669         return renderer()->absoluteToLocal(p, UseTransforms);
1670
1671     // Otherwise go up the tree looking for a renderer
1672     if (Element* parent = parentElement())
1673         return parent->convertFromPage(p);
1674
1675     // No parent - no conversion needed
1676     return p;
1677 }
1678
1679 String Node::debugName() const
1680 {
1681     StringBuilder name;
1682     name.append(nodeName());
1683
1684     if (hasID()) {
1685         name.appendLiteral(" id=\'");
1686         name.append(toElement(this)->getIdAttribute());
1687         name.append('\'');
1688     }
1689
1690     if (hasClass()) {
1691         name.appendLiteral(" class=\'");
1692         for (size_t i = 0; i < toElement(this)->classNames().size(); ++i) {
1693             if (i > 0)
1694                 name.append(' ');
1695             name.append(toElement(this)->classNames()[i]);
1696         }
1697         name.append('\'');
1698     }
1699
1700     return name.toString();
1701 }
1702
1703 #ifndef NDEBUG
1704
1705 static void appendAttributeDesc(const Node* node, StringBuilder& stringBuilder, const QualifiedName& name, const char* attrDesc)
1706 {
1707     if (!node->isElementNode())
1708         return;
1709
1710     String attr = toElement(node)->getAttribute(name);
1711     if (attr.isEmpty())
1712         return;
1713
1714     stringBuilder.append(attrDesc);
1715     stringBuilder.append("=\"");
1716     stringBuilder.append(attr);
1717     stringBuilder.append("\"");
1718 }
1719
1720 void Node::showNode(const char* prefix) const
1721 {
1722     if (!prefix)
1723         prefix = "";
1724     if (isTextNode()) {
1725         String value = nodeValue();
1726         value.replaceWithLiteral('\\', "\\\\");
1727         value.replaceWithLiteral('\n', "\\n");
1728         fprintf(stderr, "%s%s\t%p \"%s\"\n", prefix, nodeName().utf8().data(), this, value.utf8().data());
1729     } else {
1730         StringBuilder attrs;
1731         appendAttributeDesc(this, attrs, idAttr, " ID");
1732         appendAttributeDesc(this, attrs, classAttr, " CLASS");
1733         appendAttributeDesc(this, attrs, styleAttr, " STYLE");
1734         fprintf(stderr, "%s%s\t%p%s\n", prefix, nodeName().utf8().data(), this, attrs.toString().utf8().data());
1735     }
1736 }
1737
1738 void Node::showTreeForThis() const
1739 {
1740     showTreeAndMark(this, "*");
1741 }
1742
1743 void Node::showNodePathForThis() const
1744 {
1745     Vector<const Node*, 16> chain;
1746     const Node* node = this;
1747     while (node->parentOrShadowHostNode()) {
1748         chain.append(node);
1749         node = node->parentOrShadowHostNode();
1750     }
1751     for (unsigned index = chain.size(); index > 0; --index) {
1752         const Node* node = chain[index - 1];
1753         if (node->isShadowRoot()) {
1754             int count = 0;
1755             for (ShadowRoot* shadowRoot = toShadowRoot(node)->olderShadowRoot(); shadowRoot; shadowRoot = shadowRoot->olderShadowRoot())
1756                 ++count;
1757             fprintf(stderr, "/#shadow-root[%d]", count);
1758             continue;
1759         }
1760
1761         switch (node->nodeType()) {
1762         case ELEMENT_NODE: {
1763             fprintf(stderr, "/%s", node->nodeName().utf8().data());
1764
1765             const Element* element = toElement(node);
1766             const AtomicString& idattr = element->getIdAttribute();
1767             bool hasIdAttr = !idattr.isNull() && !idattr.isEmpty();
1768             if (node->previousSibling() || node->nextSibling()) {
1769                 int count = 0;
1770                 for (Node* previous = node->previousSibling(); previous; previous = previous->previousSibling())
1771                     if (previous->nodeName() == node->nodeName())
1772                         ++count;
1773                 if (hasIdAttr)
1774                     fprintf(stderr, "[@id=\"%s\" and position()=%d]", idattr.utf8().data(), count);
1775                 else
1776                     fprintf(stderr, "[%d]", count);
1777             } else if (hasIdAttr) {
1778                 fprintf(stderr, "[@id=\"%s\"]", idattr.utf8().data());
1779             }
1780             break;
1781         }
1782         case TEXT_NODE:
1783             fprintf(stderr, "/text()");
1784             break;
1785         case ATTRIBUTE_NODE:
1786             fprintf(stderr, "/@%s", node->nodeName().utf8().data());
1787             break;
1788         default:
1789             break;
1790         }
1791     }
1792     fprintf(stderr, "\n");
1793 }
1794
1795 static void traverseTreeAndMark(const String& baseIndent, const Node* rootNode, const Node* markedNode1, const char* markedLabel1, const Node* markedNode2, const char* markedLabel2)
1796 {
1797     for (const Node* node = rootNode; node; node = NodeTraversal::next(*node)) {
1798         if (node == markedNode1)
1799             fprintf(stderr, "%s", markedLabel1);
1800         if (node == markedNode2)
1801             fprintf(stderr, "%s", markedLabel2);
1802
1803         StringBuilder indent;
1804         indent.append(baseIndent);
1805         for (const Node* tmpNode = node; tmpNode && tmpNode != rootNode; tmpNode = tmpNode->parentOrShadowHostNode())
1806             indent.append('\t');
1807         fprintf(stderr, "%s", indent.toString().utf8().data());
1808         node->showNode();
1809         indent.append('\t');
1810         if (node->isShadowRoot()) {
1811             if (ShadowRoot* youngerShadowRoot = toShadowRoot(node)->youngerShadowRoot())
1812                 traverseTreeAndMark(indent.toString(), youngerShadowRoot, markedNode1, markedLabel1, markedNode2, markedLabel2);
1813         } else if (ShadowRoot* oldestShadowRoot = oldestShadowRootFor(node))
1814             traverseTreeAndMark(indent.toString(), oldestShadowRoot, markedNode1, markedLabel1, markedNode2, markedLabel2);
1815     }
1816 }
1817
1818 void Node::showTreeAndMark(const Node* markedNode1, const char* markedLabel1, const Node* markedNode2, const char* markedLabel2) const
1819 {
1820     const Node* rootNode;
1821     const Node* node = this;
1822     while (node->parentOrShadowHostNode() && !isHTMLBodyElement(*node))
1823         node = node->parentOrShadowHostNode();
1824     rootNode = node;
1825
1826     String startingIndent;
1827     traverseTreeAndMark(startingIndent, rootNode, markedNode1, markedLabel1, markedNode2, markedLabel2);
1828 }
1829
1830 void Node::formatForDebugger(char* buffer, unsigned length) const
1831 {
1832     String result;
1833     String s;
1834
1835     s = nodeName();
1836     if (s.isEmpty())
1837         result = "<none>";
1838     else
1839         result = s;
1840
1841     strncpy(buffer, result.utf8().data(), length - 1);
1842 }
1843
1844 static ContainerNode* parentOrShadowHostOrFrameOwner(const Node* node)
1845 {
1846     ContainerNode* parent = node->parentOrShadowHostNode();
1847     if (!parent && node->document().frame())
1848         parent = node->document().frame()->ownerElement();
1849     return parent;
1850 }
1851
1852 static void showSubTreeAcrossFrame(const Node* node, const Node* markedNode, const String& indent)
1853 {
1854     if (node == markedNode)
1855         fputs("*", stderr);
1856     fputs(indent.utf8().data(), stderr);
1857     node->showNode();
1858     if (node->isShadowRoot()) {
1859         if (ShadowRoot* youngerShadowRoot = toShadowRoot(node)->youngerShadowRoot())
1860             showSubTreeAcrossFrame(youngerShadowRoot, markedNode, indent + "\t");
1861     } else {
1862         if (node->isFrameOwnerElement())
1863             showSubTreeAcrossFrame(toHTMLFrameOwnerElement(node)->contentDocument(), markedNode, indent + "\t");
1864         if (ShadowRoot* oldestShadowRoot = oldestShadowRootFor(node))
1865             showSubTreeAcrossFrame(oldestShadowRoot, markedNode, indent + "\t");
1866     }
1867     for (Node* child = node->firstChild(); child; child = child->nextSibling())
1868         showSubTreeAcrossFrame(child, markedNode, indent + "\t");
1869 }
1870
1871 void Node::showTreeForThisAcrossFrame() const
1872 {
1873     Node* rootNode = const_cast<Node*>(this);
1874     while (parentOrShadowHostOrFrameOwner(rootNode))
1875         rootNode = parentOrShadowHostOrFrameOwner(rootNode);
1876     showSubTreeAcrossFrame(rootNode, this, "");
1877 }
1878
1879 #endif
1880
1881 // --------
1882
1883 Node* Node::enclosingLinkEventParentOrSelf()
1884 {
1885     for (Node* node = this; node; node = node->parentOrShadowHostNode()) {
1886         // For imagemaps, the enclosing link node is the associated area element not the image itself.
1887         // So we don't let images be the enclosingLinkNode, even though isLink sometimes returns true
1888         // for them.
1889         if (node->isLink() && !isHTMLImageElement(*node))
1890             return node;
1891     }
1892
1893     return 0;
1894 }
1895
1896 const AtomicString& Node::interfaceName() const
1897 {
1898     return EventTargetNames::Node;
1899 }
1900
1901 ExecutionContext* Node::executionContext() const
1902 {
1903     return document().contextDocument().get();
1904 }
1905
1906 void Node::didMoveToNewDocument(Document& oldDocument)
1907 {
1908     TreeScopeAdopter::ensureDidMoveToNewDocumentWasCalled(oldDocument);
1909
1910     if (const EventTargetData* eventTargetData = this->eventTargetData()) {
1911         const EventListenerMap& listenerMap = eventTargetData->eventListenerMap;
1912         if (!listenerMap.isEmpty()) {
1913             Vector<AtomicString> types = listenerMap.eventTypes();
1914             for (unsigned i = 0; i < types.size(); ++i)
1915                 document().addListenerTypeIfNeeded(types[i]);
1916         }
1917     }
1918
1919     if (AXObjectCache::accessibilityEnabled()) {
1920         if (AXObjectCache* cache = oldDocument.existingAXObjectCache())
1921             cache->remove(this);
1922     }
1923
1924     oldDocument.markers().removeMarkers(this);
1925
1926     const EventListenerVector& mousewheelListeners = getEventListeners(EventTypeNames::mousewheel);
1927     WheelController* oldController = WheelController::from(oldDocument);
1928     WheelController* newController = WheelController::from(document());
1929     for (size_t i = 0; i < mousewheelListeners.size(); ++i) {
1930         oldController->didRemoveWheelEventHandler(oldDocument);
1931         newController->didAddWheelEventHandler(document());
1932     }
1933
1934     const EventListenerVector& wheelListeners = getEventListeners(EventTypeNames::wheel);
1935     for (size_t i = 0; i < wheelListeners.size(); ++i) {
1936         oldController->didRemoveWheelEventHandler(oldDocument);
1937         newController->didAddWheelEventHandler(document());
1938     }
1939
1940     if (const TouchEventTargetSet* touchHandlers = oldDocument.touchEventTargets()) {
1941         while (touchHandlers->contains(this)) {
1942             oldDocument.didRemoveTouchEventHandler(this);
1943             document().didAddTouchEventHandler(this);
1944         }
1945     }
1946
1947     if (Vector<OwnPtr<MutationObserverRegistration> >* registry = mutationObserverRegistry()) {
1948         for (size_t i = 0; i < registry->size(); ++i) {
1949             document().addMutationObserverTypes(registry->at(i)->mutationTypes());
1950         }
1951     }
1952
1953     if (HashSet<MutationObserverRegistration*>* transientRegistry = transientMutationObserverRegistry()) {
1954         for (HashSet<MutationObserverRegistration*>::iterator iter = transientRegistry->begin(); iter != transientRegistry->end(); ++iter) {
1955             document().addMutationObserverTypes((*iter)->mutationTypes());
1956         }
1957     }
1958 }
1959
1960 static inline bool tryAddEventListener(Node* targetNode, const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
1961 {
1962     if (!targetNode->EventTarget::addEventListener(eventType, listener, useCapture))
1963         return false;
1964
1965     Document& document = targetNode->document();
1966     document.addListenerTypeIfNeeded(eventType);
1967     if (eventType == EventTypeNames::wheel || eventType == EventTypeNames::mousewheel)
1968         WheelController::from(document)->didAddWheelEventHandler(document);
1969     else if (isTouchEventType(eventType))
1970         document.didAddTouchEventHandler(targetNode);
1971
1972     return true;
1973 }
1974
1975 bool Node::addEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
1976 {
1977     return tryAddEventListener(this, eventType, listener, useCapture);
1978 }
1979
1980 static inline bool tryRemoveEventListener(Node* targetNode, const AtomicString& eventType, EventListener* listener, bool useCapture)
1981 {
1982     if (!targetNode->EventTarget::removeEventListener(eventType, listener, useCapture))
1983         return false;
1984
1985     // FIXME: Notify Document that the listener has vanished. We need to keep track of a number of
1986     // listeners for each type, not just a bool - see https://bugs.webkit.org/show_bug.cgi?id=33861
1987     Document& document = targetNode->document();
1988     if (eventType == EventTypeNames::wheel || eventType == EventTypeNames::mousewheel)
1989         WheelController::from(document)->didRemoveWheelEventHandler(document);
1990     else if (isTouchEventType(eventType))
1991         document.didRemoveTouchEventHandler(targetNode);
1992
1993     return true;
1994 }
1995
1996 bool Node::removeEventListener(const AtomicString& eventType, EventListener* listener, bool useCapture)
1997 {
1998     return tryRemoveEventListener(this, eventType, listener, useCapture);
1999 }
2000
2001 void Node::removeAllEventListeners()
2002 {
2003     EventTarget::removeAllEventListeners();
2004     document().didClearTouchEventHandlers(this);
2005 }
2006
2007 typedef HashMap<Node*, OwnPtr<EventTargetData> > EventTargetDataMap;
2008
2009 static EventTargetDataMap& eventTargetDataMap()
2010 {
2011     DEFINE_STATIC_LOCAL(EventTargetDataMap, map, ());
2012     return map;
2013 }
2014
2015 EventTargetData* Node::eventTargetData()
2016 {
2017     return hasEventTargetData() ? eventTargetDataMap().get(this) : 0;
2018 }
2019
2020 EventTargetData& Node::ensureEventTargetData()
2021 {
2022     if (hasEventTargetData())
2023         return *eventTargetDataMap().get(this);
2024     setHasEventTargetData(true);
2025     EventTargetData* data = new EventTargetData;
2026     eventTargetDataMap().set(this, adoptPtr(data));
2027     return *data;
2028 }
2029
2030 void Node::clearEventTargetData()
2031 {
2032     eventTargetDataMap().remove(this);
2033 }
2034
2035 Vector<OwnPtr<MutationObserverRegistration> >* Node::mutationObserverRegistry()
2036 {
2037     if (!hasRareData())
2038         return 0;
2039     NodeMutationObserverData* data = rareData()->mutationObserverData();
2040     if (!data)
2041         return 0;
2042     return &data->registry;
2043 }
2044
2045 HashSet<MutationObserverRegistration*>* Node::transientMutationObserverRegistry()
2046 {
2047     if (!hasRareData())
2048         return 0;
2049     NodeMutationObserverData* data = rareData()->mutationObserverData();
2050     if (!data)
2051         return 0;
2052     return &data->transientRegistry;
2053 }
2054
2055 template<typename Registry>
2056 static inline void collectMatchingObserversForMutation(HashMap<MutationObserver*, MutationRecordDeliveryOptions>& observers, Registry* registry, Node& target, MutationObserver::MutationType type, const QualifiedName* attributeName)
2057 {
2058     if (!registry)
2059         return;
2060     for (typename Registry::iterator iter = registry->begin(); iter != registry->end(); ++iter) {
2061         const MutationObserverRegistration& registration = **iter;
2062         if (registration.shouldReceiveMutationFrom(target, type, attributeName)) {
2063             MutationRecordDeliveryOptions deliveryOptions = registration.deliveryOptions();
2064             HashMap<MutationObserver*, MutationRecordDeliveryOptions>::AddResult result = observers.add(&registration.observer(), deliveryOptions);
2065             if (!result.isNewEntry)
2066                 result.storedValue->value |= deliveryOptions;
2067         }
2068     }
2069 }
2070
2071 void Node::getRegisteredMutationObserversOfType(HashMap<MutationObserver*, MutationRecordDeliveryOptions>& observers, MutationObserver::MutationType type, const QualifiedName* attributeName)
2072 {
2073     ASSERT((type == MutationObserver::Attributes && attributeName) || !attributeName);
2074     collectMatchingObserversForMutation(observers, mutationObserverRegistry(), *this, type, attributeName);
2075     collectMatchingObserversForMutation(observers, transientMutationObserverRegistry(), *this, type, attributeName);
2076     for (Node* node = parentNode(); node; node = node->parentNode()) {
2077         collectMatchingObserversForMutation(observers, node->mutationObserverRegistry(), *this, type, attributeName);
2078         collectMatchingObserversForMutation(observers, node->transientMutationObserverRegistry(), *this, type, attributeName);
2079     }
2080 }
2081
2082 void Node::registerMutationObserver(MutationObserver& observer, MutationObserverOptions options, const HashSet<AtomicString>& attributeFilter)
2083 {
2084     MutationObserverRegistration* registration = 0;
2085     Vector<OwnPtr<MutationObserverRegistration> >& registry = ensureRareData().ensureMutationObserverData().registry;
2086     for (size_t i = 0; i < registry.size(); ++i) {
2087         if (&registry[i]->observer() == &observer) {
2088             registration = registry[i].get();
2089             registration->resetObservation(options, attributeFilter);
2090         }
2091     }
2092
2093     if (!registration) {
2094         registry.append(MutationObserverRegistration::create(observer, *this, options, attributeFilter));
2095         registration = registry.last().get();
2096     }
2097
2098     document().addMutationObserverTypes(registration->mutationTypes());
2099 }
2100
2101 void Node::unregisterMutationObserver(MutationObserverRegistration* registration)
2102 {
2103     Vector<OwnPtr<MutationObserverRegistration> >* registry = mutationObserverRegistry();
2104     ASSERT(registry);
2105     if (!registry)
2106         return;
2107
2108     size_t index = registry->find(registration);
2109     ASSERT(index != kNotFound);
2110     if (index == kNotFound)
2111         return;
2112
2113     // Deleting the registration may cause this node to be derefed, so we must make sure the Vector operation completes
2114     // before that, in case |this| is destroyed (see MutationObserverRegistration::m_registrationNodeKeepAlive).
2115     // FIXME: Simplify the registration/transient registration logic to make this understandable by humans.
2116     RefPtr<Node> protect(this);
2117     registry->remove(index);
2118 }
2119
2120 void Node::registerTransientMutationObserver(MutationObserverRegistration* registration)
2121 {
2122     ensureRareData().ensureMutationObserverData().transientRegistry.add(registration);
2123 }
2124
2125 void Node::unregisterTransientMutationObserver(MutationObserverRegistration* registration)
2126 {
2127     HashSet<MutationObserverRegistration*>* transientRegistry = transientMutationObserverRegistry();
2128     ASSERT(transientRegistry);
2129     if (!transientRegistry)
2130         return;
2131
2132     ASSERT(transientRegistry->contains(registration));
2133     transientRegistry->remove(registration);
2134 }
2135
2136 void Node::notifyMutationObserversNodeWillDetach()
2137 {
2138     if (!document().hasMutationObservers())
2139         return;
2140
2141     for (Node* node = parentNode(); node; node = node->parentNode()) {
2142         if (Vector<OwnPtr<MutationObserverRegistration> >* registry = node->mutationObserverRegistry()) {
2143             const size_t size = registry->size();
2144             for (size_t i = 0; i < size; ++i)
2145                 registry->at(i)->observedSubtreeNodeWillDetach(*this);
2146         }
2147
2148         if (HashSet<MutationObserverRegistration*>* transientRegistry = node->transientMutationObserverRegistry()) {
2149             for (HashSet<MutationObserverRegistration*>::iterator iter = transientRegistry->begin(); iter != transientRegistry->end(); ++iter)
2150                 (*iter)->observedSubtreeNodeWillDetach(*this);
2151         }
2152     }
2153 }
2154
2155 void Node::handleLocalEvents(Event* event)
2156 {
2157     if (!hasEventTargetData())
2158         return;
2159
2160     if (isDisabledFormControl(this) && event->isMouseEvent())
2161         return;
2162
2163     fireEventListeners(event);
2164 }
2165
2166 void Node::dispatchScopedEvent(PassRefPtr<Event> event)
2167 {
2168     dispatchScopedEventDispatchMediator(EventDispatchMediator::create(event));
2169 }
2170
2171 void Node::dispatchScopedEventDispatchMediator(PassRefPtr<EventDispatchMediator> eventDispatchMediator)
2172 {
2173     EventDispatcher::dispatchScopedEvent(this, eventDispatchMediator);
2174 }
2175
2176 bool Node::dispatchEvent(PassRefPtr<Event> event)
2177 {
2178     if (event->isMouseEvent())
2179         return EventDispatcher::dispatchEvent(this, MouseEventDispatchMediator::create(static_pointer_cast<MouseEvent>(event), MouseEventDispatchMediator::SyntheticMouseEvent));
2180     if (event->isTouchEvent())
2181         return dispatchTouchEvent(static_pointer_cast<TouchEvent>(event));
2182     return EventDispatcher::dispatchEvent(this, EventDispatchMediator::create(event));
2183 }
2184
2185 void Node::dispatchSubtreeModifiedEvent()
2186 {
2187     if (isInShadowTree())
2188         return;
2189
2190     ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2191
2192     if (!document().hasListenerType(Document::DOMSUBTREEMODIFIED_LISTENER))
2193         return;
2194
2195     dispatchScopedEvent(MutationEvent::create(EventTypeNames::DOMSubtreeModified, true));
2196 }
2197
2198 bool Node::dispatchDOMActivateEvent(int detail, PassRefPtr<Event> underlyingEvent)
2199 {
2200     ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2201     RefPtr<UIEvent> event = UIEvent::create(EventTypeNames::DOMActivate, true, true, document().domWindow(), detail);
2202     event->setUnderlyingEvent(underlyingEvent);
2203     dispatchScopedEvent(event);
2204     return event->defaultHandled();
2205 }
2206
2207 bool Node::dispatchKeyEvent(const PlatformKeyboardEvent& event)
2208 {
2209     return EventDispatcher::dispatchEvent(this, KeyboardEventDispatchMediator::create(KeyboardEvent::create(event, document().domWindow())));
2210 }
2211
2212 bool Node::dispatchMouseEvent(const PlatformMouseEvent& event, const AtomicString& eventType,
2213     int detail, Node* relatedTarget)
2214 {
2215     return EventDispatcher::dispatchEvent(this, MouseEventDispatchMediator::create(MouseEvent::create(eventType, document().domWindow(), event, detail, relatedTarget)));
2216 }
2217
2218 bool Node::dispatchGestureEvent(const PlatformGestureEvent& event)
2219 {
2220     RefPtr<GestureEvent> gestureEvent = GestureEvent::create(document().domWindow(), event);
2221     if (!gestureEvent.get())
2222         return false;
2223     return EventDispatcher::dispatchEvent(this, GestureEventDispatchMediator::create(gestureEvent));
2224 }
2225
2226 bool Node::dispatchTouchEvent(PassRefPtr<TouchEvent> event)
2227 {
2228     return EventDispatcher::dispatchEvent(this, TouchEventDispatchMediator::create(event));
2229 }
2230
2231 void Node::dispatchSimulatedClick(Event* underlyingEvent, SimulatedClickMouseEventOptions eventOptions)
2232 {
2233     EventDispatcher::dispatchSimulatedClick(this, underlyingEvent, eventOptions);
2234 }
2235
2236 bool Node::dispatchWheelEvent(const PlatformWheelEvent& event)
2237 {
2238     return EventDispatcher::dispatchEvent(this, WheelEventDispatchMediator::create(event, document().domWindow()));
2239 }
2240
2241 void Node::dispatchInputEvent()
2242 {
2243     dispatchScopedEvent(Event::createBubble(EventTypeNames::input));
2244 }
2245
2246 void Node::defaultEventHandler(Event* event)
2247 {
2248     if (event->target() != this)
2249         return;
2250     const AtomicString& eventType = event->type();
2251     if (eventType == EventTypeNames::keydown || eventType == EventTypeNames::keypress) {
2252         if (event->isKeyboardEvent()) {
2253             if (LocalFrame* frame = document().frame())
2254                 frame->eventHandler().defaultKeyboardEventHandler(toKeyboardEvent(event));
2255         }
2256     } else if (eventType == EventTypeNames::click) {
2257         int detail = event->isUIEvent() ? static_cast<UIEvent*>(event)->detail() : 0;
2258         if (dispatchDOMActivateEvent(detail, event))
2259             event->setDefaultHandled();
2260     } else if (eventType == EventTypeNames::contextmenu) {
2261         if (Page* page = document().page())
2262             page->contextMenuController().handleContextMenuEvent(event);
2263     } else if (eventType == EventTypeNames::textInput) {
2264         if (event->hasInterface(EventNames::TextEvent)) {
2265             if (LocalFrame* frame = document().frame())
2266                 frame->eventHandler().defaultTextInputEventHandler(toTextEvent(event));
2267         }
2268 #if OS(WIN)
2269     } else if (eventType == EventTypeNames::mousedown && event->isMouseEvent()) {
2270         MouseEvent* mouseEvent = toMouseEvent(event);
2271         if (mouseEvent->button() == MiddleButton) {
2272             if (enclosingLinkEventParentOrSelf())
2273                 return;
2274
2275             RenderObject* renderer = this->renderer();
2276             while (renderer && (!renderer->isBox() || !toRenderBox(renderer)->canBeScrolledAndHasScrollableArea()))
2277                 renderer = renderer->parent();
2278
2279             if (renderer) {
2280                 if (LocalFrame* frame = document().frame())
2281                     frame->eventHandler().startPanScrolling(renderer);
2282             }
2283         }
2284 #endif
2285     } else if ((eventType == EventTypeNames::wheel || eventType == EventTypeNames::mousewheel) && event->hasInterface(EventNames::WheelEvent)) {
2286         WheelEvent* wheelEvent = toWheelEvent(event);
2287
2288         // If we don't have a renderer, send the wheel event to the first node we find with a renderer.
2289         // This is needed for <option> and <optgroup> elements so that <select>s get a wheel scroll.
2290         Node* startNode = this;
2291         while (startNode && !startNode->renderer())
2292             startNode = startNode->parentOrShadowHostNode();
2293
2294         if (startNode && startNode->renderer()) {
2295             if (LocalFrame* frame = document().frame())
2296                 frame->eventHandler().defaultWheelEventHandler(startNode, wheelEvent);
2297         }
2298     } else if (event->type() == EventTypeNames::webkitEditableContentChanged) {
2299         dispatchInputEvent();
2300     }
2301 }
2302
2303 void Node::willCallDefaultEventHandler(const Event&)
2304 {
2305 }
2306
2307 bool Node::willRespondToMouseMoveEvents()
2308 {
2309     if (isDisabledFormControl(this))
2310         return false;
2311     return hasEventListeners(EventTypeNames::mousemove) || hasEventListeners(EventTypeNames::mouseover) || hasEventListeners(EventTypeNames::mouseout);
2312 }
2313
2314 bool Node::willRespondToMouseClickEvents()
2315 {
2316     if (isDisabledFormControl(this))
2317         return false;
2318     return isContentEditable(UserSelectAllIsAlwaysNonEditable) || hasEventListeners(EventTypeNames::mouseup) || hasEventListeners(EventTypeNames::mousedown) || hasEventListeners(EventTypeNames::click) || hasEventListeners(EventTypeNames::DOMActivate);
2319 }
2320
2321 bool Node::willRespondToTouchEvents()
2322 {
2323     if (isDisabledFormControl(this))
2324         return false;
2325     return hasEventListeners(EventTypeNames::touchstart) || hasEventListeners(EventTypeNames::touchmove) || hasEventListeners(EventTypeNames::touchcancel) || hasEventListeners(EventTypeNames::touchend);
2326 }
2327
2328 // This is here for inlining
2329 inline void TreeScope::removedLastRefToScope()
2330 {
2331     ASSERT_WITH_SECURITY_IMPLICATION(!deletionHasBegun());
2332     if (m_guardRefCount) {
2333         // If removing a child removes the last self-only ref, we don't
2334         // want the scope to be destructed until after
2335         // removeDetachedChildren returns, so we guard ourselves with an
2336         // extra self-only ref.
2337         guardRef();
2338         dispose();
2339 #if !ASSERT_DISABLED
2340         // We need to do this right now since guardDeref() can delete this.
2341         rootNode().m_inRemovedLastRefFunction = false;
2342 #endif
2343         guardDeref();
2344     } else {
2345 #if !ASSERT_DISABLED
2346         rootNode().m_inRemovedLastRefFunction = false;
2347 #endif
2348 #if SECURITY_ASSERT_ENABLED
2349         beginDeletion();
2350 #endif
2351         delete this;
2352     }
2353 }
2354
2355 // It's important not to inline removedLastRef, because we don't want to inline the code to
2356 // delete a Node at each deref call site.
2357 void Node::removedLastRef()
2358 {
2359     // An explicit check for Document here is better than a virtual function since it is
2360     // faster for non-Document nodes, and because the call to removedLastRef that is inlined
2361     // at all deref call sites is smaller if it's a non-virtual function.
2362     if (isTreeScope()) {
2363         treeScope().removedLastRefToScope();
2364         return;
2365     }
2366
2367 #if SECURITY_ASSERT_ENABLED
2368     m_deletionHasBegun = true;
2369 #endif
2370     delete this;
2371 }
2372
2373 unsigned Node::connectedSubframeCount() const
2374 {
2375     return hasRareData() ? rareData()->connectedSubframeCount() : 0;
2376 }
2377
2378 void Node::incrementConnectedSubframeCount(unsigned amount)
2379 {
2380     ASSERT(isContainerNode());
2381     ensureRareData().incrementConnectedSubframeCount(amount);
2382 }
2383
2384 void Node::decrementConnectedSubframeCount(unsigned amount)
2385 {
2386     rareData()->decrementConnectedSubframeCount(amount);
2387 }
2388
2389 void Node::updateAncestorConnectedSubframeCountForRemoval() const
2390 {
2391     unsigned count = connectedSubframeCount();
2392
2393     if (!count)
2394         return;
2395
2396     for (Node* node = parentOrShadowHostNode(); node; node = node->parentOrShadowHostNode())
2397         node->decrementConnectedSubframeCount(count);
2398 }
2399
2400 void Node::updateAncestorConnectedSubframeCountForInsertion() const
2401 {
2402     unsigned count = connectedSubframeCount();
2403
2404     if (!count)
2405         return;
2406
2407     for (Node* node = parentOrShadowHostNode(); node; node = node->parentOrShadowHostNode())
2408         node->incrementConnectedSubframeCount(count);
2409 }
2410
2411 PassRefPtr<NodeList> Node::getDestinationInsertionPoints()
2412 {
2413     document().updateDistributionForNodeIfNeeded(this);
2414     Vector<InsertionPoint*, 8> insertionPoints;
2415     collectDestinationInsertionPoints(*this, insertionPoints);
2416     Vector<RefPtr<Node> > filteredInsertionPoints;
2417     for (size_t i = 0; i < insertionPoints.size(); ++i) {
2418         InsertionPoint* insertionPoint = insertionPoints[i];
2419         ASSERT(insertionPoint->containingShadowRoot());
2420         if (insertionPoint->containingShadowRoot()->type() != ShadowRoot::UserAgentShadowRoot)
2421             filteredInsertionPoints.append(insertionPoint);
2422     }
2423     return StaticNodeList::adopt(filteredInsertionPoints);
2424 }
2425
2426 void Node::registerScopedHTMLStyleChild()
2427 {
2428     setHasScopedHTMLStyleChild(true);
2429 }
2430
2431 void Node::unregisterScopedHTMLStyleChild()
2432 {
2433     ASSERT(hasScopedHTMLStyleChild());
2434     setHasScopedHTMLStyleChild(numberOfScopedHTMLStyleChildren());
2435 }
2436
2437 size_t Node::numberOfScopedHTMLStyleChildren() const
2438 {
2439     size_t count = 0;
2440     for (HTMLStyleElement* style = Traversal<HTMLStyleElement>::firstChild(*this); style; style = Traversal<HTMLStyleElement>::nextSibling(*style)) {
2441         if (style->isRegisteredAsScoped())
2442             ++count;
2443     }
2444
2445     return count;
2446 }
2447
2448 void Node::setFocus(bool flag)
2449 {
2450     document().userActionElements().setFocused(this, flag);
2451 }
2452
2453 void Node::setActive(bool flag)
2454 {
2455     document().userActionElements().setActive(this, flag);
2456 }
2457
2458 void Node::setHovered(bool flag)
2459 {
2460     document().userActionElements().setHovered(this, flag);
2461 }
2462
2463 bool Node::isUserActionElementActive() const
2464 {
2465     ASSERT(isUserActionElement());
2466     return document().userActionElements().isActive(this);
2467 }
2468
2469 bool Node::isUserActionElementInActiveChain() const
2470 {
2471     ASSERT(isUserActionElement());
2472     return document().userActionElements().isInActiveChain(this);
2473 }
2474
2475 bool Node::isUserActionElementHovered() const
2476 {
2477     ASSERT(isUserActionElement());
2478     return document().userActionElements().isHovered(this);
2479 }
2480
2481 bool Node::isUserActionElementFocused() const
2482 {
2483     ASSERT(isUserActionElement());
2484     return document().userActionElements().isFocused(this);
2485 }
2486
2487 void Node::setCustomElementState(CustomElementState newState)
2488 {
2489     CustomElementState oldState = customElementState();
2490
2491     switch (newState) {
2492     case NotCustomElement:
2493         ASSERT_NOT_REACHED(); // Everything starts in this state
2494         return;
2495
2496     case WaitingForUpgrade:
2497         ASSERT(NotCustomElement == oldState);
2498         break;
2499
2500     case Upgraded:
2501         ASSERT(WaitingForUpgrade == oldState);
2502         break;
2503     }
2504
2505     ASSERT(isHTMLElement() || isSVGElement());
2506     setFlag(CustomElement);
2507     setFlag(newState == Upgraded, CustomElementUpgraded);
2508
2509     if (oldState == NotCustomElement || newState == Upgraded)
2510         setNeedsStyleRecalc(SubtreeStyleChange); // :unresolved has changed
2511 }
2512
2513 } // namespace WebCore
2514
2515 #ifndef NDEBUG
2516
2517 void showNode(const WebCore::Node* node)
2518 {
2519     if (node)
2520         node->showNode("");
2521 }
2522
2523 void showTree(const WebCore::Node* node)
2524 {
2525     if (node)
2526         node->showTreeForThis();
2527 }
2528
2529 void showNodePath(const WebCore::Node* node)
2530 {
2531     if (node)
2532         node->showNodePathForThis();
2533 }
2534
2535 #endif