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