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