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