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