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