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