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