debda41f6791a068e4f0f39e02e6bd064e98c82a
[WebKit-https.git] / Source / WebCore / 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 "Node.h"
27
28 #include "AXObjectCache.h"
29 #include "Attr.h"
30 #include "Attribute.h"
31 #include "BeforeLoadEvent.h"
32 #include "ChildListMutationScope.h"
33 #include "Chrome.h"
34 #include "ChromeClient.h"
35 #include "CSSParser.h"
36 #include "CSSRule.h"
37 #include "CSSSelector.h"
38 #include "CSSSelectorList.h"
39 #include "CSSStyleRule.h"
40 #include "CSSStyleSheet.h"
41 #include "ChildNodeList.h"
42 #include "ClassNodeList.h"
43 #include "ContainerNodeAlgorithms.h"
44 #include "ContextMenuController.h"
45 #include "DOMImplementation.h"
46 #include "DOMSettableTokenList.h"
47 #include "Document.h"
48 #include "DocumentFragment.h"
49 #include "DocumentType.h"
50 #include "Element.h"
51 #include "ElementRareData.h"
52 #include "ElementShadow.h"
53 #include "Event.h"
54 #include "EventContext.h"
55 #include "EventDispatchMediator.h"
56 #include "EventDispatcher.h"
57 #include "EventException.h"
58 #include "EventHandler.h"
59 #include "EventListener.h"
60 #include "EventNames.h"
61 #include "ExceptionCode.h"
62 #include "ExceptionCodePlaceholder.h"
63 #include "FocusEvent.h"
64 #include "Frame.h"
65 #include "FrameView.h"
66 #include "HTMLElement.h"
67 #include "HTMLFrameOwnerElement.h"
68 #include "HTMLNames.h"
69 #include "HTMLStyleElement.h"
70 #include "InsertionPoint.h"
71 #include "InspectorCounters.h"
72 #include "KeyboardEvent.h"
73 #include "LabelsNodeList.h"
74 #include "LiveNodeList.h"
75 #include "Logging.h"
76 #include "MouseEvent.h"
77 #include "MutationEvent.h"
78 #include "NameNodeList.h"
79 #include "NamedNodeMap.h"
80 #include "NodeRareData.h"
81 #include "NodeRenderingContext.h"
82 #include "NodeTraversal.h"
83 #include "Page.h"
84 #include "PlatformMouseEvent.h"
85 #include "PlatformWheelEvent.h"
86 #include "ProcessingInstruction.h"
87 #include "ProgressEvent.h"
88 #include "RadioNodeList.h"
89 #include "RegisteredEventListener.h"
90 #include "RenderBlock.h"
91 #include "RenderBox.h"
92 #include "RenderTextControl.h"
93 #include "RenderView.h"
94 #include "ScopedEventQueue.h"
95 #include "SelectorQuery.h"
96 #include "Settings.h"
97 #include "ShadowRoot.h"
98 #include "StaticNodeList.h"
99 #include "StorageEvent.h"
100 #include "StyleResolver.h"
101 #include "TagNodeList.h"
102 #include "TemplateContentDocumentFragment.h"
103 #include "Text.h"
104 #include "TextEvent.h"
105 #include "TouchEvent.h"
106 #include "TreeScopeAdopter.h"
107 #include "UIEvent.h"
108 #include "UIEventWithKeyState.h"
109 #include "UserActionElementSet.h"
110 #include "WebCoreMemoryInstrumentation.h"
111 #include "WheelEvent.h"
112 #include "WindowEventContext.h"
113 #include "XMLNames.h"
114 #include "htmlediting.h"
115 #include <wtf/HashSet.h>
116 #include <wtf/PassOwnPtr.h>
117 #include <wtf/RefCountedLeakCounter.h>
118 #include <wtf/UnusedParam.h>
119 #include <wtf/Vector.h>
120 #include <wtf/text/CString.h>
121 #include <wtf/text/StringBuilder.h>
122
123 #ifndef NDEBUG
124 #include "RenderLayer.h"
125 #endif
126
127 #if ENABLE(GESTURE_EVENTS)
128 #include "GestureEvent.h"
129 #endif
130
131 #if ENABLE(INSPECTOR)
132 #include "InspectorController.h"
133 #endif
134
135 #if USE(JSC)
136 #include <runtime/JSGlobalData.h>
137 #include <runtime/Operations.h>
138 #endif
139
140 #if ENABLE(MICRODATA)
141 #include "HTMLPropertiesCollection.h"
142 #include "PropertyNodeList.h"
143 #endif
144
145 using namespace std;
146
147 namespace WebCore {
148
149 using namespace HTMLNames;
150
151 bool Node::isSupported(const String& feature, const String& version)
152 {
153     return DOMImplementation::hasFeature(feature, version);
154 }
155
156 #if DUMP_NODE_STATISTICS
157 static HashSet<Node*> liveNodeSet;
158 #endif
159
160 void Node::dumpStatistics()
161 {
162 #if DUMP_NODE_STATISTICS
163     size_t nodesWithRareData = 0;
164
165     size_t elementNodes = 0;
166     size_t attrNodes = 0;
167     size_t textNodes = 0;
168     size_t cdataNodes = 0;
169     size_t commentNodes = 0;
170     size_t entityReferenceNodes = 0;
171     size_t entityNodes = 0;
172     size_t piNodes = 0;
173     size_t documentNodes = 0;
174     size_t docTypeNodes = 0;
175     size_t fragmentNodes = 0;
176     size_t notationNodes = 0;
177     size_t xpathNSNodes = 0;
178     size_t shadowRootNodes = 0;
179
180     HashMap<String, size_t> perTagCount;
181
182     size_t attributes = 0;
183     size_t attributesWithAttr = 0;
184     size_t elementsWithAttributeStorage = 0;
185     size_t elementsWithRareData = 0;
186     size_t elementsWithNamedNodeMap = 0;
187
188     for (HashSet<Node*>::iterator it = liveNodeSet.begin(); it != liveNodeSet.end(); ++it) {
189         Node* node = *it;
190
191         if (node->hasRareData()) {
192             ++nodesWithRareData;
193             if (node->isElementNode()) {
194                 ++elementsWithRareData;
195                 if (toElement(node)->hasNamedNodeMap())
196                     ++elementsWithNamedNodeMap;
197             }
198         }
199
200         switch (node->nodeType()) {
201             case ELEMENT_NODE: {
202                 ++elementNodes;
203
204                 // Tag stats
205                 Element* element = toElement(node);
206                 HashMap<String, size_t>::AddResult result = perTagCount.add(element->tagName(), 1);
207                 if (!result.isNewEntry)
208                     result.iterator->value++;
209
210                 if (ElementData* elementData = element->elementData()) {
211                     attributes += elementData->length();
212                     ++elementsWithAttributeStorage;
213                     for (unsigned i = 0; i < elementData->length(); ++i) {
214                         Attribute* attr = elementData->attributeItem(i);
215                         if (attr->attr())
216                             ++attributesWithAttr;
217                     }
218                 }
219                 break;
220             }
221             case ATTRIBUTE_NODE: {
222                 ++attrNodes;
223                 break;
224             }
225             case TEXT_NODE: {
226                 ++textNodes;
227                 break;
228             }
229             case CDATA_SECTION_NODE: {
230                 ++cdataNodes;
231                 break;
232             }
233             case COMMENT_NODE: {
234                 ++commentNodes;
235                 break;
236             }
237             case ENTITY_REFERENCE_NODE: {
238                 ++entityReferenceNodes;
239                 break;
240             }
241             case ENTITY_NODE: {
242                 ++entityNodes;
243                 break;
244             }
245             case PROCESSING_INSTRUCTION_NODE: {
246                 ++piNodes;
247                 break;
248             }
249             case DOCUMENT_NODE: {
250                 ++documentNodes;
251                 break;
252             }
253             case DOCUMENT_TYPE_NODE: {
254                 ++docTypeNodes;
255                 break;
256             }
257             case DOCUMENT_FRAGMENT_NODE: {
258                 if (node->isShadowRoot())
259                     ++shadowRootNodes;
260                 else
261                     ++fragmentNodes;
262                 break;
263             }
264             case NOTATION_NODE: {
265                 ++notationNodes;
266                 break;
267             }
268             case XPATH_NAMESPACE_NODE: {
269                 ++xpathNSNodes;
270                 break;
271             }
272         }
273     }
274
275     printf("Number of Nodes: %d\n\n", liveNodeSet.size());
276     printf("Number of Nodes with RareData: %zu\n\n", nodesWithRareData);
277
278     printf("NodeType distribution:\n");
279     printf("  Number of Element nodes: %zu\n", elementNodes);
280     printf("  Number of Attribute nodes: %zu\n", attrNodes);
281     printf("  Number of Text nodes: %zu\n", textNodes);
282     printf("  Number of CDATASection nodes: %zu\n", cdataNodes);
283     printf("  Number of Comment nodes: %zu\n", commentNodes);
284     printf("  Number of EntityReference nodes: %zu\n", entityReferenceNodes);
285     printf("  Number of Entity nodes: %zu\n", entityNodes);
286     printf("  Number of ProcessingInstruction nodes: %zu\n", piNodes);
287     printf("  Number of Document nodes: %zu\n", documentNodes);
288     printf("  Number of DocumentType nodes: %zu\n", docTypeNodes);
289     printf("  Number of DocumentFragment nodes: %zu\n", fragmentNodes);
290     printf("  Number of Notation nodes: %zu\n", notationNodes);
291     printf("  Number of XPathNS nodes: %zu\n", xpathNSNodes);
292     printf("  Number of ShadowRoot nodes: %zu\n", shadowRootNodes);
293
294     printf("Element tag name distibution:\n");
295     for (HashMap<String, size_t>::iterator it = perTagCount.begin(); it != perTagCount.end(); ++it)
296         printf("  Number of <%s> tags: %zu\n", it->key.utf8().data(), it->value);
297
298     printf("Attributes:\n");
299     printf("  Number of Attributes (non-Node and Node): %zu [%zu]\n", attributes, sizeof(Attribute));
300     printf("  Number of Attributes with an Attr: %zu\n", attributesWithAttr);
301     printf("  Number of Elements with attribute storage: %zu [%zu]\n", elementsWithAttributeStorage, sizeof(ElementData));
302     printf("  Number of Elements with RareData: %zu\n", elementsWithRareData);
303     printf("  Number of Elements with NamedNodeMap: %zu [%zu]\n", elementsWithNamedNodeMap, sizeof(NamedNodeMap));
304 #endif
305 }
306
307 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, nodeCounter, ("WebCoreNode"));
308 DEFINE_DEBUG_ONLY_GLOBAL(HashSet<Node*>, ignoreSet, );
309
310 #ifndef NDEBUG
311 static bool shouldIgnoreLeaks = false;
312 #endif
313
314 void Node::startIgnoringLeaks()
315 {
316 #ifndef NDEBUG
317     shouldIgnoreLeaks = true;
318 #endif
319 }
320
321 void Node::stopIgnoringLeaks()
322 {
323 #ifndef NDEBUG
324     shouldIgnoreLeaks = false;
325 #endif
326 }
327
328 Node::StyleChange Node::diff(const RenderStyle* s1, const RenderStyle* s2, Document* doc)
329 {
330     StyleChange ch = NoInherit;
331     EDisplay display1 = s1 ? s1->display() : NONE;
332     bool fl1 = s1 && s1->hasPseudoStyle(FIRST_LETTER);
333     EDisplay display2 = s2 ? s2->display() : NONE;
334     bool fl2 = s2 && s2->hasPseudoStyle(FIRST_LETTER);
335     
336     // We just detach if a renderer acquires or loses a column-span, since spanning elements
337     // typically won't contain much content.
338     bool colSpan1 = s1 && s1->columnSpan();
339     bool colSpan2 = s2 && s2->columnSpan();
340     
341     bool specifiesColumns1 = s1 && (!s1->hasAutoColumnCount() || !s1->hasAutoColumnWidth());
342     bool specifiesColumns2 = s2 && (!s2->hasAutoColumnCount() || !s2->hasAutoColumnWidth());
343
344     if (display1 != display2 || fl1 != fl2 || colSpan1 != colSpan2 
345         || (specifiesColumns1 != specifiesColumns2 && doc->settings()->regionBasedColumnsEnabled())
346         || (s1 && s2 && !s1->contentDataEquivalent(s2)))
347         ch = Detach;
348     else if (!s1 || !s2)
349         ch = Inherit;
350     else if (*s1 == *s2)
351         ch = NoChange;
352     else if (s1->inheritedNotEqual(s2))
353         ch = Inherit;
354     else if (s1->hasExplicitlyInheritedProperties() || s2->hasExplicitlyInheritedProperties())
355         ch = Inherit;
356
357     // If the pseudoStyles have changed, we want any StyleChange that is not NoChange
358     // because setStyle will do the right thing with anything else.
359     if (ch == NoChange && s1->hasAnyPublicPseudoStyles()) {
360         for (PseudoId pseudoId = FIRST_PUBLIC_PSEUDOID; ch == NoChange && pseudoId < FIRST_INTERNAL_PSEUDOID; pseudoId = static_cast<PseudoId>(pseudoId + 1)) {
361             if (s1->hasPseudoStyle(pseudoId)) {
362                 RenderStyle* ps2 = s2->getCachedPseudoStyle(pseudoId);
363                 if (!ps2)
364                     ch = NoInherit;
365                 else {
366                     RenderStyle* ps1 = s1->getCachedPseudoStyle(pseudoId);
367                     ch = ps1 && *ps1 == *ps2 ? NoChange : NoInherit;
368                 }
369             }
370         }
371     }
372
373     // When text-combine property has been changed, we need to prepare a separate renderer object.
374     // When text-combine is on, we use RenderCombineText, otherwise RenderText.
375     // https://bugs.webkit.org/show_bug.cgi?id=55069
376     if ((s1 && s2) && (s1->hasTextCombine() != s2->hasTextCombine()))
377         ch = Detach;
378
379     // We need to reattach the node, so that it is moved to the correct RenderFlowThread.
380     if ((s1 && s2) && (s1->flowThread() != s2->flowThread()))
381         ch = Detach;
382
383     // When the region thread has changed, we need to prepare a separate render region object.
384     if ((s1 && s2) && (s1->regionThread() != s2->regionThread()))
385         ch = Detach;
386
387     return ch;
388 }
389
390 void Node::trackForDebugging()
391 {
392 #ifndef NDEBUG
393     if (shouldIgnoreLeaks)
394         ignoreSet.add(this);
395     else
396         nodeCounter.increment();
397 #endif
398
399 #if DUMP_NODE_STATISTICS
400     liveNodeSet.add(this);
401 #endif
402 }
403
404 Node::~Node()
405 {
406 #ifndef NDEBUG
407     HashSet<Node*>::iterator it = ignoreSet.find(this);
408     if (it != ignoreSet.end())
409         ignoreSet.remove(it);
410     else
411         nodeCounter.decrement();
412 #endif
413
414 #if DUMP_NODE_STATISTICS
415     liveNodeSet.remove(this);
416 #endif
417
418     if (hasRareData())
419         clearRareData();
420
421     Document* doc = documentInternal();
422
423     if (hasEventTargetData()) {
424 #if ENABLE(TOUCH_EVENT_TRACKING)
425         if (doc)
426             doc->didRemoveEventTargetNode(this);
427 #endif
428         clearEventTargetData();
429     }
430
431     if (renderer())
432         detach();
433
434     if (AXObjectCache::accessibilityEnabled() && doc && doc->axObjectCacheExists() && !isContainerNode())
435         doc->axObjectCache()->remove(this);
436     
437     if (m_previous)
438         m_previous->setNextSibling(0);
439     if (m_next)
440         m_next->setPreviousSibling(0);
441
442     m_treeScope->guardDeref();
443
444     InspectorCounters::decrementCounter(InspectorCounters::NodeCounter);
445 }
446
447 NodeRareData* Node::rareData() const
448 {
449     ASSERT(hasRareData());
450     return static_cast<NodeRareData*>(m_data.m_rareData);
451 }
452
453 NodeRareData* Node::ensureRareData()
454 {
455     if (hasRareData())
456         return rareData();
457
458     NodeRareData* data;
459     if (isElementNode())
460         data = ElementRareData::create(m_data.m_renderer).leakPtr();
461     else
462         data = NodeRareData::create(m_data.m_renderer).leakPtr();
463     ASSERT(data);
464
465     m_data.m_rareData = data;
466     setFlag(HasRareDataFlag);
467     return data;
468 }
469
470 void Node::clearRareData()
471 {
472     ASSERT(hasRareData());
473     ASSERT(!transientMutationObserverRegistry() || transientMutationObserverRegistry()->isEmpty());
474
475     RenderObject* renderer = m_data.m_rareData->renderer();
476     if (isElementNode())
477         delete static_cast<ElementRareData*>(m_data.m_rareData);
478     else
479         delete static_cast<NodeRareData*>(m_data.m_rareData);
480     m_data.m_renderer = renderer;
481     clearFlag(HasRareDataFlag);
482 }
483
484 Node* Node::toNode()
485 {
486     return this;
487 }
488
489 HTMLInputElement* Node::toInputElement()
490 {
491     // If one of the below ASSERTs trigger, you are calling this function
492     // directly or indirectly from a constructor or destructor of this object.
493     // Don't do this!
494     ASSERT(!(isHTMLElement() && hasTagName(inputTag)));
495     return 0;
496 }
497
498 short Node::tabIndex() const
499 {
500     return 0;
501 }
502
503 String Node::nodeValue() const
504 {
505     return String();
506 }
507
508 void Node::setNodeValue(const String& /*nodeValue*/, ExceptionCode& ec)
509 {
510     // NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly
511     if (isReadOnlyNode()) {
512         ec = NO_MODIFICATION_ALLOWED_ERR;
513         return;
514     }
515
516     // By default, setting nodeValue has no effect.
517 }
518
519 PassRefPtr<NodeList> Node::childNodes()
520 {
521     return ensureRareData()->ensureNodeLists()->ensureChildNodeList(this);
522 }
523
524 Node *Node::lastDescendant() const
525 {
526     Node *n = const_cast<Node *>(this);
527     while (n && n->lastChild())
528         n = n->lastChild();
529     return n;
530 }
531
532 Node* Node::firstDescendant() const
533 {
534     Node *n = const_cast<Node *>(this);
535     while (n && n->firstChild())
536         n = n->firstChild();
537     return n;
538 }
539
540 bool Node::insertBefore(PassRefPtr<Node> newChild, Node* refChild, ExceptionCode& ec, AttachBehavior attachBehavior)
541 {
542     if (!isContainerNode()) {
543         ec = HIERARCHY_REQUEST_ERR;
544         return false;
545     }
546     return toContainerNode(this)->insertBefore(newChild, refChild, ec, attachBehavior);
547 }
548
549 bool Node::replaceChild(PassRefPtr<Node> newChild, Node* oldChild, ExceptionCode& ec, AttachBehavior attachBehavior)
550 {
551     if (!isContainerNode()) {
552         ec = HIERARCHY_REQUEST_ERR;
553         return false;
554     }
555     return toContainerNode(this)->replaceChild(newChild, oldChild, ec, attachBehavior);
556 }
557
558 bool Node::removeChild(Node* oldChild, ExceptionCode& ec)
559 {
560     if (!isContainerNode()) {
561         ec = NOT_FOUND_ERR;
562         return false;
563     }
564     return toContainerNode(this)->removeChild(oldChild, ec);
565 }
566
567 bool Node::appendChild(PassRefPtr<Node> newChild, ExceptionCode& ec, AttachBehavior attachBehavior)
568 {
569     if (!isContainerNode()) {
570         ec = HIERARCHY_REQUEST_ERR;
571         return false;
572     }
573     return toContainerNode(this)->appendChild(newChild, ec, attachBehavior);
574 }
575
576 void Node::remove(ExceptionCode& ec)
577 {
578     if (ContainerNode* parent = parentNode())
579         parent->removeChild(this, ec);
580 }
581
582 void Node::normalize()
583 {
584     // Go through the subtree beneath us, normalizing all nodes. This means that
585     // any two adjacent text nodes are merged and any empty text nodes are removed.
586
587     RefPtr<Node> node = this;
588     while (Node* firstChild = node->firstChild())
589         node = firstChild;
590     while (node) {
591         NodeType type = node->nodeType();
592         if (type == ELEMENT_NODE)
593             toElement(node.get())->normalizeAttributes();
594
595         if (node == this)
596             break;
597
598         if (type != TEXT_NODE) {
599             node = NodeTraversal::nextPostOrder(node.get());
600             continue;
601         }
602
603         RefPtr<Text> text = toText(node.get());
604
605         // Remove empty text nodes.
606         if (!text->length()) {
607             // Care must be taken to get the next node before removing the current node.
608             node = NodeTraversal::nextPostOrder(node.get());
609             text->remove(IGNORE_EXCEPTION);
610             continue;
611         }
612
613         // Merge text nodes.
614         while (Node* nextSibling = node->nextSibling()) {
615             if (nextSibling->nodeType() != TEXT_NODE)
616                 break;
617             RefPtr<Text> nextText = toText(nextSibling);
618
619             // Remove empty text nodes.
620             if (!nextText->length()) {
621                 nextText->remove(IGNORE_EXCEPTION);
622                 continue;
623             }
624
625             // Both non-empty text nodes. Merge them.
626             unsigned offset = text->length();
627             text->appendData(nextText->data(), IGNORE_EXCEPTION);
628             document()->textNodesMerged(nextText.get(), offset);
629             nextText->remove(IGNORE_EXCEPTION);
630         }
631
632         node = NodeTraversal::nextPostOrder(node.get());
633     }
634 }
635
636 const AtomicString& Node::virtualPrefix() const
637 {
638     // For nodes other than elements and attributes, the prefix is always null
639     return nullAtom;
640 }
641
642 void Node::setPrefix(const AtomicString& /*prefix*/, ExceptionCode& ec)
643 {
644     // The spec says that for nodes other than elements and attributes, prefix is always null.
645     // It does not say what to do when the user tries to set the prefix on another type of
646     // node, however Mozilla throws a NAMESPACE_ERR exception.
647     ec = NAMESPACE_ERR;
648 }
649
650 const AtomicString& Node::virtualLocalName() const
651 {
652     return nullAtom;
653 }
654
655 const AtomicString& Node::virtualNamespaceURI() const
656 {
657     return nullAtom;
658 }
659
660 bool Node::isContentEditable(UserSelectAllTreatment treatment)
661 {
662     document()->updateStyleIfNeeded();
663     return rendererIsEditable(Editable, treatment);
664 }
665
666 bool Node::isContentRichlyEditable()
667 {
668     document()->updateStyleIfNeeded();
669     return rendererIsEditable(RichlyEditable, UserSelectAllIsAlwaysNonEditable);
670 }
671
672 void Node::inspect()
673 {
674 #if ENABLE(INSPECTOR)
675     if (document() && document()->page())
676         document()->page()->inspectorController()->inspect(this);
677 #endif
678 }
679
680 bool Node::rendererIsEditable(EditableLevel editableLevel, UserSelectAllTreatment treatment) const
681 {
682     if (document()->frame() && document()->frame()->page() && document()->frame()->page()->isEditable() && !containingShadowRoot())
683         return true;
684
685     if (isPseudoElement())
686         return false;
687
688     // Ideally we'd call ASSERT(!needsStyleRecalc()) here, but
689     // ContainerNode::setFocus() calls setNeedsStyleRecalc(), so the assertion
690     // would fire in the middle of Document::setFocusedNode().
691
692     for (const Node* node = this; node; node = node->parentNode()) {
693         if ((node->isHTMLElement() || node->isDocumentNode()) && node->renderer()) {
694 #if ENABLE(USERSELECT_ALL)
695             // Elements with user-select: all style are considered atomic
696             // therefore non editable.
697             if (node->renderer()->style()->userSelect() == SELECT_ALL && treatment == UserSelectAllIsAlwaysNonEditable)
698                 return false;
699 #else
700             UNUSED_PARAM(treatment);
701 #endif
702             switch (node->renderer()->style()->userModify()) {
703             case READ_ONLY:
704                 return false;
705             case READ_WRITE:
706                 return true;
707             case READ_WRITE_PLAINTEXT_ONLY:
708                 return editableLevel != RichlyEditable;
709             }
710             ASSERT_NOT_REACHED();
711             return false;
712         }
713     }
714
715     return false;
716 }
717
718 bool Node::isEditableToAccessibility(EditableLevel editableLevel) const
719 {
720     if (rendererIsEditable(editableLevel))
721         return true;
722
723     // FIXME: Respect editableLevel for ARIA editable elements.
724     if (editableLevel == RichlyEditable)
725         return false;
726
727     ASSERT(document());
728     ASSERT(AXObjectCache::accessibilityEnabled());
729     ASSERT(document()->axObjectCacheExists());
730
731     if (document() && AXObjectCache::accessibilityEnabled() && document()->axObjectCacheExists())
732         return document()->axObjectCache()->rootAXEditableElement(this);
733
734     return false;
735 }
736
737 bool Node::shouldUseInputMethod()
738 {
739     return isContentEditable(UserSelectAllIsAlwaysNonEditable);
740 }
741
742 RenderBox* Node::renderBox() const
743 {
744     RenderObject* renderer = this->renderer();
745     return renderer && renderer->isBox() ? toRenderBox(renderer) : 0;
746 }
747
748 RenderBoxModelObject* Node::renderBoxModelObject() const
749 {
750     RenderObject* renderer = this->renderer();
751     return renderer && renderer->isBoxModelObject() ? toRenderBoxModelObject(renderer) : 0;
752 }
753
754 LayoutRect Node::boundingBox() const
755 {
756     if (renderer())
757         return renderer()->absoluteBoundingBoxRect();
758     return LayoutRect();
759 }
760     
761 LayoutRect Node::renderRect(bool* isReplaced)
762 {    
763     RenderObject* hitRenderer = this->renderer();
764     ASSERT(hitRenderer);
765     RenderObject* renderer = hitRenderer;
766     while (renderer && !renderer->isBody() && !renderer->isRoot()) {
767         if (renderer->isRenderBlock() || renderer->isInlineBlockOrInlineTable() || renderer->isReplaced()) {
768             *isReplaced = renderer->isReplaced();
769             return renderer->absoluteBoundingBoxRect();
770         }
771         renderer = renderer->parent();
772     }
773     return LayoutRect();    
774 }
775
776 bool Node::hasNonEmptyBoundingBox() const
777 {
778     // Before calling absoluteRects, check for the common case where the renderer
779     // is non-empty, since this is a faster check and almost always returns true.
780     RenderBoxModelObject* box = renderBoxModelObject();
781     if (!box)
782         return false;
783     if (!box->borderBoundingBox().isEmpty())
784         return true;
785
786     Vector<IntRect> rects;
787     FloatPoint absPos = renderer()->localToAbsolute();
788     renderer()->absoluteRects(rects, flooredLayoutPoint(absPos));
789     size_t n = rects.size();
790     for (size_t i = 0; i < n; ++i)
791         if (!rects[i].isEmpty())
792             return true;
793
794     return false;
795 }
796
797 inline static ShadowRoot* oldestShadowRootFor(const Node* node)
798 {
799     if (!node->isElementNode())
800         return 0;
801     if (ElementShadow* shadow = toElement(node)->shadow())
802         return shadow->oldestShadowRoot();
803     return 0;
804 }
805
806 inline void Node::setStyleChange(StyleChangeType changeType)
807 {
808     m_nodeFlags = (m_nodeFlags & ~StyleChangeMask) | changeType;
809 }
810
811 inline void Node::markAncestorsWithChildNeedsStyleRecalc()
812 {
813     for (ContainerNode* p = parentOrShadowHostNode(); p && !p->childNeedsStyleRecalc(); p = p->parentOrShadowHostNode())
814         p->setChildNeedsStyleRecalc();
815
816     if (document()->childNeedsStyleRecalc())
817         document()->scheduleStyleRecalc();
818 }
819
820 void Node::refEventTarget()
821 {
822     ref();
823 }
824
825 void Node::derefEventTarget()
826 {
827     deref();
828 }
829
830 void Node::setNeedsStyleRecalc(StyleChangeType changeType)
831 {
832     ASSERT(changeType != NoStyleChange);
833     if (!attached()) // changed compared to what?
834         return;
835
836     StyleChangeType existingChangeType = styleChangeType();
837     if (changeType > existingChangeType)
838         setStyleChange(changeType);
839
840     if (existingChangeType == NoStyleChange)
841         markAncestorsWithChildNeedsStyleRecalc();
842 }
843
844 void Node::lazyAttach(ShouldSetAttached shouldSetAttached)
845 {
846     for (Node* n = this; n; n = NodeTraversal::next(n, this)) {
847         if (n->hasChildNodes())
848             n->setChildNeedsStyleRecalc();
849         n->setStyleChange(FullStyleChange);
850         if (shouldSetAttached == SetAttached)
851             n->setAttached();
852     }
853     markAncestorsWithChildNeedsStyleRecalc();
854 }
855
856 bool Node::supportsFocus() const
857 {
858     return false;
859 }
860     
861 bool Node::isFocusable() const
862 {
863     if (!inDocument() || !supportsFocus())
864         return false;
865     
866     // Elements in canvas fallback content are not rendered, but they are allowed to be
867     // focusable as long as their canvas is displayed and visible.
868     if (isElementNode() && toElement(this)->isInCanvasSubtree()) {
869         const Element* e = toElement(this);
870         while (e && !e->hasLocalName(canvasTag))
871             e = e->parentElement();
872         ASSERT(e);
873         return e->renderer() && e->renderer()->style()->visibility() == VISIBLE;
874     }
875
876     if (renderer())
877         ASSERT(!renderer()->needsLayout());
878     else
879         // If the node is in a display:none tree it might say it needs style recalc but
880         // the whole document is actually up to date.
881         ASSERT(!document()->childNeedsStyleRecalc());
882
883     // FIXME: Even if we are not visible, we might have a child that is visible.
884     // Hyatt wants to fix that some day with a "has visible content" flag or the like.
885     if (!renderer() || renderer()->style()->visibility() != VISIBLE)
886         return false;
887
888     return true;
889 }
890
891 bool Node::isKeyboardFocusable(KeyboardEvent*) const
892 {
893     return isFocusable() && tabIndex() >= 0;
894 }
895
896 bool Node::isMouseFocusable() const
897 {
898     return isFocusable();
899 }
900
901 Node* Node::focusDelegate()
902 {
903     return this;
904 }
905
906 #if ENABLE(DIALOG_ELEMENT)
907 bool Node::isInert() const
908 {
909     Element* dialog = document()->activeModalDialog();
910     return dialog && !containsIncludingShadowDOM(dialog) && !dialog->containsIncludingShadowDOM(this);
911 }
912 #endif
913
914 unsigned Node::nodeIndex() const
915 {
916     Node *_tempNode = previousSibling();
917     unsigned count=0;
918     for ( count=0; _tempNode; count++ )
919         _tempNode = _tempNode->previousSibling();
920     return count;
921 }
922
923 template<unsigned type>
924 bool shouldInvalidateNodeListCachesForAttr(const unsigned nodeListCounts[], const QualifiedName& attrName)
925 {
926     if (nodeListCounts[type] && LiveNodeListBase::shouldInvalidateTypeOnAttributeChange(static_cast<NodeListInvalidationType>(type), attrName))
927         return true;
928     return shouldInvalidateNodeListCachesForAttr<type + 1>(nodeListCounts, attrName);
929 }
930
931 template<>
932 bool shouldInvalidateNodeListCachesForAttr<numNodeListInvalidationTypes>(const unsigned[], const QualifiedName&)
933 {
934     return false;
935 }
936
937 bool Document::shouldInvalidateNodeListCaches(const QualifiedName* attrName) const
938 {
939     if (attrName)
940         return shouldInvalidateNodeListCachesForAttr<DoNotInvalidateOnAttributeChanges + 1>(m_nodeListCounts, *attrName);
941
942     for (int type = 0; type < numNodeListInvalidationTypes; type++) {
943         if (m_nodeListCounts[type])
944             return true;
945     }
946
947     return false;
948 }
949
950 void Document::invalidateNodeListCaches(const QualifiedName* attrName)
951 {
952     HashSet<LiveNodeListBase*>::iterator end = m_listsInvalidatedAtDocument.end();
953     for (HashSet<LiveNodeListBase*>::iterator it = m_listsInvalidatedAtDocument.begin(); it != end; ++it)
954         (*it)->invalidateCache(attrName);
955 }
956
957 void Node::invalidateNodeListCachesInAncestors(const QualifiedName* attrName, Element* attributeOwnerElement)
958 {
959     if (hasRareData() && (!attrName || isAttributeNode())) {
960         if (NodeListsNodeData* lists = rareData()->nodeLists())
961             lists->clearChildNodeListCache();
962     }
963
964     // Modifications to attributes that are not associated with an Element can't invalidate NodeList caches.
965     if (attrName && !attributeOwnerElement)
966         return;
967
968     if (!document()->shouldInvalidateNodeListCaches(attrName))
969         return;
970
971     document()->invalidateNodeListCaches(attrName);
972
973     for (Node* node = this; node; node = node->parentNode()) {
974         if (!node->hasRareData())
975             continue;
976         NodeRareData* data = node->rareData();
977         if (data->nodeLists())
978             data->nodeLists()->invalidateCaches(attrName);
979     }
980 }
981
982 NodeListsNodeData* Node::nodeLists()
983 {
984     return hasRareData() ? rareData()->nodeLists() : 0;
985 }
986
987 void Node::clearNodeLists()
988 {
989     rareData()->clearNodeLists();
990 }
991
992 void Node::checkSetPrefix(const AtomicString& prefix, ExceptionCode& ec)
993 {
994     // Perform error checking as required by spec for setting Node.prefix. Used by
995     // Element::setPrefix() and Attr::setPrefix()
996
997     if (!prefix.isEmpty() && !Document::isValidName(prefix)) {
998         ec = INVALID_CHARACTER_ERR;
999         return;
1000     }
1001
1002     if (isReadOnlyNode()) {
1003         ec = NO_MODIFICATION_ALLOWED_ERR;
1004         return;
1005     }
1006
1007     // FIXME: Raise NAMESPACE_ERR if prefix is malformed per the Namespaces in XML specification.
1008
1009     const AtomicString& nodeNamespaceURI = namespaceURI();
1010     if ((nodeNamespaceURI.isEmpty() && !prefix.isEmpty())
1011         || (prefix == xmlAtom && nodeNamespaceURI != XMLNames::xmlNamespaceURI)) {
1012         ec = NAMESPACE_ERR;
1013         return;
1014     }
1015     // Attribute-specific checks are in Attr::setPrefix().
1016 }
1017
1018 bool Node::isDescendantOf(const Node *other) const
1019 {
1020     // Return true if other is an ancestor of this, otherwise false
1021     if (!other || !other->hasChildNodes() || inDocument() != other->inDocument())
1022         return false;
1023     if (other->isDocumentNode())
1024         return document() == other && !isDocumentNode() && inDocument();
1025     for (const ContainerNode* n = parentNode(); n; n = n->parentNode()) {
1026         if (n == other)
1027             return true;
1028     }
1029     return false;
1030 }
1031
1032 bool Node::contains(const Node* node) const
1033 {
1034     if (!node)
1035         return false;
1036     return this == node || node->isDescendantOf(this);
1037 }
1038
1039 bool Node::containsIncludingShadowDOM(const Node* node) const
1040 {
1041     for (; node; node = node->parentOrShadowHostNode()) {
1042         if (node == this)
1043             return true;
1044     }
1045     return false;
1046 }
1047
1048 bool Node::containsIncludingHostElements(const Node* node) const
1049 {
1050 #if ENABLE(TEMPLATE_ELEMENT)
1051     while (node) {
1052         if (node == this)
1053             return true;
1054         if (node->isDocumentFragment() && static_cast<const DocumentFragment*>(node)->isTemplateContent())
1055             node = static_cast<const TemplateContentDocumentFragment*>(node)->host();
1056         else
1057             node = node->parentOrShadowHostNode();
1058     }
1059     return false;
1060 #else
1061     return containsIncludingShadowDOM(node);
1062 #endif
1063 }
1064
1065 void Node::attach()
1066 {
1067     ASSERT(!attached());
1068     ASSERT(!renderer() || (renderer()->style() && renderer()->parent()));
1069
1070     // If this node got a renderer it may be the previousRenderer() of sibling text nodes and thus affect the
1071     // result of Text::textRendererIsNeeded() for those nodes.
1072     if (renderer()) {
1073         for (Node* next = nextSibling(); next; next = next->nextSibling()) {
1074             if (next->renderer())
1075                 break;
1076             if (!next->attached())
1077                 break; // Assume this means none of the following siblings are attached.
1078             if (!next->isTextNode())
1079                 continue;
1080             ASSERT(!next->renderer());
1081             toText(next)->createTextRendererIfNeeded();
1082             // If we again decided not to create a renderer for next, we can bail out the loop,
1083             // because it won't affect the result of Text::textRendererIsNeeded() for the rest
1084             // of sibling nodes.
1085             if (!next->renderer())
1086                 break;
1087         }
1088     }
1089
1090     setAttached();
1091     clearNeedsStyleRecalc();
1092
1093     Document* doc = documentInternal();
1094     if (AXObjectCache::accessibilityEnabled() && doc && doc->axObjectCacheExists())
1095         doc->axObjectCache()->updateCacheAfterNodeIsAttached(this);
1096 }
1097
1098 #ifndef NDEBUG
1099 static Node* detachingNode;
1100
1101 bool Node::inDetach() const
1102 {
1103     return detachingNode == this;
1104 }
1105 #endif
1106
1107 void Node::detach()
1108 {
1109 #ifndef NDEBUG
1110     ASSERT(!detachingNode);
1111     detachingNode = this;
1112 #endif
1113
1114     if (renderer())
1115         renderer()->destroyAndCleanupAnonymousWrappers();
1116     setRenderer(0);
1117
1118     Document* doc = document();
1119     if (isUserActionElement()) {
1120         if (hovered())
1121             doc->hoveredNodeDetached(this);
1122         if (inActiveChain())
1123             doc->activeChainNodeDetached(this);
1124         doc->userActionElements().didDetach(this);
1125     }
1126
1127     clearFlag(IsAttachedFlag);
1128
1129 #ifndef NDEBUG
1130     detachingNode = 0;
1131 #endif
1132 }
1133
1134 // FIXME: This code is used by editing.  Seems like it could move over there and not pollute Node.
1135 Node *Node::previousNodeConsideringAtomicNodes() const
1136 {
1137     if (previousSibling()) {
1138         Node *n = previousSibling();
1139         while (!isAtomicNode(n) && n->lastChild())
1140             n = n->lastChild();
1141         return n;
1142     }
1143     else if (parentNode()) {
1144         return parentNode();
1145     }
1146     else {
1147         return 0;
1148     }
1149 }
1150
1151 Node *Node::nextNodeConsideringAtomicNodes() const
1152 {
1153     if (!isAtomicNode(this) && firstChild())
1154         return firstChild();
1155     if (nextSibling())
1156         return nextSibling();
1157     const Node *n = this;
1158     while (n && !n->nextSibling())
1159         n = n->parentNode();
1160     if (n)
1161         return n->nextSibling();
1162     return 0;
1163 }
1164
1165 Node *Node::previousLeafNode() const
1166 {
1167     Node *node = previousNodeConsideringAtomicNodes();
1168     while (node) {
1169         if (isAtomicNode(node))
1170             return node;
1171         node = node->previousNodeConsideringAtomicNodes();
1172     }
1173     return 0;
1174 }
1175
1176 Node *Node::nextLeafNode() const
1177 {
1178     Node *node = nextNodeConsideringAtomicNodes();
1179     while (node) {
1180         if (isAtomicNode(node))
1181             return node;
1182         node = node->nextNodeConsideringAtomicNodes();
1183     }
1184     return 0;
1185 }
1186
1187 ContainerNode* Node::parentNodeForRenderingAndStyle()
1188 {
1189     return NodeRenderingContext(this).parentNodeForRenderingAndStyle();
1190 }
1191
1192 RenderStyle* Node::virtualComputedStyle(PseudoId pseudoElementSpecifier)
1193 {
1194     return parentOrShadowHostNode() ? parentOrShadowHostNode()->computedStyle(pseudoElementSpecifier) : 0;
1195 }
1196
1197 int Node::maxCharacterOffset() const
1198 {
1199     ASSERT_NOT_REACHED();
1200     return 0;
1201 }
1202
1203 // FIXME: Shouldn't these functions be in the editing code?  Code that asks questions about HTML in the core DOM class
1204 // is obviously misplaced.
1205 bool Node::canStartSelection() const
1206 {
1207     if (rendererIsEditable())
1208         return true;
1209
1210     if (renderer()) {
1211         RenderStyle* style = renderer()->style();
1212         // We allow selections to begin within an element that has -webkit-user-select: none set,
1213         // but if the element is draggable then dragging should take priority over selection.
1214         if (style->userDrag() == DRAG_ELEMENT && style->userSelect() == SELECT_NONE)
1215             return false;
1216     }
1217     return parentOrShadowHostNode() ? parentOrShadowHostNode()->canStartSelection() : true;
1218 }
1219
1220 Element* Node::shadowHost() const
1221 {
1222     if (ShadowRoot* root = containingShadowRoot())
1223         return root->host();
1224     return 0;
1225 }
1226
1227 Node* Node::deprecatedShadowAncestorNode() const
1228 {
1229     if (ShadowRoot* root = containingShadowRoot())
1230         return root->host();
1231
1232     return const_cast<Node*>(this);
1233 }
1234
1235 ShadowRoot* Node::containingShadowRoot() const
1236 {
1237     Node* root = treeScope()->rootNode();
1238     return root && root->isShadowRoot() ? toShadowRoot(root) : 0;
1239 }
1240
1241 Node* Node::nonBoundaryShadowTreeRootNode()
1242 {
1243     ASSERT(!isShadowRoot());
1244     Node* root = this;
1245     while (root) {
1246         if (root->isShadowRoot())
1247             return root;
1248         Node* parent = root->parentNodeGuaranteedHostFree();
1249         if (parent && parent->isShadowRoot())
1250             return root;
1251         root = parent;
1252     }
1253     return 0;
1254 }
1255
1256 ContainerNode* Node::nonShadowBoundaryParentNode() const
1257 {
1258     ContainerNode* parent = parentNode();
1259     return parent && !parent->isShadowRoot() ? parent : 0;
1260 }
1261
1262 Element* Node::parentOrShadowHostElement() const
1263 {
1264     ContainerNode* parent = parentOrShadowHostNode();
1265     if (!parent)
1266         return 0;
1267
1268     if (parent->isShadowRoot())
1269         return toShadowRoot(parent)->host();
1270
1271     if (!parent->isElementNode())
1272         return 0;
1273
1274     return toElement(parent);
1275 }
1276
1277 Node* Node::insertionParentForBinding() const
1278 {
1279     return resolveReprojection(this);
1280 }
1281
1282 bool Node::needsShadowTreeWalkerSlow() const
1283 {
1284     return (isShadowRoot() || (isElementNode() && (isInsertionPoint() || isPseudoElement() || toElement(this)->hasPseudoElements() || toElement(this)->shadow())));
1285 }
1286
1287 bool Node::isBlockFlow() const
1288 {
1289     return renderer() && renderer()->isBlockFlow();
1290 }
1291
1292 Element *Node::enclosingBlockFlowElement() const
1293 {
1294     Node *n = const_cast<Node *>(this);
1295     if (isBlockFlow())
1296         return static_cast<Element *>(n);
1297
1298     while (1) {
1299         n = n->parentNode();
1300         if (!n)
1301             break;
1302         if (n->isBlockFlow() || n->hasTagName(bodyTag))
1303             return static_cast<Element *>(n);
1304     }
1305     return 0;
1306 }
1307
1308 bool Node::isRootEditableElement() const
1309 {
1310     return rendererIsEditable() && isElementNode() && (!parentNode() || !parentNode()->rendererIsEditable()
1311         || !parentNode()->isElementNode() || hasTagName(bodyTag));
1312 }
1313
1314 Element* Node::rootEditableElement(EditableType editableType) const
1315 {
1316     if (editableType == HasEditableAXRole)
1317         return const_cast<Element*>(document()->axObjectCache()->rootAXEditableElement(this));
1318
1319     return rootEditableElement();
1320 }
1321
1322 Element* Node::rootEditableElement() const
1323 {
1324     Element* result = 0;
1325     for (Node* n = const_cast<Node*>(this); n && n->rendererIsEditable(); n = n->parentNode()) {
1326         if (n->isElementNode())
1327             result = toElement(n);
1328         if (n->hasTagName(bodyTag))
1329             break;
1330     }
1331     return result;
1332 }
1333
1334 bool Node::inSameContainingBlockFlowElement(Node *n)
1335 {
1336     return n ? enclosingBlockFlowElement() == n->enclosingBlockFlowElement() : false;
1337 }
1338
1339 // FIXME: End of obviously misplaced HTML editing functions.  Try to move these out of Node.
1340
1341 PassRefPtr<NodeList> Node::getElementsByTagName(const AtomicString& localName)
1342 {
1343     if (localName.isNull())
1344         return 0;
1345
1346     if (document()->isHTMLDocument())
1347         return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLTagNodeList>(this, HTMLTagNodeListType, localName);
1348     return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<TagNodeList>(this, TagNodeListType, localName);
1349 }
1350
1351 PassRefPtr<NodeList> Node::getElementsByTagNameNS(const AtomicString& namespaceURI, const AtomicString& localName)
1352 {
1353     if (localName.isNull())
1354         return 0;
1355
1356     if (namespaceURI == starAtom)
1357         return getElementsByTagName(localName);
1358
1359     return ensureRareData()->ensureNodeLists()->addCacheWithQualifiedName(this, namespaceURI.isEmpty() ? nullAtom : namespaceURI, localName);
1360 }
1361
1362 PassRefPtr<NodeList> Node::getElementsByName(const String& elementName)
1363 {
1364     return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<NameNodeList>(this, NameNodeListType, elementName);
1365 }
1366
1367 PassRefPtr<NodeList> Node::getElementsByClassName(const String& classNames)
1368 {
1369     return ensureRareData()->ensureNodeLists()->addCacheWithName<ClassNodeList>(this, ClassNodeListType, classNames);
1370 }
1371
1372 PassRefPtr<RadioNodeList> Node::radioNodeList(const AtomicString& name)
1373 {
1374     ASSERT(hasTagName(formTag) || hasTagName(fieldsetTag));
1375     return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<RadioNodeList>(this, RadioNodeListType, name);
1376 }
1377
1378 PassRefPtr<Element> Node::querySelector(const AtomicString& selectors, ExceptionCode& ec)
1379 {
1380     if (selectors.isEmpty()) {
1381         ec = SYNTAX_ERR;
1382         return 0;
1383     }
1384
1385     SelectorQuery* selectorQuery = document()->selectorQueryCache()->add(selectors, document(), ec);
1386     if (!selectorQuery)
1387         return 0;
1388     return selectorQuery->queryFirst(this);
1389 }
1390
1391 PassRefPtr<NodeList> Node::querySelectorAll(const AtomicString& selectors, ExceptionCode& ec)
1392 {
1393     if (selectors.isEmpty()) {
1394         ec = SYNTAX_ERR;
1395         return 0;
1396     }
1397
1398     SelectorQuery* selectorQuery = document()->selectorQueryCache()->add(selectors, document(), ec);
1399     if (!selectorQuery)
1400         return 0;
1401     return selectorQuery->queryAll(this);
1402 }
1403
1404 Document *Node::ownerDocument() const
1405 {
1406     Document *doc = document();
1407     return doc == this ? 0 : doc;
1408 }
1409
1410 KURL Node::baseURI() const
1411 {
1412     return parentNode() ? parentNode()->baseURI() : KURL();
1413 }
1414
1415 bool Node::isEqualNode(Node* other) const
1416 {
1417     if (!other)
1418         return false;
1419     
1420     NodeType nodeType = this->nodeType();
1421     if (nodeType != other->nodeType())
1422         return false;
1423     
1424     if (nodeName() != other->nodeName())
1425         return false;
1426     
1427     if (localName() != other->localName())
1428         return false;
1429     
1430     if (namespaceURI() != other->namespaceURI())
1431         return false;
1432     
1433     if (prefix() != other->prefix())
1434         return false;
1435     
1436     if (nodeValue() != other->nodeValue())
1437         return false;
1438     
1439     if (isElementNode() && !toElement(this)->hasEquivalentAttributes(toElement(other)))
1440         return false;
1441     
1442     Node* child = firstChild();
1443     Node* otherChild = other->firstChild();
1444     
1445     while (child) {
1446         if (!child->isEqualNode(otherChild))
1447             return false;
1448         
1449         child = child->nextSibling();
1450         otherChild = otherChild->nextSibling();
1451     }
1452     
1453     if (otherChild)
1454         return false;
1455     
1456     if (nodeType == DOCUMENT_TYPE_NODE) {
1457         const DocumentType* documentTypeThis = static_cast<const DocumentType*>(this);
1458         const DocumentType* documentTypeOther = static_cast<const DocumentType*>(other);
1459         
1460         if (documentTypeThis->publicId() != documentTypeOther->publicId())
1461             return false;
1462
1463         if (documentTypeThis->systemId() != documentTypeOther->systemId())
1464             return false;
1465
1466         if (documentTypeThis->internalSubset() != documentTypeOther->internalSubset())
1467             return false;
1468
1469         // FIXME: We don't compare entities or notations because currently both are always empty.
1470     }
1471     
1472     return true;
1473 }
1474
1475 bool Node::isDefaultNamespace(const AtomicString& namespaceURIMaybeEmpty) const
1476 {
1477     const AtomicString& namespaceURI = namespaceURIMaybeEmpty.isEmpty() ? nullAtom : namespaceURIMaybeEmpty;
1478
1479     switch (nodeType()) {
1480         case ELEMENT_NODE: {
1481             const Element* elem = toElement(this);
1482             
1483             if (elem->prefix().isNull())
1484                 return elem->namespaceURI() == namespaceURI;
1485
1486             if (elem->hasAttributes()) {
1487                 for (unsigned i = 0; i < elem->attributeCount(); i++) {
1488                     const Attribute* attr = elem->attributeItem(i);
1489                     
1490                     if (attr->localName() == xmlnsAtom)
1491                         return attr->value() == namespaceURI;
1492                 }
1493             }
1494
1495             if (Element* ancestor = ancestorElement())
1496                 return ancestor->isDefaultNamespace(namespaceURI);
1497
1498             return false;
1499         }
1500         case DOCUMENT_NODE:
1501             if (Element* de = toDocument(this)->documentElement())
1502                 return de->isDefaultNamespace(namespaceURI);
1503             return false;
1504         case ENTITY_NODE:
1505         case NOTATION_NODE:
1506         case DOCUMENT_TYPE_NODE:
1507         case DOCUMENT_FRAGMENT_NODE:
1508             return false;
1509         case ATTRIBUTE_NODE: {
1510             const Attr* attr = static_cast<const Attr*>(this);
1511             if (attr->ownerElement())
1512                 return attr->ownerElement()->isDefaultNamespace(namespaceURI);
1513             return false;
1514         }
1515         default:
1516             if (Element* ancestor = ancestorElement())
1517                 return ancestor->isDefaultNamespace(namespaceURI);
1518             return false;
1519     }
1520 }
1521
1522 String Node::lookupPrefix(const AtomicString &namespaceURI) const
1523 {
1524     // Implemented according to
1525     // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/namespaces-algorithms.html#lookupNamespacePrefixAlgo
1526     
1527     if (namespaceURI.isEmpty())
1528         return String();
1529     
1530     switch (nodeType()) {
1531         case ELEMENT_NODE:
1532             return lookupNamespacePrefix(namespaceURI, static_cast<const Element *>(this));
1533         case DOCUMENT_NODE:
1534             if (Element* de = toDocument(this)->documentElement())
1535                 return de->lookupPrefix(namespaceURI);
1536             return String();
1537         case ENTITY_NODE:
1538         case NOTATION_NODE:
1539         case DOCUMENT_FRAGMENT_NODE:
1540         case DOCUMENT_TYPE_NODE:
1541             return String();
1542         case ATTRIBUTE_NODE: {
1543             const Attr *attr = static_cast<const Attr *>(this);
1544             if (attr->ownerElement())
1545                 return attr->ownerElement()->lookupPrefix(namespaceURI);
1546             return String();
1547         }
1548         default:
1549             if (Element* ancestor = ancestorElement())
1550                 return ancestor->lookupPrefix(namespaceURI);
1551             return String();
1552     }
1553 }
1554
1555 String Node::lookupNamespaceURI(const String &prefix) const
1556 {
1557     // Implemented according to
1558     // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/namespaces-algorithms.html#lookupNamespaceURIAlgo
1559     
1560     if (!prefix.isNull() && prefix.isEmpty())
1561         return String();
1562     
1563     switch (nodeType()) {
1564         case ELEMENT_NODE: {
1565             const Element *elem = static_cast<const Element *>(this);
1566             
1567             if (!elem->namespaceURI().isNull() && elem->prefix() == prefix)
1568                 return elem->namespaceURI();
1569             
1570             if (elem->hasAttributes()) {
1571                 for (unsigned i = 0; i < elem->attributeCount(); i++) {
1572                     const Attribute* attr = elem->attributeItem(i);
1573                     
1574                     if (attr->prefix() == xmlnsAtom && attr->localName() == prefix) {
1575                         if (!attr->value().isEmpty())
1576                             return attr->value();
1577                         
1578                         return String();
1579                     } else if (attr->localName() == xmlnsAtom && prefix.isNull()) {
1580                         if (!attr->value().isEmpty())
1581                             return attr->value();
1582                         
1583                         return String();
1584                     }
1585                 }
1586             }
1587             if (Element* ancestor = ancestorElement())
1588                 return ancestor->lookupNamespaceURI(prefix);
1589             return String();
1590         }
1591         case DOCUMENT_NODE:
1592             if (Element* de = toDocument(this)->documentElement())
1593                 return de->lookupNamespaceURI(prefix);
1594             return String();
1595         case ENTITY_NODE:
1596         case NOTATION_NODE:
1597         case DOCUMENT_TYPE_NODE:
1598         case DOCUMENT_FRAGMENT_NODE:
1599             return String();
1600         case ATTRIBUTE_NODE: {
1601             const Attr *attr = static_cast<const Attr *>(this);
1602             
1603             if (attr->ownerElement())
1604                 return attr->ownerElement()->lookupNamespaceURI(prefix);
1605             else
1606                 return String();
1607         }
1608         default:
1609             if (Element* ancestor = ancestorElement())
1610                 return ancestor->lookupNamespaceURI(prefix);
1611             return String();
1612     }
1613 }
1614
1615 String Node::lookupNamespacePrefix(const AtomicString &_namespaceURI, const Element *originalElement) const
1616 {
1617     if (_namespaceURI.isNull())
1618         return String();
1619             
1620     if (originalElement->lookupNamespaceURI(prefix()) == _namespaceURI)
1621         return prefix();
1622     
1623     ASSERT(isElementNode());
1624     const Element* thisElement = toElement(this);
1625     if (thisElement->hasAttributes()) {
1626         for (unsigned i = 0; i < thisElement->attributeCount(); i++) {
1627             const Attribute* attr = thisElement->attributeItem(i);
1628             
1629             if (attr->prefix() == xmlnsAtom && attr->value() == _namespaceURI
1630                     && originalElement->lookupNamespaceURI(attr->localName()) == _namespaceURI)
1631                 return attr->localName();
1632         }
1633     }
1634     
1635     if (Element* ancestor = ancestorElement())
1636         return ancestor->lookupNamespacePrefix(_namespaceURI, originalElement);
1637     return String();
1638 }
1639
1640 static void appendTextContent(const Node* node, bool convertBRsToNewlines, bool& isNullString, StringBuilder& content)
1641 {
1642     switch (node->nodeType()) {
1643     case Node::TEXT_NODE:
1644     case Node::CDATA_SECTION_NODE:
1645     case Node::COMMENT_NODE:
1646         isNullString = false;
1647         content.append(static_cast<const CharacterData*>(node)->data());
1648         break;
1649
1650     case Node::PROCESSING_INSTRUCTION_NODE:
1651         isNullString = false;
1652         content.append(static_cast<const ProcessingInstruction*>(node)->data());
1653         break;
1654     
1655     case Node::ELEMENT_NODE:
1656         if (node->hasTagName(brTag) && convertBRsToNewlines) {
1657             isNullString = false;
1658             content.append('\n');
1659             break;
1660         }
1661     // Fall through.
1662     case Node::ATTRIBUTE_NODE:
1663     case Node::ENTITY_NODE:
1664     case Node::ENTITY_REFERENCE_NODE:
1665     case Node::DOCUMENT_FRAGMENT_NODE:
1666         isNullString = false;
1667         for (Node* child = node->firstChild(); child; child = child->nextSibling()) {
1668             if (child->nodeType() == Node::COMMENT_NODE || child->nodeType() == Node::PROCESSING_INSTRUCTION_NODE)
1669                 continue;
1670             appendTextContent(child, convertBRsToNewlines, isNullString, content);
1671         }
1672         break;
1673
1674     case Node::DOCUMENT_NODE:
1675     case Node::DOCUMENT_TYPE_NODE:
1676     case Node::NOTATION_NODE:
1677     case Node::XPATH_NAMESPACE_NODE:
1678         break;
1679     }
1680 }
1681
1682 String Node::textContent(bool convertBRsToNewlines) const
1683 {
1684     StringBuilder content;
1685     bool isNullString = true;
1686     appendTextContent(this, convertBRsToNewlines, isNullString, content);
1687     return isNullString ? String() : content.toString();
1688 }
1689
1690 void Node::setTextContent(const String& text, ExceptionCode& ec)
1691 {           
1692     switch (nodeType()) {
1693         case TEXT_NODE:
1694         case CDATA_SECTION_NODE:
1695         case COMMENT_NODE:
1696         case PROCESSING_INSTRUCTION_NODE:
1697             setNodeValue(text, ec);
1698             return;
1699         case ELEMENT_NODE:
1700         case ATTRIBUTE_NODE:
1701         case ENTITY_NODE:
1702         case ENTITY_REFERENCE_NODE:
1703         case DOCUMENT_FRAGMENT_NODE: {
1704             RefPtr<ContainerNode> container = toContainerNode(this);
1705             ChildListMutationScope mutation(this);
1706             container->removeChildren();
1707             if (!text.isEmpty())
1708                 container->appendChild(document()->createTextNode(text), ec);
1709             return;
1710         }
1711         case DOCUMENT_NODE:
1712         case DOCUMENT_TYPE_NODE:
1713         case NOTATION_NODE:
1714         case XPATH_NAMESPACE_NODE:
1715             // Do nothing.
1716             return;
1717     }
1718     ASSERT_NOT_REACHED();
1719 }
1720
1721 Element* Node::ancestorElement() const
1722 {
1723     // In theory, there can be EntityReference nodes between elements, but this is currently not supported.
1724     for (ContainerNode* n = parentNode(); n; n = n->parentNode()) {
1725         if (n->isElementNode())
1726             return toElement(n);
1727     }
1728     return 0;
1729 }
1730
1731 bool Node::offsetInCharacters() const
1732 {
1733     return false;
1734 }
1735
1736 unsigned short Node::compareDocumentPosition(Node* otherNode)
1737 {
1738     // It is not clear what should be done if |otherNode| is 0.
1739     if (!otherNode)
1740         return DOCUMENT_POSITION_DISCONNECTED;
1741
1742     if (otherNode == this)
1743         return DOCUMENT_POSITION_EQUIVALENT;
1744     
1745     Attr* attr1 = nodeType() == ATTRIBUTE_NODE ? static_cast<Attr*>(this) : 0;
1746     Attr* attr2 = otherNode->nodeType() == ATTRIBUTE_NODE ? static_cast<Attr*>(otherNode) : 0;
1747     
1748     Node* start1 = attr1 ? attr1->ownerElement() : this;
1749     Node* start2 = attr2 ? attr2->ownerElement() : otherNode;
1750     
1751     // If either of start1 or start2 is null, then we are disconnected, since one of the nodes is
1752     // an orphaned attribute node.
1753     if (!start1 || !start2)
1754         return DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC;
1755
1756     Vector<Node*, 16> chain1;
1757     Vector<Node*, 16> chain2;
1758     if (attr1)
1759         chain1.append(attr1);
1760     if (attr2)
1761         chain2.append(attr2);
1762     
1763     if (attr1 && attr2 && start1 == start2 && start1) {
1764         // We are comparing two attributes on the same node. Crawl our attribute map and see which one we hit first.
1765         Element* owner1 = attr1->ownerElement();
1766         owner1->synchronizeAllAttributes();
1767         unsigned length = owner1->attributeCount();
1768         for (unsigned i = 0; i < length; ++i) {
1769             // If neither of the two determining nodes is a child node and nodeType is the same for both determining nodes, then an 
1770             // implementation-dependent order between the determining nodes is returned. This order is stable as long as no nodes of
1771             // the same nodeType are inserted into or removed from the direct container. This would be the case, for example, 
1772             // when comparing two attributes of the same element, and inserting or removing additional attributes might change 
1773             // the order between existing attributes.
1774             const Attribute* attribute = owner1->attributeItem(i);
1775             if (attr1->qualifiedName() == attribute->name())
1776                 return DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | DOCUMENT_POSITION_FOLLOWING;
1777             if (attr2->qualifiedName() == attribute->name())
1778                 return DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | DOCUMENT_POSITION_PRECEDING;
1779         }
1780         
1781         ASSERT_NOT_REACHED();
1782         return DOCUMENT_POSITION_DISCONNECTED;
1783     }
1784
1785     // If one node is in the document and the other is not, we must be disconnected.
1786     // If the nodes have different owning documents, they must be disconnected.  Note that we avoid
1787     // comparing Attr nodes here, since they return false from inDocument() all the time (which seems like a bug).
1788     if (start1->inDocument() != start2->inDocument() ||
1789         start1->treeScope() != start2->treeScope())
1790         return DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC;
1791
1792     // We need to find a common ancestor container, and then compare the indices of the two immediate children.
1793     Node* current;
1794     for (current = start1; current; current = current->parentNode())
1795         chain1.append(current);
1796     for (current = start2; current; current = current->parentNode())
1797         chain2.append(current);
1798
1799     unsigned index1 = chain1.size();
1800     unsigned index2 = chain2.size();
1801
1802     // If the two elements don't have a common root, they're not in the same tree.
1803     if (chain1[index1 - 1] != chain2[index2 - 1]) {
1804         unsigned short direction = (start1 > start2) ? DOCUMENT_POSITION_PRECEDING : DOCUMENT_POSITION_FOLLOWING;
1805         return DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | direction;
1806     }
1807
1808     // Walk the two chains backwards and look for the first difference.
1809     for (unsigned i = min(index1, index2); i; --i) {
1810         Node* child1 = chain1[--index1];
1811         Node* child2 = chain2[--index2];
1812         if (child1 != child2) {
1813             // If one of the children is an attribute, it wins.
1814             if (child1->nodeType() == ATTRIBUTE_NODE)
1815                 return DOCUMENT_POSITION_FOLLOWING;
1816             if (child2->nodeType() == ATTRIBUTE_NODE)
1817                 return DOCUMENT_POSITION_PRECEDING;
1818             
1819             if (!child2->nextSibling())
1820                 return DOCUMENT_POSITION_FOLLOWING;
1821             if (!child1->nextSibling())
1822                 return DOCUMENT_POSITION_PRECEDING;
1823
1824             // Otherwise we need to see which node occurs first.  Crawl backwards from child2 looking for child1.
1825             for (Node* child = child2->previousSibling(); child; child = child->previousSibling()) {
1826                 if (child == child1)
1827                     return DOCUMENT_POSITION_FOLLOWING;
1828             }
1829             return DOCUMENT_POSITION_PRECEDING;
1830         }
1831     }
1832     
1833     // There was no difference between the two parent chains, i.e., one was a subset of the other.  The shorter
1834     // chain is the ancestor.
1835     return index1 < index2 ? 
1836                DOCUMENT_POSITION_FOLLOWING | DOCUMENT_POSITION_CONTAINED_BY :
1837                DOCUMENT_POSITION_PRECEDING | DOCUMENT_POSITION_CONTAINS;
1838 }
1839
1840 FloatPoint Node::convertToPage(const FloatPoint& p) const
1841 {
1842     // If there is a renderer, just ask it to do the conversion
1843     if (renderer())
1844         return renderer()->localToAbsolute(p, UseTransforms);
1845     
1846     // Otherwise go up the tree looking for a renderer
1847     Element *parent = ancestorElement();
1848     if (parent)
1849         return parent->convertToPage(p);
1850
1851     // No parent - no conversion needed
1852     return p;
1853 }
1854
1855 FloatPoint Node::convertFromPage(const FloatPoint& p) const
1856 {
1857     // If there is a renderer, just ask it to do the conversion
1858     if (renderer())
1859         return renderer()->absoluteToLocal(p, UseTransforms);
1860
1861     // Otherwise go up the tree looking for a renderer
1862     Element *parent = ancestorElement();
1863     if (parent)
1864         return parent->convertFromPage(p);
1865
1866     // No parent - no conversion needed
1867     return p;
1868 }
1869
1870 #ifndef NDEBUG
1871
1872 static void appendAttributeDesc(const Node* node, StringBuilder& stringBuilder, const QualifiedName& name, const char* attrDesc)
1873 {
1874     if (!node->isElementNode())
1875         return;
1876
1877     String attr = toElement(node)->getAttribute(name);
1878     if (attr.isEmpty())
1879         return;
1880
1881     stringBuilder.append(attrDesc);
1882     stringBuilder.append(attr);
1883 }
1884
1885 void Node::showNode(const char* prefix) const
1886 {
1887     if (!prefix)
1888         prefix = "";
1889     if (isTextNode()) {
1890         String value = nodeValue();
1891         value.replaceWithLiteral('\\', "\\\\");
1892         value.replaceWithLiteral('\n', "\\n");
1893         fprintf(stderr, "%s%s\t%p \"%s\"\n", prefix, nodeName().utf8().data(), this, value.utf8().data());
1894     } else {
1895         StringBuilder attrs;
1896         appendAttributeDesc(this, attrs, classAttr, " CLASS=");
1897         appendAttributeDesc(this, attrs, styleAttr, " STYLE=");
1898         fprintf(stderr, "%s%s\t%p%s\n", prefix, nodeName().utf8().data(), this, attrs.toString().utf8().data());
1899     }
1900 }
1901
1902 void Node::showTreeForThis() const
1903 {
1904     showTreeAndMark(this, "*");
1905 }
1906
1907 void Node::showNodePathForThis() const
1908 {
1909     Vector<const Node*, 16> chain;
1910     const Node* node = this;
1911     while (node->parentOrShadowHostNode()) {
1912         chain.append(node);
1913         node = node->parentOrShadowHostNode();
1914     }
1915     for (unsigned index = chain.size(); index > 0; --index) {
1916         const Node* node = chain[index - 1];
1917         if (node->isShadowRoot()) {
1918             int count = 0;
1919             for (ShadowRoot* shadowRoot = oldestShadowRootFor(toShadowRoot(node)->host()); shadowRoot && shadowRoot != node; shadowRoot = shadowRoot->youngerShadowRoot())
1920                 ++count;
1921             fprintf(stderr, "/#shadow-root[%d]", count);
1922             continue;
1923         }
1924
1925         switch (node->nodeType()) {
1926         case ELEMENT_NODE: {
1927             fprintf(stderr, "/%s", node->nodeName().utf8().data());
1928
1929             const Element* element = toElement(node);
1930             const AtomicString& idattr = element->getIdAttribute();
1931             bool hasIdAttr = !idattr.isNull() && !idattr.isEmpty();
1932             if (node->previousSibling() || node->nextSibling()) {
1933                 int count = 0;
1934                 for (Node* previous = node->previousSibling(); previous; previous = previous->previousSibling())
1935                     if (previous->nodeName() == node->nodeName())
1936                         ++count;
1937                 if (hasIdAttr)
1938                     fprintf(stderr, "[@id=\"%s\" and position()=%d]", idattr.string().utf8().data(), count);
1939                 else
1940                     fprintf(stderr, "[%d]", count);
1941             } else if (hasIdAttr)
1942                 fprintf(stderr, "[@id=\"%s\"]", idattr.string().utf8().data());
1943             break;
1944         }
1945         case TEXT_NODE:
1946             fprintf(stderr, "/text()");
1947             break;
1948         case ATTRIBUTE_NODE:
1949             fprintf(stderr, "/@%s", node->nodeName().utf8().data());
1950             break;
1951         default:
1952             break;
1953         }
1954     }
1955     fprintf(stderr, "\n");
1956 }
1957
1958 static void traverseTreeAndMark(const String& baseIndent, const Node* rootNode, const Node* markedNode1, const char* markedLabel1, const Node* markedNode2, const char* markedLabel2)
1959 {
1960     for (const Node* node = rootNode; node; node = NodeTraversal::next(node)) {
1961         if (node == markedNode1)
1962             fprintf(stderr, "%s", markedLabel1);
1963         if (node == markedNode2)
1964             fprintf(stderr, "%s", markedLabel2);
1965
1966         StringBuilder indent;
1967         indent.append(baseIndent);
1968         for (const Node* tmpNode = node; tmpNode && tmpNode != rootNode; tmpNode = tmpNode->parentOrShadowHostNode())
1969             indent.append('\t');
1970         fprintf(stderr, "%s", indent.toString().utf8().data());
1971         node->showNode();
1972         indent.append('\t');
1973         if (node->isShadowRoot()) {
1974             if (ShadowRoot* youngerShadowRoot = toShadowRoot(node)->youngerShadowRoot())
1975                 traverseTreeAndMark(indent.toString(), youngerShadowRoot, markedNode1, markedLabel1, markedNode2, markedLabel2);
1976         } else if (ShadowRoot* oldestShadowRoot = oldestShadowRootFor(node))
1977             traverseTreeAndMark(indent.toString(), oldestShadowRoot, markedNode1, markedLabel1, markedNode2, markedLabel2);
1978     }
1979 }
1980
1981 void Node::showTreeAndMark(const Node* markedNode1, const char* markedLabel1, const Node* markedNode2, const char* markedLabel2) const
1982 {
1983     const Node* rootNode;
1984     const Node* node = this;
1985     while (node->parentOrShadowHostNode() && !node->hasTagName(bodyTag))
1986         node = node->parentOrShadowHostNode();
1987     rootNode = node;
1988
1989     String startingIndent;
1990     traverseTreeAndMark(startingIndent, rootNode, markedNode1, markedLabel1, markedNode2, markedLabel2);
1991 }
1992
1993 void Node::formatForDebugger(char* buffer, unsigned length) const
1994 {
1995     String result;
1996     String s;
1997
1998     s = nodeName();
1999     if (s.isEmpty())
2000         result = "<none>";
2001     else
2002         result = s;
2003
2004     strncpy(buffer, result.utf8().data(), length - 1);
2005 }
2006
2007 static ContainerNode* parentOrShadowHostOrFrameOwner(const Node* node)
2008 {
2009     ContainerNode* parent = node->parentOrShadowHostNode();
2010     if (!parent && node->document() && node->document()->frame())
2011         parent = node->document()->frame()->ownerElement();
2012     return parent;
2013 }
2014
2015 static void showSubTreeAcrossFrame(const Node* node, const Node* markedNode, const String& indent)
2016 {
2017     if (node == markedNode)
2018         fputs("*", stderr);
2019     fputs(indent.utf8().data(), stderr);
2020     node->showNode();
2021      if (node->isShadowRoot()) {
2022          if (ShadowRoot* youngerShadowRoot = toShadowRoot(node)->youngerShadowRoot())
2023              showSubTreeAcrossFrame(youngerShadowRoot, markedNode, indent + "\t");
2024      } else {
2025          if (node->isFrameOwnerElement())
2026              showSubTreeAcrossFrame(static_cast<const HTMLFrameOwnerElement*>(node)->contentDocument(), markedNode, indent + "\t");
2027          if (ShadowRoot* oldestShadowRoot = oldestShadowRootFor(node))
2028              showSubTreeAcrossFrame(oldestShadowRoot, markedNode, indent + "\t");
2029      }
2030     for (Node* child = node->firstChild(); child; child = child->nextSibling())
2031         showSubTreeAcrossFrame(child, markedNode, indent + "\t");
2032 }
2033
2034 void Node::showTreeForThisAcrossFrame() const
2035 {
2036     Node* rootNode = const_cast<Node*>(this);
2037     while (parentOrShadowHostOrFrameOwner(rootNode))
2038         rootNode = parentOrShadowHostOrFrameOwner(rootNode);
2039     showSubTreeAcrossFrame(rootNode, this, "");
2040 }
2041
2042 #endif
2043
2044 // --------
2045
2046 void NodeListsNodeData::invalidateCaches(const QualifiedName* attrName)
2047 {
2048     NodeListAtomicNameCacheMap::const_iterator atomicNameCacheEnd = m_atomicNameCaches.end();
2049     for (NodeListAtomicNameCacheMap::const_iterator it = m_atomicNameCaches.begin(); it != atomicNameCacheEnd; ++it)
2050         it->value->invalidateCache(attrName);
2051
2052     NodeListNameCacheMap::const_iterator nameCacheEnd = m_nameCaches.end();
2053     for (NodeListNameCacheMap::const_iterator it = m_nameCaches.begin(); it != nameCacheEnd; ++it)
2054         it->value->invalidateCache(attrName);
2055
2056     if (attrName)
2057         return;
2058
2059     TagNodeListCacheNS::iterator tagCacheEnd = m_tagNodeListCacheNS.end();
2060     for (TagNodeListCacheNS::iterator it = m_tagNodeListCacheNS.begin(); it != tagCacheEnd; ++it)
2061         it->value->invalidateCache();
2062 }
2063
2064 void Node::getSubresourceURLs(ListHashSet<KURL>& urls) const
2065 {
2066     addSubresourceAttributeURLs(urls);
2067 }
2068
2069 Node* Node::enclosingLinkEventParentOrSelf()
2070 {
2071     for (Node* node = this; node; node = node->parentOrShadowHostNode()) {
2072         // For imagemaps, the enclosing link node is the associated area element not the image itself.
2073         // So we don't let images be the enclosingLinkNode, even though isLink sometimes returns true
2074         // for them.
2075         if (node->isLink() && !node->hasTagName(imgTag))
2076             return node;
2077     }
2078
2079     return 0;
2080 }
2081
2082 const AtomicString& Node::interfaceName() const
2083 {
2084     return eventNames().interfaceForNode;
2085 }
2086
2087 ScriptExecutionContext* Node::scriptExecutionContext() const
2088 {
2089     return document();
2090 }
2091
2092 void Node::didMoveToNewDocument(Document* oldDocument)
2093 {
2094     TreeScopeAdopter::ensureDidMoveToNewDocumentWasCalled(oldDocument);
2095
2096     if (AXObjectCache::accessibilityEnabled() && oldDocument && oldDocument->axObjectCacheExists())
2097         oldDocument->axObjectCache()->remove(this);
2098
2099     // FIXME: Event listener types for this node should be set on the new owner document here.
2100
2101     const EventListenerVector& wheelListeners = getEventListeners(eventNames().mousewheelEvent);
2102     for (size_t i = 0; i < wheelListeners.size(); ++i) {
2103         oldDocument->didRemoveWheelEventHandler();
2104         document()->didAddWheelEventHandler();
2105     }
2106
2107     Vector<AtomicString> touchEventNames = eventNames().touchEventNames();
2108     for (size_t i = 0; i < touchEventNames.size(); ++i) {
2109         const EventListenerVector& listeners = getEventListeners(touchEventNames[i]);
2110         for (size_t j = 0; j < listeners.size(); ++j) {
2111             oldDocument->didRemoveTouchEventHandler(this);
2112             document()->didAddTouchEventHandler(this);
2113         }
2114     }
2115
2116     if (Vector<OwnPtr<MutationObserverRegistration> >* registry = mutationObserverRegistry()) {
2117         for (size_t i = 0; i < registry->size(); ++i) {
2118             document()->addMutationObserverTypes(registry->at(i)->mutationTypes());
2119         }
2120     }
2121
2122     if (HashSet<MutationObserverRegistration*>* transientRegistry = transientMutationObserverRegistry()) {
2123         for (HashSet<MutationObserverRegistration*>::iterator iter = transientRegistry->begin(); iter != transientRegistry->end(); ++iter) {
2124             document()->addMutationObserverTypes((*iter)->mutationTypes());
2125         }
2126     }
2127 }
2128
2129 static inline bool tryAddEventListener(Node* targetNode, const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
2130 {
2131     if (!targetNode->EventTarget::addEventListener(eventType, listener, useCapture))
2132         return false;
2133
2134     if (Document* document = targetNode->document()) {
2135         document->addListenerTypeIfNeeded(eventType);
2136         if (eventType == eventNames().mousewheelEvent)
2137             document->didAddWheelEventHandler();
2138         else if (eventNames().isTouchEventType(eventType))
2139             document->didAddTouchEventHandler(targetNode);
2140     }
2141
2142     return true;
2143 }
2144
2145 bool Node::addEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
2146 {
2147     return tryAddEventListener(this, eventType, listener, useCapture);
2148 }
2149
2150 static inline bool tryRemoveEventListener(Node* targetNode, const AtomicString& eventType, EventListener* listener, bool useCapture)
2151 {
2152     if (!targetNode->EventTarget::removeEventListener(eventType, listener, useCapture))
2153         return false;
2154
2155     // FIXME: Notify Document that the listener has vanished. We need to keep track of a number of
2156     // listeners for each type, not just a bool - see https://bugs.webkit.org/show_bug.cgi?id=33861
2157     if (Document* document = targetNode->document()) {
2158         if (eventType == eventNames().mousewheelEvent)
2159             document->didRemoveWheelEventHandler();
2160         else if (eventNames().isTouchEventType(eventType))
2161             document->didRemoveTouchEventHandler(targetNode);
2162     }
2163
2164     return true;
2165 }
2166
2167 bool Node::removeEventListener(const AtomicString& eventType, EventListener* listener, bool useCapture)
2168 {
2169     return tryRemoveEventListener(this, eventType, listener, useCapture);
2170 }
2171
2172 typedef HashMap<Node*, OwnPtr<EventTargetData> > EventTargetDataMap;
2173
2174 static EventTargetDataMap& eventTargetDataMap()
2175 {
2176     DEFINE_STATIC_LOCAL(EventTargetDataMap, map, ());
2177     return map;
2178 }
2179
2180 EventTargetData* Node::eventTargetData()
2181 {
2182     return hasEventTargetData() ? eventTargetDataMap().get(this) : 0;
2183 }
2184
2185 EventTargetData* Node::ensureEventTargetData()
2186 {
2187     if (hasEventTargetData())
2188         return eventTargetDataMap().get(this);
2189     setHasEventTargetData(true);
2190     EventTargetData* data = new EventTargetData;
2191     eventTargetDataMap().set(this, adoptPtr(data));
2192     return data;
2193 }
2194
2195 void Node::clearEventTargetData()
2196 {
2197     eventTargetDataMap().remove(this);
2198 }
2199
2200 Vector<OwnPtr<MutationObserverRegistration> >* Node::mutationObserverRegistry()
2201 {
2202     if (!hasRareData())
2203         return 0;
2204     NodeMutationObserverData* data = rareData()->mutationObserverData();
2205     if (!data)
2206         return 0;
2207     return &data->registry;
2208 }
2209
2210 HashSet<MutationObserverRegistration*>* Node::transientMutationObserverRegistry()
2211 {
2212     if (!hasRareData())
2213         return 0;
2214     NodeMutationObserverData* data = rareData()->mutationObserverData();
2215     if (!data)
2216         return 0;
2217     return &data->transientRegistry;
2218 }
2219
2220 template<typename Registry>
2221 static inline void collectMatchingObserversForMutation(HashMap<MutationObserver*, MutationRecordDeliveryOptions>& observers, Registry* registry, Node* target, MutationObserver::MutationType type, const QualifiedName* attributeName)
2222 {
2223     if (!registry)
2224         return;
2225     for (typename Registry::iterator iter = registry->begin(); iter != registry->end(); ++iter) {
2226         const MutationObserverRegistration& registration = **iter;
2227         if (registration.shouldReceiveMutationFrom(target, type, attributeName)) {
2228             MutationRecordDeliveryOptions deliveryOptions = registration.deliveryOptions();
2229             HashMap<MutationObserver*, MutationRecordDeliveryOptions>::AddResult result = observers.add(registration.observer(), deliveryOptions);
2230             if (!result.isNewEntry)
2231                 result.iterator->value |= deliveryOptions;
2232         }
2233     }
2234 }
2235
2236 void Node::getRegisteredMutationObserversOfType(HashMap<MutationObserver*, MutationRecordDeliveryOptions>& observers, MutationObserver::MutationType type, const QualifiedName* attributeName)
2237 {
2238     ASSERT((type == MutationObserver::Attributes && attributeName) || !attributeName);
2239     collectMatchingObserversForMutation(observers, mutationObserverRegistry(), this, type, attributeName);
2240     collectMatchingObserversForMutation(observers, transientMutationObserverRegistry(), this, type, attributeName);
2241     for (Node* node = parentNode(); node; node = node->parentNode()) {
2242         collectMatchingObserversForMutation(observers, node->mutationObserverRegistry(), this, type, attributeName);
2243         collectMatchingObserversForMutation(observers, node->transientMutationObserverRegistry(), this, type, attributeName);
2244     }
2245 }
2246
2247 void Node::registerMutationObserver(MutationObserver* observer, MutationObserverOptions options, const HashSet<AtomicString>& attributeFilter)
2248 {
2249     MutationObserverRegistration* registration = 0;
2250     Vector<OwnPtr<MutationObserverRegistration> >& registry = ensureRareData()->ensureMutationObserverData()->registry;
2251     for (size_t i = 0; i < registry.size(); ++i) {
2252         if (registry[i]->observer() == observer) {
2253             registration = registry[i].get();
2254             registration->resetObservation(options, attributeFilter);
2255         }
2256     }
2257
2258     if (!registration) {
2259         registry.append(MutationObserverRegistration::create(observer, this, options, attributeFilter));
2260         registration = registry.last().get();
2261     }
2262
2263     document()->addMutationObserverTypes(registration->mutationTypes());
2264 }
2265
2266 void Node::unregisterMutationObserver(MutationObserverRegistration* registration)
2267 {
2268     Vector<OwnPtr<MutationObserverRegistration> >* registry = mutationObserverRegistry();
2269     ASSERT(registry);
2270     if (!registry)
2271         return;
2272
2273     size_t index = registry->find(registration);
2274     ASSERT(index != notFound);
2275     if (index == notFound)
2276         return;
2277
2278     registry->remove(index);
2279 }
2280
2281 void Node::registerTransientMutationObserver(MutationObserverRegistration* registration)
2282 {
2283     ensureRareData()->ensureMutationObserverData()->transientRegistry.add(registration);
2284 }
2285
2286 void Node::unregisterTransientMutationObserver(MutationObserverRegistration* registration)
2287 {
2288     HashSet<MutationObserverRegistration*>* transientRegistry = transientMutationObserverRegistry();
2289     ASSERT(transientRegistry);
2290     if (!transientRegistry)
2291         return;
2292
2293     ASSERT(transientRegistry->contains(registration));
2294     transientRegistry->remove(registration);
2295 }
2296
2297 void Node::notifyMutationObserversNodeWillDetach()
2298 {
2299     if (!document()->hasMutationObservers())
2300         return;
2301
2302     for (Node* node = parentNode(); node; node = node->parentNode()) {
2303         if (Vector<OwnPtr<MutationObserverRegistration> >* registry = node->mutationObserverRegistry()) {
2304             const size_t size = registry->size();
2305             for (size_t i = 0; i < size; ++i)
2306                 registry->at(i)->observedSubtreeNodeWillDetach(this);
2307         }
2308
2309         if (HashSet<MutationObserverRegistration*>* transientRegistry = node->transientMutationObserverRegistry()) {
2310             for (HashSet<MutationObserverRegistration*>::iterator iter = transientRegistry->begin(); iter != transientRegistry->end(); ++iter)
2311                 (*iter)->observedSubtreeNodeWillDetach(this);
2312         }
2313     }
2314 }
2315
2316 void Node::handleLocalEvents(Event* event)
2317 {
2318     if (!hasEventTargetData())
2319         return;
2320
2321     if (disabled() && event->isMouseEvent())
2322         return;
2323
2324     fireEventListeners(event);
2325 }
2326
2327 void Node::dispatchScopedEvent(PassRefPtr<Event> event)
2328 {
2329     dispatchScopedEventDispatchMediator(EventDispatchMediator::create(event));
2330 }
2331
2332 void Node::dispatchScopedEventDispatchMediator(PassRefPtr<EventDispatchMediator> eventDispatchMediator)
2333 {
2334     EventDispatcher::dispatchScopedEvent(this, eventDispatchMediator);
2335 }
2336
2337 bool Node::dispatchEvent(PassRefPtr<Event> event)
2338 {
2339     if (event->isMouseEvent())
2340         return EventDispatcher::dispatchEvent(this, MouseEventDispatchMediator::create(adoptRef(toMouseEvent(event.leakRef())), MouseEventDispatchMediator::SyntheticMouseEvent));
2341 #if ENABLE(TOUCH_EVENTS)
2342     if (event->isTouchEvent())
2343         return dispatchTouchEvent(adoptRef(toTouchEvent(event.leakRef())));
2344 #endif
2345     return EventDispatcher::dispatchEvent(this, EventDispatchMediator::create(event));
2346 }
2347
2348 void Node::dispatchSubtreeModifiedEvent()
2349 {
2350     if (isInShadowTree())
2351         return;
2352
2353     ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2354
2355     if (!document()->hasListenerType(Document::DOMSUBTREEMODIFIED_LISTENER))
2356         return;
2357
2358     dispatchScopedEvent(MutationEvent::create(eventNames().DOMSubtreeModifiedEvent, true));
2359 }
2360
2361 void Node::dispatchFocusInEvent(const AtomicString& eventType, PassRefPtr<Node> oldFocusedNode)
2362 {
2363     ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2364     ASSERT(eventType == eventNames().focusinEvent || eventType == eventNames().DOMFocusInEvent);
2365     dispatchScopedEventDispatchMediator(FocusInEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document()->defaultView(), 0, oldFocusedNode)));
2366 }
2367
2368 void Node::dispatchFocusOutEvent(const AtomicString& eventType, PassRefPtr<Node> newFocusedNode)
2369 {
2370     ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2371     ASSERT(eventType == eventNames().focusoutEvent || eventType == eventNames().DOMFocusOutEvent);
2372     dispatchScopedEventDispatchMediator(FocusOutEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document()->defaultView(), 0, newFocusedNode)));
2373 }
2374
2375 bool Node::dispatchDOMActivateEvent(int detail, PassRefPtr<Event> underlyingEvent)
2376 {
2377     ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2378     RefPtr<UIEvent> event = UIEvent::create(eventNames().DOMActivateEvent, true, true, document()->defaultView(), detail);
2379     event->setUnderlyingEvent(underlyingEvent);
2380     dispatchScopedEvent(event);
2381     return event->defaultHandled();
2382 }
2383
2384 bool Node::dispatchKeyEvent(const PlatformKeyboardEvent& event)
2385 {
2386     return EventDispatcher::dispatchEvent(this, KeyboardEventDispatchMediator::create(KeyboardEvent::create(event, document()->defaultView())));
2387 }
2388
2389 bool Node::dispatchMouseEvent(const PlatformMouseEvent& event, const AtomicString& eventType,
2390     int detail, Node* relatedTarget)
2391 {
2392     return EventDispatcher::dispatchEvent(this, MouseEventDispatchMediator::create(MouseEvent::create(eventType, document()->defaultView(), event, detail, relatedTarget)));
2393 }
2394
2395 #if ENABLE(GESTURE_EVENTS)
2396 bool Node::dispatchGestureEvent(const PlatformGestureEvent& event)
2397 {
2398     RefPtr<GestureEvent> gestureEvent = GestureEvent::create(document()->defaultView(), event);
2399     if (!gestureEvent.get())
2400         return false;
2401     return EventDispatcher::dispatchEvent(this, GestureEventDispatchMediator::create(gestureEvent));
2402 }
2403 #endif
2404
2405 #if ENABLE(TOUCH_EVENTS)
2406 bool Node::dispatchTouchEvent(PassRefPtr<TouchEvent> event)
2407 {
2408     return EventDispatcher::dispatchEvent(this, TouchEventDispatchMediator::create(event));
2409 }
2410 #endif
2411
2412 void Node::dispatchSimulatedClick(Event* underlyingEvent, SimulatedClickMouseEventOptions eventOptions, SimulatedClickVisualOptions visualOptions)
2413 {
2414     EventDispatcher::dispatchSimulatedClick(this, underlyingEvent, eventOptions, visualOptions);
2415 }
2416
2417 bool Node::dispatchBeforeLoadEvent(const String& sourceURL)
2418 {
2419     if (!document()->hasListenerType(Document::BEFORELOAD_LISTENER))
2420         return true;
2421
2422     RefPtr<Node> protector(this);
2423     RefPtr<BeforeLoadEvent> beforeLoadEvent = BeforeLoadEvent::create(sourceURL);
2424     dispatchEvent(beforeLoadEvent.get());
2425     return !beforeLoadEvent->defaultPrevented();
2426 }
2427
2428 bool Node::dispatchWheelEvent(const PlatformWheelEvent& event)
2429 {
2430     return EventDispatcher::dispatchEvent(this, WheelEventDispatchMediator::create(event, document()->defaultView()));
2431 }
2432
2433 void Node::dispatchFocusEvent(PassRefPtr<Node> oldFocusedNode, FocusDirection)
2434 {
2435     if (document()->page())
2436         document()->page()->chrome()->client()->elementDidFocus(this);
2437
2438     RefPtr<FocusEvent> event = FocusEvent::create(eventNames().focusEvent, false, false, document()->defaultView(), 0, oldFocusedNode);
2439     EventDispatcher::dispatchEvent(this, FocusEventDispatchMediator::create(event.release()));
2440 }
2441
2442 void Node::dispatchBlurEvent(PassRefPtr<Node> newFocusedNode)
2443 {
2444     if (document()->page())
2445         document()->page()->chrome()->client()->elementDidBlur(this);
2446
2447     RefPtr<FocusEvent> event = FocusEvent::create(eventNames().blurEvent, false, false, document()->defaultView(), 0, newFocusedNode);
2448     EventDispatcher::dispatchEvent(this, BlurEventDispatchMediator::create(event.release()));
2449 }
2450
2451 void Node::dispatchChangeEvent()
2452 {
2453     dispatchScopedEvent(Event::create(eventNames().changeEvent, true, false));
2454 }
2455
2456 void Node::dispatchInputEvent()
2457 {
2458     dispatchScopedEvent(Event::create(eventNames().inputEvent, true, false));
2459 }
2460
2461 bool Node::disabled() const
2462 {
2463 #if ENABLE(DIALOG_ELEMENT)
2464     if (isInert())
2465         return true;
2466 #endif
2467     return false;
2468 }
2469
2470 void Node::defaultEventHandler(Event* event)
2471 {
2472     if (event->target() != this)
2473         return;
2474     const AtomicString& eventType = event->type();
2475     if (eventType == eventNames().keydownEvent || eventType == eventNames().keypressEvent) {
2476         if (event->isKeyboardEvent())
2477             if (Frame* frame = document()->frame())
2478                 frame->eventHandler()->defaultKeyboardEventHandler(static_cast<KeyboardEvent*>(event));
2479     } else if (eventType == eventNames().clickEvent) {
2480         int detail = event->isUIEvent() ? static_cast<UIEvent*>(event)->detail() : 0;
2481         if (dispatchDOMActivateEvent(detail, event))
2482             event->setDefaultHandled();
2483 #if ENABLE(CONTEXT_MENUS)
2484     } else if (eventType == eventNames().contextmenuEvent) {
2485         if (Frame* frame = document()->frame())
2486             if (Page* page = frame->page())
2487                 page->contextMenuController()->handleContextMenuEvent(event);
2488 #endif
2489     } else if (eventType == eventNames().textInputEvent) {
2490         if (event->hasInterface(eventNames().interfaceForTextEvent))
2491             if (Frame* frame = document()->frame())
2492                 frame->eventHandler()->defaultTextInputEventHandler(static_cast<TextEvent*>(event));
2493 #if ENABLE(PAN_SCROLLING)
2494     } else if (eventType == eventNames().mousedownEvent && event->isMouseEvent()) {
2495         MouseEvent* mouseEvent = static_cast<MouseEvent*>(event);
2496         if (mouseEvent->button() == MiddleButton) {
2497             if (enclosingLinkEventParentOrSelf())
2498                 return;
2499
2500             RenderObject* renderer = this->renderer();
2501             while (renderer && (!renderer->isBox() || !toRenderBox(renderer)->canBeScrolledAndHasScrollableArea()))
2502                 renderer = renderer->parent();
2503
2504             if (renderer) {
2505                 if (Frame* frame = document()->frame())
2506                     frame->eventHandler()->startPanScrolling(renderer);
2507             }
2508         }
2509 #endif
2510     } else if (eventType == eventNames().mousewheelEvent && event->hasInterface(eventNames().interfaceForWheelEvent)) {
2511         WheelEvent* wheelEvent = static_cast<WheelEvent*>(event);
2512         
2513         // If we don't have a renderer, send the wheel event to the first node we find with a renderer.
2514         // This is needed for <option> and <optgroup> elements so that <select>s get a wheel scroll.
2515         Node* startNode = this;
2516         while (startNode && !startNode->renderer())
2517             startNode = startNode->parentOrShadowHostNode();
2518         
2519         if (startNode && startNode->renderer())
2520             if (Frame* frame = document()->frame())
2521                 frame->eventHandler()->defaultWheelEventHandler(startNode, wheelEvent);
2522     } else if (event->type() == eventNames().webkitEditableContentChangedEvent) {
2523         dispatchInputEvent();
2524     }
2525 }
2526
2527 bool Node::willRespondToMouseMoveEvents()
2528 {
2529     if (disabled())
2530         return false;
2531     return hasEventListeners(eventNames().mousemoveEvent) || hasEventListeners(eventNames().mouseoverEvent) || hasEventListeners(eventNames().mouseoutEvent);
2532 }
2533
2534 bool Node::willRespondToMouseClickEvents()
2535 {
2536     if (disabled())
2537         return false;
2538     return isContentEditable(UserSelectAllIsAlwaysNonEditable) || hasEventListeners(eventNames().mouseupEvent) || hasEventListeners(eventNames().mousedownEvent) || hasEventListeners(eventNames().clickEvent) || hasEventListeners(eventNames().DOMActivateEvent);
2539 }
2540
2541 bool Node::willRespondToTouchEvents()
2542 {
2543 #if ENABLE(TOUCH_EVENTS)
2544     if (disabled())
2545         return false;
2546     return hasEventListeners(eventNames().touchstartEvent) || hasEventListeners(eventNames().touchmoveEvent) || hasEventListeners(eventNames().touchcancelEvent) || hasEventListeners(eventNames().touchendEvent);
2547 #else
2548     return false;
2549 #endif
2550 }
2551
2552 #if ENABLE(MICRODATA)
2553 DOMSettableTokenList* Node::itemProp()
2554 {
2555     return ensureRareData()->ensureMicroDataTokenLists()->itemProp(this);
2556 }
2557
2558 void Node::setItemProp(const String& value)
2559 {
2560     ensureRareData()->ensureMicroDataTokenLists()->itemProp(this)->setValueInternal(value);
2561 }
2562
2563 DOMSettableTokenList* Node::itemRef()
2564 {
2565     return ensureRareData()->ensureMicroDataTokenLists()->itemRef(this);
2566 }
2567
2568 void Node::setItemRef(const String& value)
2569 {
2570     ensureRareData()->ensureMicroDataTokenLists()->itemRef(this)->setValueInternal(value);
2571 }
2572
2573 DOMSettableTokenList* Node::itemType()
2574 {
2575     return ensureRareData()->ensureMicroDataTokenLists()->itemType(this);
2576 }
2577
2578 void Node::setItemType(const String& value)
2579 {
2580     ensureRareData()->ensureMicroDataTokenLists()->itemType(this)->setValueInternal(value);
2581 }
2582
2583 PassRefPtr<PropertyNodeList> Node::propertyNodeList(const String& name)
2584 {
2585     return ensureRareData()->ensureNodeLists()->addCacheWithName<PropertyNodeList>(this, PropertyNodeListType, name);
2586 }
2587 #endif
2588
2589 // This is here for inlining
2590 inline void TreeScope::removedLastRefToScope()
2591 {
2592     ASSERT(!deletionHasBegun());
2593     if (m_guardRefCount) {
2594         // If removing a child removes the last self-only ref, we don't
2595         // want the scope to be destructed until after
2596         // removeDetachedChildren returns, so we guard ourselves with an
2597         // extra self-only ref.
2598         guardRef();
2599         dispose();
2600 #ifndef NDEBUG
2601         // We need to do this right now since guardDeref() can delete this.
2602         rootNode()->m_inRemovedLastRefFunction = false;
2603 #endif
2604         guardDeref();
2605     } else {
2606 #ifndef NDEBUG
2607         rootNode()->m_inRemovedLastRefFunction = false;
2608         beginDeletion();
2609 #endif
2610         delete this;
2611     }
2612 }
2613
2614 // It's important not to inline removedLastRef, because we don't want to inline the code to
2615 // delete a Node at each deref call site.
2616 void Node::removedLastRef()
2617 {
2618     // An explicit check for Document here is better than a virtual function since it is
2619     // faster for non-Document nodes, and because the call to removedLastRef that is inlined
2620     // at all deref call sites is smaller if it's a non-virtual function.
2621     if (isTreeScope()) {
2622         treeScope()->removedLastRefToScope();
2623         return;
2624     }
2625
2626 #ifndef NDEBUG
2627     m_deletionHasBegun = true;
2628 #endif
2629     delete this;
2630 }
2631
2632 void Node::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
2633 {
2634     MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::DOM);
2635     ScriptWrappable::reportMemoryUsage(memoryObjectInfo);
2636     info.addMember(m_parentOrShadowHostNode, "parentOrShadowHostNode");
2637     info.addMember(m_treeScope, "treeScope");
2638     info.ignoreMember(m_next);
2639     info.ignoreMember(m_previous);
2640     info.addMember(this->renderer(), "renderer");
2641     if (hasRareData()) {
2642         if (isElementNode())
2643             info.addMember(static_cast<ElementRareData*>(rareData()), "elementRareData");
2644         else
2645             info.addMember(rareData(), "rareData");
2646     }
2647 }
2648
2649 void Node::textRects(Vector<IntRect>& rects) const
2650 {
2651     RefPtr<Range> range = Range::create(document());
2652     range->selectNodeContents(const_cast<Node*>(this), IGNORE_EXCEPTION);
2653     range->textRects(rects);
2654 }
2655
2656 unsigned Node::connectedSubframeCount() const
2657 {
2658     return hasRareData() ? rareData()->connectedSubframeCount() : 0;
2659 }
2660
2661 void Node::incrementConnectedSubframeCount(unsigned amount)
2662 {
2663     ASSERT(isContainerNode());
2664     ensureRareData()->incrementConnectedSubframeCount(amount);
2665 }
2666
2667 void Node::decrementConnectedSubframeCount(unsigned amount)
2668 {
2669     rareData()->decrementConnectedSubframeCount(amount);
2670 }
2671
2672 void Node::updateAncestorConnectedSubframeCountForRemoval() const
2673 {
2674     unsigned count = connectedSubframeCount();
2675
2676     if (!count)
2677         return;
2678
2679     for (Node* node = parentOrShadowHostNode(); node; node = node->parentOrShadowHostNode())
2680         node->decrementConnectedSubframeCount(count);
2681 }
2682
2683 void Node::updateAncestorConnectedSubframeCountForInsertion() const
2684 {
2685     unsigned count = connectedSubframeCount();
2686
2687     if (!count)
2688         return;
2689
2690     for (Node* node = parentOrShadowHostNode(); node; node = node->parentOrShadowHostNode())
2691         node->incrementConnectedSubframeCount(count);
2692 }
2693
2694 void Node::registerScopedHTMLStyleChild()
2695 {
2696     setHasScopedHTMLStyleChild(true);
2697 }
2698
2699 void Node::unregisterScopedHTMLStyleChild()
2700 {
2701     ASSERT(hasScopedHTMLStyleChild());
2702     setHasScopedHTMLStyleChild(numberOfScopedHTMLStyleChildren());
2703 }
2704
2705 size_t Node::numberOfScopedHTMLStyleChildren() const
2706 {
2707     size_t count = 0;
2708     for (Node* child = firstChild(); child; child = child->nextSibling()) {
2709         if (child->hasTagName(HTMLNames::styleTag) && static_cast<HTMLStyleElement*>(child)->isRegisteredAsScoped())
2710             count++;
2711     }
2712
2713     return count;
2714 }
2715
2716 void Node::setFocus(bool flag)
2717 {
2718     if (Document* document = this->document())
2719         document->userActionElements().setFocused(this, flag);
2720 }
2721
2722 void Node::setActive(bool flag, bool)
2723 {
2724     if (Document* document = this->document())
2725         document->userActionElements().setActive(this, flag);
2726 }
2727
2728 void Node::setHovered(bool flag)
2729 {
2730     if (Document* document = this->document())
2731         document->userActionElements().setHovered(this, flag);
2732 }
2733
2734 bool Node::isUserActionElementActive() const
2735 {
2736     ASSERT(isUserActionElement());
2737     return document()->userActionElements().isActive(this);
2738 }
2739
2740 bool Node::isUserActionElementInActiveChain() const
2741 {
2742     ASSERT(isUserActionElement());
2743     return document()->userActionElements().isInActiveChain(this);
2744 }
2745
2746 bool Node::isUserActionElementHovered() const
2747 {
2748     ASSERT(isUserActionElement());
2749     return document()->userActionElements().isHovered(this);
2750 }
2751
2752 bool Node::isUserActionElementFocused() const
2753 {
2754     ASSERT(isUserActionElement());
2755     return document()->userActionElements().isFocused(this);
2756 }
2757
2758 } // namespace WebCore
2759
2760 #ifndef NDEBUG
2761
2762 void showTree(const WebCore::Node* node)
2763 {
2764     if (node)
2765         node->showTreeForThis();
2766 }
2767
2768 void showNodePath(const WebCore::Node* node)
2769 {
2770     if (node)
2771         node->showNodePathForThis();
2772 }
2773
2774 #endif