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