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