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/)
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.
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.
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.
28 #include "AXObjectCache.h"
30 #include "Attribute.h"
32 #include "ChromeClient.h"
33 #include "CSSParser.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"
46 #include "DocumentType.h"
47 #include "DynamicNodeList.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"
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"
67 #include "MouseEvent.h"
68 #include "MutationEvent.h"
69 #include "NameNodeList.h"
70 #include "NamedNodeMap.h"
71 #include "NodeRareData.h"
72 #include "NodeRenderingContext.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"
89 #include "TextEvent.h"
91 #include "UIEventWithKeyState.h"
92 #include "WebKitAnimationEvent.h"
93 #include "WebKitTransitionEvent.h"
94 #include "WheelEvent.h"
95 #include "WindowEventContext.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>
105 #if ENABLE(DOM_STORAGE)
106 #include "StorageEvent.h"
110 #include "SVGElementInstance.h"
111 #include "SVGUseElement.h"
115 #include "HTMLNoScriptElement.h"
119 #include <runtime/JSGlobalData.h>
122 #define DUMP_NODE_STATISTICS 0
128 using namespace HTMLNames;
130 bool Node::isSupported(const String& feature, const String& version)
132 return DOMImplementation::hasFeature(feature, version);
135 #if DUMP_NODE_STATISTICS
136 static HashSet<Node*> liveNodeSet;
139 void Node::dumpStatistics()
141 #if DUMP_NODE_STATISTICS
142 size_t nodesWithRareData = 0;
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;
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;
159 HashMap<String, size_t> perTagCount;
161 size_t attributes = 0;
162 size_t mappedAttributes = 0;
163 size_t mappedAttributesWithStyleDecl = 0;
164 size_t attributesWithAttr = 0;
167 for (HashSet<Node*>::iterator it = liveNodeSet.begin(); it != liveNodeSet.end(); ++it) {
170 if (node->hasRareData())
173 switch (node->nodeType()) {
178 Element* element = static_cast<Element*>(node);
179 pair<HashMap<String, size_t>::iterator, bool> result = perTagCount.add(element->tagName(), 1);
181 result.first->second++;
183 // AttributeMap stats
184 if (NamedNodeMap* attrMap = element->attributes(true)) {
185 attributes += attrMap->length();
187 for (unsigned i = 0; i < attrMap->length(); ++i) {
188 Attribute* attr = attrMap->attributeItem(i);
190 ++attributesWithAttr;
191 if (attr->isMappedAttribute()) {
194 ++mappedAttributesWithStyleDecl;
200 case ATTRIBUTE_NODE: {
208 case CDATA_SECTION_NODE: {
216 case ENTITY_REFERENCE_NODE: {
217 ++entityReferenceNodes;
224 case PROCESSING_INSTRUCTION_NODE: {
228 case DOCUMENT_NODE: {
232 case DOCUMENT_TYPE_NODE: {
236 case DOCUMENT_FRAGMENT_NODE: {
240 case NOTATION_NODE: {
244 case XPATH_NAMESPACE_NODE: {
248 case SHADOW_ROOT_NODE: {
255 printf("Number of Nodes: %d\n\n", liveNodeSet.size());
256 printf("Number of Nodes with RareData: %zu\n\n", nodesWithRareData);
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);
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);
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));
288 static WTF::RefCountedLeakCounter nodeCounter("WebCoreNode");
290 static bool shouldIgnoreLeaks = false;
291 static HashSet<Node*> ignoreSet;
294 void Node::startIgnoringLeaks()
297 shouldIgnoreLeaks = true;
301 void Node::stopIgnoringLeaks()
304 shouldIgnoreLeaks = false;
308 Node::StyleChange Node::diff(const RenderStyle* s1, const RenderStyle* s2)
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);
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();
324 if (display1 != display2 || fl1 != fl2 || colSpan1 != colSpan2 || (s1 && s2 && !s1->contentDataEquivalent(s2)))
330 else if (s1->inheritedNotEqual(s2))
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())
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);
348 RenderStyle* ps1 = s1->getCachedPseudoStyle(pseudoId);
349 ch = ps1 && *ps1 == *ps2 ? NoChange : NoInherit;
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()))
361 // We need to reattach the node, so that it is moved to the correct RenderFlowThread.
362 if ((s1 && s2) && (s1->flowThread() != s2->flowThread()))
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()))))
373 void Node::trackForDebugging()
376 if (shouldIgnoreLeaks)
379 nodeCounter.increment();
382 #if DUMP_NODE_STATISTICS
383 liveNodeSet.add(this);
390 HashSet<Node*>::iterator it = ignoreSet.find(this);
391 if (it != ignoreSet.end())
392 ignoreSet.remove(it);
394 nodeCounter.decrement();
397 #if DUMP_NODE_STATISTICS
398 liveNodeSet.remove(this);
401 ASSERT(hasRareData() == NodeRareData::rareDataMap().contains(this));
408 if (AXObjectCache::accessibilityEnabled() && m_document && m_document->axObjectCacheExists())
409 m_document->axObjectCache()->removeNodeForUse(this);
412 m_previous->setNextSibling(0);
414 m_next->setPreviousSibling(0);
417 m_document->guardDeref();
422 static inline void setWillMoveToNewOwnerDocumentWasCalled(bool)
426 static inline void setDidMoveToNewOwnerDocumentWasCalled(bool)
432 static bool willMoveToNewOwnerDocumentWasCalled;
433 static bool didMoveToNewOwnerDocumentWasCalled;
435 static void setWillMoveToNewOwnerDocumentWasCalled(bool wasCalled)
437 willMoveToNewOwnerDocumentWasCalled = wasCalled;
440 static void setDidMoveToNewOwnerDocumentWasCalled(bool wasCalled)
442 didMoveToNewOwnerDocumentWasCalled = wasCalled;
447 void Node::setDocument(Document* document)
449 ASSERT(!inDocument() || m_document == document);
450 if (inDocument() || m_document == document)
453 document->guardRef();
455 setWillMoveToNewOwnerDocumentWasCalled(false);
456 willMoveToNewOwnerDocument();
457 ASSERT(willMoveToNewOwnerDocumentWasCalled);
460 m_document->moveNodeIteratorsToNewDocument(this, document);
461 m_document->guardDeref();
464 m_document = document;
466 setDidMoveToNewOwnerDocumentWasCalled(false);
467 didMoveToNewOwnerDocument();
468 ASSERT(didMoveToNewOwnerDocumentWasCalled);
471 TreeScope* Node::treeScope() const
473 // FIXME: Using m_document directly is not good -> see comment with document() in the header file.
476 TreeScope* scope = rareData()->treeScope();
477 return scope ? scope : m_document;
480 void Node::setTreeScopeRecursively(TreeScope* newTreeScope, bool includeRoot)
483 ASSERT(!includeRoot || !isDocumentNode());
484 ASSERT(newTreeScope);
485 ASSERT(!m_deletionHasBegun);
487 TreeScope* currentTreeScope = treeScope();
488 if (currentTreeScope == newTreeScope)
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();
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.
507 node->ensureRareData()->setTreeScope(newTreeScope);
509 if (node->hasRareData() && node->rareData()->nodeLists()) {
510 if (currentTreeScope)
511 currentTreeScope->removeNodeListCache();
512 newTreeScope->addNodeListCache();
515 node->setDocument(newDocument);
517 if (!node->isElementNode())
519 if (ShadowRoot* shadowRoot = toElement(node)->shadowRoot()) {
520 shadowRoot->setParentTreeScope(newTreeScope);
521 if (currentDocument != newDocument)
522 shadowRoot->setDocumentRecursively(newDocument);
527 NodeRareData* Node::rareData() const
529 ASSERT(hasRareData());
530 return NodeRareData::rareDataFromMap(this);
533 NodeRareData* Node::ensureRareData()
538 ASSERT(!NodeRareData::rareDataMap().contains(this));
539 NodeRareData* data = createRareData().leakPtr();
540 NodeRareData::rareDataMap().set(this, data);
541 setFlag(HasRareDataFlag);
545 OwnPtr<NodeRareData> Node::createRareData()
547 return adoptPtr(new NodeRareData);
550 void Node::clearRareData()
552 ASSERT(hasRareData());
553 if (treeScope() && rareData()->nodeLists())
554 treeScope()->removeNodeListCache();
556 NodeRareData::NodeRareDataMap& dataMap = NodeRareData::rareDataMap();
557 NodeRareData::NodeRareDataMap::iterator it = dataMap.find(this);
558 ASSERT(it != dataMap.end());
561 clearFlag(HasRareDataFlag);
564 Element* Node::shadowHost() const
566 return toElement(getFlag(IsShadowRootFlag) ? parent() : 0);
569 void Node::setShadowHost(Element* host)
571 ASSERT(!parentNode() && !isSVGShadowRoot());
573 setFlag(IsShadowRootFlag);
575 clearFlag(IsShadowRootFlag);
580 HTMLInputElement* Node::toInputElement()
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.
585 ASSERT(!(isHTMLElement() && hasTagName(inputTag)));
589 short Node::tabIndex() const
591 return hasRareData() ? rareData()->tabIndex() : 0;
594 void Node::setTabIndexExplicitly(short i)
596 ensureRareData()->setTabIndexExplicitly(i);
599 void Node::clearTabIndexExplicitly()
601 ensureRareData()->clearTabIndexExplicitly();
604 String Node::nodeValue() const
609 void Node::setNodeValue(const String& /*nodeValue*/, ExceptionCode& ec)
611 // NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly
612 if (isReadOnlyNode()) {
613 ec = NO_MODIFICATION_ALLOWED_ERR;
617 // By default, setting nodeValue has no effect.
620 PassRefPtr<NodeList> Node::childNodes()
622 NodeRareData* data = ensureRareData();
623 if (!data->nodeLists()) {
624 data->setNodeLists(NodeListsNodeData::create());
626 treeScope()->addNodeListCache();
629 if (!data->nodeLists()->m_childNodeListCaches)
630 data->nodeLists()->m_childNodeListCaches = DynamicNodeList::Caches::create();
631 return ChildNodeList::create(this, data->nodeLists()->m_childNodeListCaches.get());
634 Node *Node::lastDescendant() const
636 Node *n = const_cast<Node *>(this);
637 while (n && n->lastChild())
642 Node* Node::firstDescendant() const
644 Node *n = const_cast<Node *>(this);
645 while (n && n->firstChild())
650 bool Node::insertBefore(PassRefPtr<Node> newChild, Node* refChild, ExceptionCode& ec, bool shouldLazyAttach)
652 if (!isContainerNode()) {
653 ec = HIERARCHY_REQUEST_ERR;
656 return toContainerNode(this)->insertBefore(newChild, refChild, ec, shouldLazyAttach);
659 bool Node::replaceChild(PassRefPtr<Node> newChild, Node* oldChild, ExceptionCode& ec, bool shouldLazyAttach)
661 if (!isContainerNode()) {
662 ec = HIERARCHY_REQUEST_ERR;
665 return toContainerNode(this)->replaceChild(newChild, oldChild, ec, shouldLazyAttach);
668 bool Node::removeChild(Node* oldChild, ExceptionCode& ec)
670 if (!isContainerNode()) {
674 return toContainerNode(this)->removeChild(oldChild, ec);
677 bool Node::appendChild(PassRefPtr<Node> newChild, ExceptionCode& ec, bool shouldLazyAttach)
679 if (!isContainerNode()) {
680 ec = HIERARCHY_REQUEST_ERR;
683 return toContainerNode(this)->appendChild(newChild, ec, shouldLazyAttach);
686 void Node::remove(ExceptionCode& ec)
688 if (ContainerNode* parent = parentNode())
689 parent->removeChild(this, ec);
691 ec = HIERARCHY_REQUEST_ERR;
694 void Node::normalize()
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.
699 RefPtr<Node> node = this;
700 while (Node* firstChild = node->firstChild())
703 NodeType type = node->nodeType();
704 if (type == ELEMENT_NODE)
705 static_cast<Element*>(node.get())->normalizeAttributes();
710 if (type != TEXT_NODE) {
711 node = node->traverseNextNodePostOrder();
715 Text* text = static_cast<Text*>(node.get());
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();
727 while (Node* nextSibling = node->nextSibling()) {
728 if (nextSibling->nodeType() != TEXT_NODE)
730 RefPtr<Text> nextText = static_cast<Text*>(nextSibling);
732 // Remove empty text nodes.
733 if (!nextText->length()) {
735 nextText->remove(ec);
739 // Both non-empty text nodes. Merge them.
740 unsigned offset = text->length();
742 text->appendData(nextText->data(), ec);
743 document()->textNodesMerged(nextText.get(), offset);
744 nextText->remove(ec);
747 node = node->traverseNextNodePostOrder();
751 const AtomicString& Node::virtualPrefix() const
753 // For nodes other than elements and attributes, the prefix is always null
757 void Node::setPrefix(const AtomicString& /*prefix*/, ExceptionCode& ec)
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.
765 const AtomicString& Node::virtualLocalName() const
770 const AtomicString& Node::virtualNamespaceURI() const
775 bool Node::isContentEditable()
777 document()->updateLayoutIgnorePendingStylesheets();
778 return rendererIsEditable(Editable);
781 bool Node::rendererIsEditable(EditableLevel editableLevel) const
783 if (document()->frame() && document()->frame()->page() && document()->frame()->page()->isEditable() && !shadowTreeRootNode())
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().
790 for (const Node* node = this; node; node = node->parentNode()) {
791 if ((node->isHTMLElement() || node->isDocumentNode()) && node->renderer()) {
792 switch (node->renderer()->style()->userModify()) {
797 case READ_WRITE_PLAINTEXT_ONLY:
798 return editableLevel != RichlyEditable;
800 ASSERT_NOT_REACHED();
808 bool Node::shouldUseInputMethod()
810 return isContentEditable();
813 RenderBox* Node::renderBox() const
815 return m_renderer && m_renderer->isBox() ? toRenderBox(m_renderer) : 0;
818 RenderBoxModelObject* Node::renderBoxModelObject() const
820 return m_renderer && m_renderer->isBoxModelObject() ? toRenderBoxModelObject(m_renderer) : 0;
823 LayoutRect Node::getRect() const
826 return renderer()->absoluteBoundingBoxRect(true);
830 LayoutRect Node::renderRect(bool* isReplaced)
832 RenderObject* hitRenderer = this->renderer();
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);
840 renderer = renderer->parent();
845 bool Node::hasNonEmptyBoundingBox() const
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();
852 if (!box->borderBoundingBox().isEmpty())
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())
866 inline static ShadowRoot* shadowRoot(Node* node)
868 return node->isElementNode() ? toElement(node)->shadowRoot() : 0;
871 void Node::setDocumentRecursively(Document* newDocument)
873 ASSERT(document() != newDocument);
875 for (Node* node = this; node; node = node->traverseNextNode(this)) {
876 node->setDocument(newDocument);
877 if (!node->isElementNode())
879 if (ShadowRoot* shadow = shadowRoot(node))
880 shadow->setDocumentRecursively(newDocument);
884 inline void Node::setStyleChange(StyleChangeType changeType)
886 m_nodeFlags = (m_nodeFlags & ~StyleChangeMask) | changeType;
889 inline void Node::markAncestorsWithChildNeedsStyleRecalc()
891 for (ContainerNode* p = parentOrHostNode(); p && !p->childNeedsStyleRecalc(); p = p->parentOrHostNode())
892 p->setChildNeedsStyleRecalc();
894 if (document()->childNeedsStyleRecalc())
895 document()->scheduleStyleRecalc();
898 void Node::refEventTarget()
903 void Node::derefEventTarget()
908 void Node::setNeedsStyleRecalc(StyleChangeType changeType)
910 ASSERT(changeType != NoStyleChange);
911 if (!attached()) // changed compared to what?
914 StyleChangeType existingChangeType = styleChangeType();
915 if (changeType > existingChangeType)
916 setStyleChange(changeType);
918 if (existingChangeType == NoStyleChange)
919 markAncestorsWithChildNeedsStyleRecalc();
922 void Node::lazyAttach(ShouldSetAttached shouldSetAttached)
924 for (Node* n = this; n; n = n->traverseNextNode(this)) {
926 n->setChildNeedsStyleRecalc();
927 n->setStyleChange(FullStyleChange);
928 if (shouldSetAttached == SetAttached)
931 markAncestorsWithChildNeedsStyleRecalc();
934 void Node::setFocus(bool b)
936 if (b || hasRareData())
937 ensureRareData()->setFocused(b);
940 bool Node::rareDataFocused() const
942 ASSERT(hasRareData());
943 return rareData()->isFocused();
946 bool Node::supportsFocus() const
948 return hasRareData() && rareData()->tabIndexSetExplicitly();
951 bool Node::isFocusable() const
953 if (!inDocument() || !supportsFocus())
957 ASSERT(!renderer()->needsLayout());
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());
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)
971 bool Node::isKeyboardFocusable(KeyboardEvent*) const
973 return isFocusable() && tabIndex() >= 0;
976 bool Node::isMouseFocusable() const
978 return isFocusable();
981 Node* Node::focusDelegate()
986 unsigned Node::nodeIndex() const
988 Node *_tempNode = previousSibling();
990 for ( count=0; _tempNode; count++ )
991 _tempNode = _tempNode->previousSibling();
995 void Node::registerDynamicNodeList(DynamicNodeList* list)
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();
1006 if (list->hasOwnCaches())
1007 data->nodeLists()->m_listsWithCaches.add(list);
1010 void Node::unregisterDynamicNodeList(DynamicNodeList* list)
1013 ASSERT(rareData()->nodeLists());
1014 if (list->hasOwnCaches()) {
1015 NodeRareData* data = rareData();
1016 data->nodeLists()->m_listsWithCaches.remove(list);
1017 removeNodeListCacheIfPossible();
1021 inline void Node::notifyLocalNodeListsAttributeChanged()
1025 NodeRareData* data = rareData();
1026 if (!data->nodeLists())
1029 if (!isAttributeNode())
1030 data->nodeLists()->invalidateCachesThatDependOnAttributes();
1032 data->nodeLists()->invalidateCaches();
1034 removeNodeListCacheIfPossible();
1037 void Node::notifyNodeListsAttributeChanged()
1039 for (Node *n = this; n; n = n->parentNode())
1040 n->notifyLocalNodeListsAttributeChanged();
1043 inline void Node::notifyLocalNodeListsChildrenChanged()
1047 NodeRareData* data = rareData();
1048 if (!data->nodeLists())
1051 data->nodeLists()->invalidateCaches();
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();
1057 removeNodeListCacheIfPossible();
1060 void Node::removeNodeListCacheIfPossible()
1062 ASSERT(rareData()->nodeLists());
1064 NodeRareData* data = rareData();
1065 if (!data->nodeLists()->isEmpty())
1067 data->clearNodeLists();
1068 treeScope()->removeNodeListCache();
1071 void Node::notifyNodeListsChildrenChanged()
1073 for (Node* n = this; n; n = n->parentNode())
1074 n->notifyLocalNodeListsChildrenChanged();
1077 void Node::notifyLocalNodeListsLabelChanged()
1081 NodeRareData* data = rareData();
1082 if (!data->nodeLists())
1085 if (data->nodeLists()->m_labelsNodeListCache)
1086 data->nodeLists()->m_labelsNodeListCache->invalidateCache();
1089 void Node::removeCachedClassNodeList(ClassNodeList* list, const String& className)
1092 ASSERT(rareData()->nodeLists());
1093 ASSERT_UNUSED(list, list->hasOwnCaches());
1095 NodeListsNodeData* data = rareData()->nodeLists();
1096 ASSERT_UNUSED(list, list == data->m_classNodeListCache.get(className));
1097 data->m_classNodeListCache.remove(className);
1100 void Node::removeCachedNameNodeList(NameNodeList* list, const String& nodeName)
1103 ASSERT(rareData()->nodeLists());
1104 ASSERT_UNUSED(list, list->hasOwnCaches());
1106 NodeListsNodeData* data = rareData()->nodeLists();
1107 ASSERT_UNUSED(list, list == data->m_nameNodeListCache.get(nodeName));
1108 data->m_nameNodeListCache.remove(nodeName);
1111 void Node::removeCachedTagNodeList(TagNodeList* list, const AtomicString& name)
1114 ASSERT(rareData()->nodeLists());
1115 ASSERT_UNUSED(list, list->hasOwnCaches());
1117 NodeListsNodeData* data = rareData()->nodeLists();
1118 ASSERT_UNUSED(list, list == data->m_tagNodeListCache.get(name.impl()));
1119 data->m_tagNodeListCache.remove(name.impl());
1122 void Node::removeCachedTagNodeList(TagNodeList* list, const QualifiedName& name)
1125 ASSERT(rareData()->nodeLists());
1126 ASSERT_UNUSED(list, list->hasOwnCaches());
1128 NodeListsNodeData* data = rareData()->nodeLists();
1129 ASSERT_UNUSED(list, list == data->m_tagNodeListCacheNS.get(name.impl()));
1130 data->m_tagNodeListCacheNS.remove(name.impl());
1133 void Node::removeCachedLabelsNodeList(DynamicNodeList* list)
1136 ASSERT(rareData()->nodeLists());
1137 ASSERT_UNUSED(list, list->hasOwnCaches());
1139 NodeListsNodeData* data = rareData()->nodeLists();
1140 data->m_labelsNodeListCache = 0;
1143 Node* Node::traverseNextNode(const Node* stayWithin) const
1146 return firstChild();
1147 if (this == stayWithin)
1150 return nextSibling();
1151 const Node *n = this;
1152 while (n && !n->nextSibling() && (!stayWithin || n->parentNode() != stayWithin))
1153 n = n->parentNode();
1155 return n->nextSibling();
1159 Node* Node::traverseNextSibling(const Node* stayWithin) const
1161 if (this == stayWithin)
1164 return nextSibling();
1165 const Node *n = this;
1166 while (n && !n->nextSibling() && (!stayWithin || n->parentNode() != stayWithin))
1167 n = n->parentNode();
1169 return n->nextSibling();
1173 Node* Node::traverseNextNodePostOrder() const
1175 Node* next = nextSibling();
1177 return parentNode();
1178 while (Node* firstChild = next->firstChild())
1183 Node* Node::traversePreviousNode(const Node* stayWithin) const
1185 if (this == stayWithin)
1187 if (previousSibling()) {
1188 Node *n = previousSibling();
1189 while (n->lastChild())
1193 return parentNode();
1196 Node* Node::traversePreviousNodePostOrder(const Node* stayWithin) const
1200 if (this == stayWithin)
1202 if (previousSibling())
1203 return previousSibling();
1204 const Node *n = this;
1205 while (n && !n->previousSibling() && (!stayWithin || n->parentNode() != stayWithin))
1206 n = n->parentNode();
1208 return n->previousSibling();
1212 Node* Node::traversePreviousSiblingPostOrder(const Node* stayWithin) const
1214 if (this == stayWithin)
1216 if (previousSibling())
1217 return previousSibling();
1218 const Node *n = this;
1219 while (n && !n->previousSibling() && (!stayWithin || n->parentNode() != stayWithin))
1220 n = n->parentNode();
1222 return n->previousSibling();
1226 void Node::checkSetPrefix(const AtomicString& prefix, ExceptionCode& ec)
1228 // Perform error checking as required by spec for setting Node.prefix. Used by
1229 // Element::setPrefix() and Attr::setPrefix()
1231 // FIXME: Implement support for INVALID_CHARACTER_ERR: Raised if the specified prefix contains an illegal character.
1233 if (isReadOnlyNode()) {
1234 ec = NO_MODIFICATION_ALLOWED_ERR;
1238 // FIXME: Raise NAMESPACE_ERR if prefix is malformed per the Namespaces in XML specification.
1240 const AtomicString& nodeNamespaceURI = namespaceURI();
1241 if ((nodeNamespaceURI.isEmpty() && !prefix.isEmpty())
1242 || (prefix == xmlAtom && nodeNamespaceURI != XMLNames::xmlNamespaceURI)) {
1246 // Attribute-specific checks are in Attr::setPrefix().
1249 static bool isChildTypeAllowed(Node* newParent, Node* child)
1251 if (child->nodeType() != Node::DOCUMENT_FRAGMENT_NODE) {
1252 if (!newParent->childTypeAllowed(child->nodeType()))
1257 for (Node *n = child->firstChild(); n; n = n->nextSibling()) {
1258 if (!newParent->childTypeAllowed(n->nodeType()))
1264 bool Node::canReplaceChild(Node* newChild, Node*)
1266 return isChildTypeAllowed(this, newChild);
1269 static void checkAcceptChild(Node* newParent, Node* newChild, ExceptionCode& ec)
1271 // Not mentioned in spec: throw NOT_FOUND_ERR if newChild is null
1277 if (newParent->isReadOnlyNode()) {
1278 ec = NO_MODIFICATION_ALLOWED_ERR;
1282 if (newChild->inDocument() && newChild->nodeType() == Node::DOCUMENT_TYPE_NODE) {
1283 ec = HIERARCHY_REQUEST_ERR;
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.
1290 if (newChild == newParent || newParent->isDescendantOf(newChild)) {
1291 ec = HIERARCHY_REQUEST_ERR;
1296 void Node::checkReplaceChild(Node* newChild, Node* oldChild, ExceptionCode& ec)
1303 checkAcceptChild(this, newChild, ec);
1307 if (!canReplaceChild(newChild, oldChild)) {
1308 ec = HIERARCHY_REQUEST_ERR;
1313 void Node::checkAddChild(Node *newChild, ExceptionCode& ec)
1315 checkAcceptChild(this, newChild, ec);
1319 if (!isChildTypeAllowed(this, newChild)) {
1320 ec = HIERARCHY_REQUEST_ERR;
1325 bool Node::isDescendantOf(const Node *other) const
1327 // Return true if other is an ancestor of this, otherwise false
1330 for (const ContainerNode* n = parentNode(); n; n = n->parentNode()) {
1337 bool Node::contains(const Node* node) const
1341 if (document() == this)
1342 return node->document() == this && node->inDocument();
1343 return this == node || node->isDescendantOf(this);
1346 bool Node::containsIncludingShadowDOM(Node* node)
1350 for (Node* n = node; n; n = n->parentOrHostNode()) {
1359 ASSERT(!attached());
1360 ASSERT(!renderer() || (renderer()->style() && renderer()->parent()));
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.
1366 for (Node* next = nextSibling(); next; next = next->nextSibling()) {
1367 if (next->renderer())
1369 if (!next->attached())
1370 break; // Assume this means none of the following siblings are attached.
1371 if (next->isTextNode())
1372 next->createRendererIfNeeded();
1377 clearNeedsStyleRecalc();
1380 void Node::willRemove()
1386 setFlag(InDetachFlag);
1389 renderer()->destroy();
1392 Document* doc = document();
1394 doc->hoveredNodeDetached(this);
1395 if (inActiveChain())
1396 doc->activeChainNodeDetached(this);
1398 clearFlag(IsActiveFlag);
1399 clearFlag(IsHoveredFlag);
1400 clearFlag(InActiveChainFlag);
1401 clearFlag(IsAttachedFlag);
1403 clearFlag(InDetachFlag);
1406 // FIXME: This code is used by editing. Seems like it could move over there and not pollute Node.
1407 Node *Node::previousNodeConsideringAtomicNodes() const
1409 if (previousSibling()) {
1410 Node *n = previousSibling();
1411 while (!isAtomicNode(n) && n->lastChild())
1415 else if (parentNode()) {
1416 return parentNode();
1423 Node *Node::nextNodeConsideringAtomicNodes() const
1425 if (!isAtomicNode(this) && firstChild())
1426 return firstChild();
1428 return nextSibling();
1429 const Node *n = this;
1430 while (n && !n->nextSibling())
1431 n = n->parentNode();
1433 return n->nextSibling();
1437 Node *Node::previousLeafNode() const
1439 Node *node = previousNodeConsideringAtomicNodes();
1441 if (isAtomicNode(node))
1443 node = node->previousNodeConsideringAtomicNodes();
1448 Node *Node::nextLeafNode() const
1450 Node *node = nextNodeConsideringAtomicNodes();
1452 if (isAtomicNode(node))
1454 node = node->nextNodeConsideringAtomicNodes();
1459 ContainerNode* Node::parentNodeForRenderingAndStyle()
1461 return NodeRenderingContext(this).parentNodeForRenderingAndStyle();
1464 void Node::createRendererIfNeeded()
1466 NodeRendererFactory(this).createRendererIfNeeded();
1469 bool Node::rendererIsNeeded(const NodeRenderingContext& context)
1471 return (document()->documentElement() == this) || (context.style()->display() != NONE);
1474 RenderObject* Node::createRenderer(RenderArena*, RenderStyle*)
1480 RenderStyle* Node::nonRendererRenderStyle() const
1485 void Node::setRenderStyle(PassRefPtr<RenderStyle> s)
1488 m_renderer->setAnimatableStyle(s);
1491 RenderStyle* Node::virtualComputedStyle(PseudoId pseudoElementSpecifier)
1493 return parentOrHostNode() ? parentOrHostNode()->computedStyle(pseudoElementSpecifier) : 0;
1496 int Node::maxCharacterOffset() const
1498 ASSERT_NOT_REACHED();
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
1506 if (rendererIsEditable())
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)
1516 return parentOrHostNode() ? parentOrHostNode()->canStartSelection() : true;
1520 SVGUseElement* Node::svgShadowHost() const
1522 return isSVGShadowRoot() ? static_cast<SVGUseElement*>(parent()) : 0;
1526 Node* Node::shadowAncestorNode() const
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?)
1534 return const_cast<Node*>(this);
1537 Node* root = shadowTreeRootNode();
1539 return root->shadowHost();
1540 return const_cast<Node*>(this);
1543 Node* Node::shadowTreeRootNode() const
1545 Node* root = const_cast<Node*>(this);
1547 if (root->isShadowRoot() || root->isSVGShadowRoot())
1549 root = root->parentNodeGuaranteedHostFree();
1554 Node* Node::nonBoundaryShadowTreeRootNode()
1556 ASSERT(!isShadowRoot());
1559 if (root->isShadowRoot() || root->isSVGShadowRoot())
1561 Node* parent = root->parentNodeGuaranteedHostFree();
1562 if (parent && parent->isShadowRoot())
1569 ContainerNode* Node::nonShadowBoundaryParentNode() const
1571 ContainerNode* parent = parentNode();
1572 return parent && !parent->isShadowRoot() ? parent : 0;
1575 bool Node::isInShadowTree()
1577 for (Node* n = this; n; n = n->parentNode())
1578 if (n->isShadowRoot())
1583 Element* Node::parentOrHostElement() const
1585 ContainerNode* parent = parentOrHostNode();
1589 if (parent->isShadowRoot())
1590 parent = parent->shadowHost();
1592 if (!parent->isElementNode())
1595 return toElement(parent);
1599 bool Node::isBlockFlow() const
1601 return renderer() && renderer()->isBlockFlow();
1604 bool Node::isBlockFlowOrBlockTable() const
1606 return renderer() && (renderer()->isBlockFlow() || (renderer()->isTable() && !renderer()->isInline()));
1609 Element *Node::enclosingBlockFlowElement() const
1611 Node *n = const_cast<Node *>(this);
1613 return static_cast<Element *>(n);
1616 n = n->parentNode();
1619 if (n->isBlockFlow() || n->hasTagName(bodyTag))
1620 return static_cast<Element *>(n);
1625 Element* Node::rootEditableElement() const
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))
1637 bool Node::inSameContainingBlockFlowElement(Node *n)
1639 return n ? enclosingBlockFlowElement() == n->enclosingBlockFlowElement() : false;
1642 // FIXME: End of obviously misplaced HTML editing functions. Try to move these out of Node.
1644 PassRefPtr<NodeList> Node::getElementsByTagName(const AtomicString& localName)
1646 if (localName.isNull())
1649 NodeRareData* data = ensureRareData();
1650 if (!data->nodeLists()) {
1651 data->setNodeLists(NodeListsNodeData::create());
1652 treeScope()->addNodeListCache();
1655 String name = localName;
1656 if (document()->isHTMLDocument())
1657 name = localName.lower();
1659 AtomicString localNameAtom = name;
1661 pair<NodeListsNodeData::TagNodeListCache::iterator, bool> result = data->nodeLists()->m_tagNodeListCache.add(localNameAtom, 0);
1663 return PassRefPtr<TagNodeList>(result.first->second);
1665 RefPtr<TagNodeList> list = TagNodeList::create(this, starAtom, localNameAtom);
1666 result.first->second = list.get();
1667 return list.release();
1670 PassRefPtr<NodeList> Node::getElementsByTagNameNS(const AtomicString& namespaceURI, const AtomicString& localName)
1672 if (localName.isNull())
1675 if (namespaceURI == starAtom)
1676 return getElementsByTagName(localName);
1678 NodeRareData* data = ensureRareData();
1679 if (!data->nodeLists()) {
1680 data->setNodeLists(NodeListsNodeData::create());
1681 treeScope()->addNodeListCache();
1684 String name = localName;
1685 if (document()->isHTMLDocument())
1686 name = localName.lower();
1688 AtomicString localNameAtom = name;
1690 pair<NodeListsNodeData::TagNodeListCacheNS::iterator, bool> result = data->nodeLists()->m_tagNodeListCacheNS.add(QualifiedName(nullAtom, localNameAtom, namespaceURI).impl(), 0);
1692 return PassRefPtr<TagNodeList>(result.first->second);
1694 RefPtr<TagNodeList> list = TagNodeList::create(this, namespaceURI.isEmpty() ? nullAtom : namespaceURI, localNameAtom);
1695 result.first->second = list.get();
1696 return list.release();
1699 PassRefPtr<NodeList> Node::getElementsByName(const String& elementName)
1701 NodeRareData* data = ensureRareData();
1702 if (!data->nodeLists()) {
1703 data->setNodeLists(NodeListsNodeData::create());
1704 treeScope()->addNodeListCache();
1707 pair<NodeListsNodeData::NameNodeListCache::iterator, bool> result = data->nodeLists()->m_nameNodeListCache.add(elementName, 0);
1709 return PassRefPtr<NodeList>(result.first->second);
1711 RefPtr<NameNodeList> list = NameNodeList::create(this, elementName);
1712 result.first->second = list.get();
1713 return list.release();
1716 PassRefPtr<NodeList> Node::getElementsByClassName(const String& classNames)
1718 NodeRareData* data = ensureRareData();
1719 if (!data->nodeLists()) {
1720 data->setNodeLists(NodeListsNodeData::create());
1721 treeScope()->addNodeListCache();
1724 pair<NodeListsNodeData::ClassNodeListCache::iterator, bool> result = data->nodeLists()->m_classNodeListCache.add(classNames, 0);
1726 return PassRefPtr<NodeList>(result.first->second);
1728 RefPtr<ClassNodeList> list = ClassNodeList::create(this, classNames);
1729 result.first->second = list.get();
1730 return list.release();
1733 PassRefPtr<Element> Node::querySelector(const String& selectors, ExceptionCode& ec)
1735 if (selectors.isEmpty()) {
1739 bool strictParsing = !document()->inQuirksMode();
1740 CSSParser p(strictParsing);
1742 CSSSelectorList querySelectorList;
1743 p.parseSelector(selectors, document(), querySelectorList);
1745 if (!querySelectorList.first() || querySelectorList.hasUnknownPseudoElements()) {
1750 // throw a NAMESPACE_ERR if the selector includes any namespace prefixes.
1751 if (querySelectorList.selectorsNeedNamespaceResolution()) {
1756 SelectorQuery selectorQuery(this, querySelectorList);
1757 return selectorQuery.queryFirst();
1760 PassRefPtr<NodeList> Node::querySelectorAll(const String& selectors, ExceptionCode& ec)
1762 if (selectors.isEmpty()) {
1766 bool strictParsing = !document()->inQuirksMode();
1767 CSSParser p(strictParsing);
1769 CSSSelectorList querySelectorList;
1770 p.parseSelector(selectors, document(), querySelectorList);
1772 if (!querySelectorList.first() || querySelectorList.hasUnknownPseudoElements()) {
1777 // Throw a NAMESPACE_ERR if the selector includes any namespace prefixes.
1778 if (querySelectorList.selectorsNeedNamespaceResolution()) {
1783 SelectorQuery selectorQuery(this, querySelectorList);
1784 return selectorQuery.queryAll();
1787 Document *Node::ownerDocument() const
1789 Document *doc = document();
1790 return doc == this ? 0 : doc;
1793 KURL Node::baseURI() const
1795 return parentNode() ? parentNode()->baseURI() : KURL();
1798 bool Node::isEqualNode(Node* other) const
1803 NodeType nodeType = this->nodeType();
1804 if (nodeType != other->nodeType())
1807 if (nodeName() != other->nodeName())
1810 if (localName() != other->localName())
1813 if (namespaceURI() != other->namespaceURI())
1816 if (prefix() != other->prefix())
1819 if (nodeValue() != other->nodeValue())
1822 NamedNodeMap* attributes = this->attributes();
1823 NamedNodeMap* otherAttributes = other->attributes();
1825 if (!attributes && otherAttributes)
1828 if (attributes && !attributes->mapsEquivalent(otherAttributes))
1831 Node* child = firstChild();
1832 Node* otherChild = other->firstChild();
1835 if (!child->isEqualNode(otherChild))
1838 child = child->nextSibling();
1839 otherChild = otherChild->nextSibling();
1845 if (nodeType == DOCUMENT_TYPE_NODE) {
1846 const DocumentType* documentTypeThis = static_cast<const DocumentType*>(this);
1847 const DocumentType* documentTypeOther = static_cast<const DocumentType*>(other);
1849 if (documentTypeThis->publicId() != documentTypeOther->publicId())
1852 if (documentTypeThis->systemId() != documentTypeOther->systemId())
1855 if (documentTypeThis->internalSubset() != documentTypeOther->internalSubset())
1858 NamedNodeMap* entities = documentTypeThis->entities();
1859 NamedNodeMap* otherEntities = documentTypeOther->entities();
1860 if (!entities && otherEntities)
1862 if (entities && !entities->mapsEquivalent(otherEntities))
1865 NamedNodeMap* notations = documentTypeThis->notations();
1866 NamedNodeMap* otherNotations = documentTypeOther->notations();
1867 if (!notations && otherNotations)
1869 if (notations && !notations->mapsEquivalent(otherNotations))
1876 bool Node::isDefaultNamespace(const AtomicString& namespaceURIMaybeEmpty) const
1878 const AtomicString& namespaceURI = namespaceURIMaybeEmpty.isEmpty() ? nullAtom : namespaceURIMaybeEmpty;
1880 switch (nodeType()) {
1881 case ELEMENT_NODE: {
1882 const Element* elem = static_cast<const Element*>(this);
1884 if (elem->prefix().isNull())
1885 return elem->namespaceURI() == namespaceURI;
1887 if (elem->hasAttributes()) {
1888 NamedNodeMap* attrs = elem->attributes();
1890 for (unsigned i = 0; i < attrs->length(); i++) {
1891 Attribute* attr = attrs->attributeItem(i);
1893 if (attr->localName() == xmlnsAtom)
1894 return attr->value() == namespaceURI;
1898 if (Element* ancestor = ancestorElement())
1899 return ancestor->isDefaultNamespace(namespaceURI);
1904 if (Element* de = static_cast<const Document*>(this)->documentElement())
1905 return de->isDefaultNamespace(namespaceURI);
1909 case DOCUMENT_TYPE_NODE:
1910 case DOCUMENT_FRAGMENT_NODE:
1911 case SHADOW_ROOT_NODE:
1913 case ATTRIBUTE_NODE: {
1914 const Attr* attr = static_cast<const Attr*>(this);
1915 if (attr->ownerElement())
1916 return attr->ownerElement()->isDefaultNamespace(namespaceURI);
1920 if (Element* ancestor = ancestorElement())
1921 return ancestor->isDefaultNamespace(namespaceURI);
1926 String Node::lookupPrefix(const AtomicString &namespaceURI) const
1928 // Implemented according to
1929 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/namespaces-algorithms.html#lookupNamespacePrefixAlgo
1931 if (namespaceURI.isEmpty())
1934 switch (nodeType()) {
1936 return lookupNamespacePrefix(namespaceURI, static_cast<const Element *>(this));
1938 if (Element* de = static_cast<const Document*>(this)->documentElement())
1939 return de->lookupPrefix(namespaceURI);
1943 case DOCUMENT_FRAGMENT_NODE:
1944 case DOCUMENT_TYPE_NODE:
1945 case SHADOW_ROOT_NODE:
1947 case ATTRIBUTE_NODE: {
1948 const Attr *attr = static_cast<const Attr *>(this);
1949 if (attr->ownerElement())
1950 return attr->ownerElement()->lookupPrefix(namespaceURI);
1954 if (Element* ancestor = ancestorElement())
1955 return ancestor->lookupPrefix(namespaceURI);
1960 String Node::lookupNamespaceURI(const String &prefix) const
1962 // Implemented according to
1963 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/namespaces-algorithms.html#lookupNamespaceURIAlgo
1965 if (!prefix.isNull() && prefix.isEmpty())
1968 switch (nodeType()) {
1969 case ELEMENT_NODE: {
1970 const Element *elem = static_cast<const Element *>(this);
1972 if (!elem->namespaceURI().isNull() && elem->prefix() == prefix)
1973 return elem->namespaceURI();
1975 if (elem->hasAttributes()) {
1976 NamedNodeMap *attrs = elem->attributes();
1978 for (unsigned i = 0; i < attrs->length(); i++) {
1979 Attribute *attr = attrs->attributeItem(i);
1981 if (attr->prefix() == xmlnsAtom && attr->localName() == prefix) {
1982 if (!attr->value().isEmpty())
1983 return attr->value();
1986 } else if (attr->localName() == xmlnsAtom && prefix.isNull()) {
1987 if (!attr->value().isEmpty())
1988 return attr->value();
1994 if (Element* ancestor = ancestorElement())
1995 return ancestor->lookupNamespaceURI(prefix);
1999 if (Element* de = static_cast<const Document*>(this)->documentElement())
2000 return de->lookupNamespaceURI(prefix);
2004 case DOCUMENT_TYPE_NODE:
2005 case DOCUMENT_FRAGMENT_NODE:
2006 case SHADOW_ROOT_NODE:
2008 case ATTRIBUTE_NODE: {
2009 const Attr *attr = static_cast<const Attr *>(this);
2011 if (attr->ownerElement())
2012 return attr->ownerElement()->lookupNamespaceURI(prefix);
2017 if (Element* ancestor = ancestorElement())
2018 return ancestor->lookupNamespaceURI(prefix);
2023 String Node::lookupNamespacePrefix(const AtomicString &_namespaceURI, const Element *originalElement) const
2025 if (_namespaceURI.isNull())
2028 if (originalElement->lookupNamespaceURI(prefix()) == _namespaceURI)
2031 if (hasAttributes()) {
2032 NamedNodeMap *attrs = attributes();
2034 for (unsigned i = 0; i < attrs->length(); i++) {
2035 Attribute *attr = attrs->attributeItem(i);
2037 if (attr->prefix() == xmlnsAtom &&
2038 attr->value() == _namespaceURI &&
2039 originalElement->lookupNamespaceURI(attr->localName()) == _namespaceURI)
2040 return attr->localName();
2044 if (Element* ancestor = ancestorElement())
2045 return ancestor->lookupNamespacePrefix(_namespaceURI, originalElement);
2049 static void appendTextContent(const Node* node, bool convertBRsToNewlines, bool& isNullString, StringBuilder& content)
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());
2059 case Node::PROCESSING_INSTRUCTION_NODE:
2060 isNullString = false;
2061 content.append(static_cast<const ProcessingInstruction*>(node)->data());
2064 case Node::ELEMENT_NODE:
2065 if (node->hasTagName(brTag) && convertBRsToNewlines) {
2066 isNullString = false;
2067 content.append('\n');
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)
2080 appendTextContent(child, convertBRsToNewlines, isNullString, content);
2084 case Node::DOCUMENT_NODE:
2085 case Node::DOCUMENT_TYPE_NODE:
2086 case Node::NOTATION_NODE:
2087 case Node::XPATH_NAMESPACE_NODE:
2092 String Node::textContent(bool convertBRsToNewlines) const
2094 StringBuilder content;
2095 bool isNullString = true;
2096 appendTextContent(this, convertBRsToNewlines, isNullString, content);
2097 return isNullString ? String() : content.toString();
2100 void Node::setTextContent(const String& text, ExceptionCode& ec)
2102 switch (nodeType()) {
2104 case CDATA_SECTION_NODE:
2106 case PROCESSING_INSTRUCTION_NODE:
2107 setNodeValue(text, ec);
2110 case ATTRIBUTE_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);
2122 case DOCUMENT_TYPE_NODE:
2124 case XPATH_NAMESPACE_NODE:
2128 ASSERT_NOT_REACHED();
2131 Element* Node::ancestorElement() const
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);
2141 bool Node::offsetInCharacters() const
2146 unsigned short Node::compareDocumentPosition(Node* otherNode)
2148 // It is not clear what should be done if |otherNode| is 0.
2150 return DOCUMENT_POSITION_DISCONNECTED;
2152 if (otherNode == this)
2153 return DOCUMENT_POSITION_EQUIVALENT;
2155 Attr* attr1 = nodeType() == ATTRIBUTE_NODE ? static_cast<Attr*>(this) : 0;
2156 Attr* attr2 = otherNode->nodeType() == ATTRIBUTE_NODE ? static_cast<Attr*>(otherNode) : 0;
2158 Node* start1 = attr1 ? attr1->ownerElement() : this;
2159 Node* start2 = attr2 ? attr2->ownerElement() : otherNode;
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;
2166 Vector<Node*, 16> chain1;
2167 Vector<Node*, 16> chain2;
2169 chain1.append(attr1);
2171 chain2.append(attr2);
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;
2191 ASSERT_NOT_REACHED();
2192 return DOCUMENT_POSITION_DISCONNECTED;
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;
2202 // We need to find a common ancestor container, and then compare the indices of the two immediate children.
2204 for (current = start1; current; current = current->parentNode())
2205 chain1.append(current);
2206 for (current = start2; current; current = current->parentNode())
2207 chain2.append(current);
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;
2222 if (!child2->nextSibling())
2223 return DOCUMENT_POSITION_FOLLOWING;
2224 if (!child1->nextSibling())
2225 return DOCUMENT_POSITION_PRECEDING;
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;
2232 return DOCUMENT_POSITION_PRECEDING;
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;
2243 FloatPoint Node::convertToPage(const FloatPoint& p) const
2245 // If there is a renderer, just ask it to do the conversion
2247 return renderer()->localToAbsolute(p, false, true);
2249 // Otherwise go up the tree looking for a renderer
2250 Element *parent = ancestorElement();
2252 return parent->convertToPage(p);
2254 // No parent - no conversion needed
2258 FloatPoint Node::convertFromPage(const FloatPoint& p) const
2260 // If there is a renderer, just ask it to do the conversion
2262 return renderer()->absoluteToLocal(p, false, true);
2264 // Otherwise go up the tree looking for a renderer
2265 Element *parent = ancestorElement();
2267 return parent->convertFromPage(p);
2269 // No parent - no conversion needed
2275 static void appendAttributeDesc(const Node* node, String& string, const QualifiedName& name, const char* attrDesc)
2277 if (node->isElementNode()) {
2278 String attr = static_cast<const Element*>(node)->getAttribute(name);
2279 if (!attr.isEmpty()) {
2286 void Node::showNode(const char* prefix) const
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());
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());
2303 void Node::showTreeForThis() const
2305 showTreeAndMark(this, "*");
2308 static void traverseTreeAndMark(const String& baseIndent, const Node* rootNode, const Node* markedNode1, const char* markedLabel1, const Node* markedNode2, const char* markedLabel2)
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);
2316 String indent = baseIndent;
2317 for (const Node* tmpNode = node; tmpNode && tmpNode != rootNode; tmpNode = tmpNode->parentOrHostNode())
2319 fprintf(stderr, "%s", indent.utf8().data());
2322 ContainerNode* rootNode = shadowRoot(const_cast<Node*>(node));
2326 traverseTreeAndMark(indent, rootNode, markedNode1, markedLabel1, markedNode2, markedLabel2);
2331 void Node::showTreeAndMark(const Node* markedNode1, const char* markedLabel1, const Node* markedNode2, const char* markedLabel2) const
2333 const Node* rootNode;
2334 const Node* node = this;
2335 while (node->parentOrHostNode() && !node->hasTagName(bodyTag))
2336 node = node->parentOrHostNode();
2339 String startingIndent;
2340 traverseTreeAndMark(startingIndent, rootNode, markedNode1, markedLabel1, markedNode2, markedLabel2);
2343 void Node::formatForDebugger(char* buffer, unsigned length) const
2349 if (s.length() == 0)
2354 strncpy(buffer, result.utf8().data(), length - 1);
2357 static ContainerNode* parentOrHostOrFrameOwner(Node* node)
2359 ContainerNode* parent = node->parentOrHostNode();
2360 if (!parent && node->document() && node->document()->frame())
2361 parent = node->document()->frame()->ownerElement();
2365 static void showSubTreeAcrossFrame(Node* node, const Node* markedNode, const String& indent)
2367 if (node == markedNode)
2369 fputs(indent.utf8().data(), stderr);
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");
2379 void Node::showTreeForThisAcrossFrame() const
2381 Node* rootNode = const_cast<Node*>(this);
2382 while (parentOrHostOrFrameOwner(rootNode))
2383 rootNode = parentOrHostOrFrameOwner(rootNode);
2384 showSubTreeAcrossFrame(rootNode, this, "");
2391 void NodeListsNodeData::invalidateCaches()
2393 if (m_childNodeListCaches) {
2394 if (m_childNodeListCaches->hasOneRef())
2395 m_childNodeListCaches.clear();
2397 m_childNodeListCaches->reset();
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();
2411 void NodeListsNodeData::invalidateCachesThatDependOnAttributes()
2413 ClassNodeListCache::iterator classCacheEnd = m_classNodeListCache.end();
2414 for (ClassNodeListCache::iterator it = m_classNodeListCache.begin(); it != classCacheEnd; ++it)
2415 it->second->invalidateCache();
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();
2424 bool NodeListsNodeData::isEmpty() const
2426 if (!m_listsWithCaches.isEmpty())
2429 if (m_childNodeListCaches)
2432 if (!m_tagNodeListCache.isEmpty())
2434 if (!m_tagNodeListCacheNS.isEmpty())
2436 if (!m_classNodeListCache.isEmpty())
2438 if (!m_nameNodeListCache.isEmpty())
2441 if (m_labelsNodeListCache)
2447 void Node::getSubresourceURLs(ListHashSet<KURL>& urls) const
2449 addSubresourceAttributeURLs(urls);
2452 Node* Node::enclosingLinkEventParentOrSelf()
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
2458 if (node->isLink() && !node->hasTagName(imgTag))
2467 ScriptExecutionContext* Node::scriptExecutionContext() const
2472 void Node::insertedIntoDocument()
2477 void Node::removedFromDocument()
2482 void Node::willMoveToNewOwnerDocument()
2484 ASSERT(!willMoveToNewOwnerDocumentWasCalled);
2485 setWillMoveToNewOwnerDocumentWasCalled(true);
2488 void Node::didMoveToNewOwnerDocument()
2490 ASSERT(!didMoveToNewOwnerDocumentWasCalled);
2491 setDidMoveToNewOwnerDocumentWasCalled(true);
2495 static inline HashSet<SVGElementInstance*> instancesForSVGElement(Node* node)
2497 HashSet<SVGElementInstance*> instances;
2500 if (!node->isSVGElement() || node->shadowTreeRootNode())
2501 return HashSet<SVGElementInstance*>();
2503 SVGElement* element = static_cast<SVGElement*>(node);
2504 if (!element->isStyled())
2505 return HashSet<SVGElementInstance*>();
2507 SVGStyledElement* styledElement = static_cast<SVGStyledElement*>(element);
2508 ASSERT(!styledElement->instanceUpdatesBlocked());
2510 return styledElement->instancesForElement();
2514 static inline bool tryAddEventListener(Node* targetNode, const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
2516 if (!targetNode->EventTarget::addEventListener(eventType, listener, useCapture))
2519 if (Document* document = targetNode->document()) {
2520 document->addListenerTypeIfNeeded(eventType);
2521 if (eventType == eventNames().mousewheelEvent)
2522 document->didAddWheelEventHandler();
2528 bool Node::addEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
2531 return tryAddEventListener(this, eventType, listener, useCapture);
2533 if (!isSVGElement())
2534 return tryAddEventListener(this, eventType, listener, useCapture);
2536 HashSet<SVGElementInstance*> instances = instancesForSVGElement(this);
2537 if (instances.isEmpty())
2538 return tryAddEventListener(this, eventType, listener, useCapture);
2540 RefPtr<EventListener> listenerForRegularTree = listener;
2541 RefPtr<EventListener> listenerForShadowTree = listenerForRegularTree;
2543 // Add event listener to regular DOM element
2544 if (!tryAddEventListener(this, eventType, listenerForRegularTree.release(), useCapture))
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);
2553 RefPtr<EventListener> listenerForCurrentShadowTreeElement = listenerForShadowTree;
2554 bool result = tryAddEventListener((*it)->shadowTreeElement(), eventType, listenerForCurrentShadowTreeElement.release(), useCapture);
2555 ASSERT_UNUSED(result, result);
2562 static inline bool tryRemoveEventListener(Node* targetNode, const AtomicString& eventType, EventListener* listener, bool useCapture)
2564 if (!targetNode->EventTarget::removeEventListener(eventType, listener, useCapture))
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();
2577 bool Node::removeEventListener(const AtomicString& eventType, EventListener* listener, bool useCapture)
2580 return tryRemoveEventListener(this, eventType, listener, useCapture);
2582 if (!isSVGElement())
2583 return tryRemoveEventListener(this, eventType, listener, useCapture);
2585 HashSet<SVGElementInstance*> instances = instancesForSVGElement(this);
2586 if (instances.isEmpty())
2587 return tryRemoveEventListener(this, eventType, listener, useCapture);
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);
2596 // Remove event listener from regular DOM element
2597 if (!tryRemoveEventListener(this, eventType, listener, useCapture))
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);
2605 SVGElement* shadowTreeElement = (*it)->shadowTreeElement();
2606 ASSERT(shadowTreeElement);
2608 if (tryRemoveEventListener(shadowTreeElement, eventType, listener, useCapture))
2611 // This case can only be hit for event listeners created from markup
2612 ASSERT(listener->wasCreatedFromMarkup());
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();
2623 EventListenerMap::iterator result = data->eventListenerMap.find(eventType);
2624 ASSERT(result != data->eventListenerMap.end());
2626 EventListenerVector* entry = result->second;
2629 unsigned int index = 0;
2630 bool foundListener = false;
2632 EventListenerVector::iterator end = entry->end();
2633 for (EventListenerVector::iterator it = entry->begin(); it != end; ++it) {
2634 if (!(*it).listener->wasCreatedFromMarkup()) {
2639 foundListener = true;
2640 entry->remove(index);
2644 ASSERT_UNUSED(foundListener, foundListener);
2646 if (entry->isEmpty()) {
2648 data->eventListenerMap.remove(result);
2656 EventTargetData* Node::eventTargetData()
2658 return hasRareData() ? rareData()->eventTargetData() : 0;
2661 EventTargetData* Node::ensureEventTargetData()
2663 return ensureRareData()->ensureEventTargetData();
2666 void Node::handleLocalEvents(Event* event)
2668 if (!hasRareData() || !rareData()->eventTargetData())
2671 if (disabled() && event->isMouseEvent())
2674 fireEventListeners(event);
2677 void Node::dispatchScopedEvent(PassRefPtr<Event> event)
2679 dispatchScopedEventDispatchMediator(EventDispatchMediator::create(event));
2682 void Node::dispatchScopedEventDispatchMediator(PassRefPtr<EventDispatchMediator> eventDispatchMediator)
2684 EventDispatcher::dispatchScopedEvent(this, eventDispatchMediator);
2687 bool Node::dispatchEvent(PassRefPtr<Event> event)
2689 return EventDispatcher::dispatchEvent(this, EventDispatchMediator::create(event));
2692 void Node::dispatchSubtreeModifiedEvent()
2694 ASSERT(!eventDispatchForbidden());
2696 document()->incDOMTreeVersion();
2698 notifyNodeListsAttributeChanged(); // FIXME: Can do better some day. Really only care about the name attribute changing.
2700 if (!document()->hasListenerType(Document::DOMSUBTREEMODIFIED_LISTENER))
2703 dispatchScopedEvent(MutationEvent::create(eventNames().DOMSubtreeModifiedEvent, true));
2706 void Node::dispatchFocusInEvent(const AtomicString& eventType, PassRefPtr<Node> oldFocusedNode)
2708 ASSERT(!eventDispatchForbidden());
2709 ASSERT(eventType == eventNames().focusinEvent || eventType == eventNames().DOMFocusInEvent);
2710 dispatchScopedEventDispatchMediator(FocusInEventDispatchMediator::create(UIEvent::create(eventType, true, false, document()->defaultView(), 0), oldFocusedNode));
2713 void Node::dispatchFocusOutEvent(const AtomicString& eventType, PassRefPtr<Node> newFocusedNode)
2715 ASSERT(!eventDispatchForbidden());
2716 ASSERT(eventType == eventNames().focusoutEvent || eventType == eventNames().DOMFocusOutEvent);
2717 dispatchScopedEventDispatchMediator(FocusOutEventDispatchMediator::create(UIEvent::create(eventType, true, false, document()->defaultView(), 0), newFocusedNode));
2720 void Node::dispatchDOMActivateEvent(int detail, PassRefPtr<Event> underlyingEvent)
2722 ASSERT(!eventDispatchForbidden());
2723 RefPtr<UIEvent> event = UIEvent::create(eventNames().DOMActivateEvent, true, true, document()->defaultView(), detail);
2724 event->setUnderlyingEvent(underlyingEvent);
2725 dispatchScopedEvent(event.release());
2728 bool Node::dispatchKeyEvent(const PlatformKeyboardEvent& event)
2730 return EventDispatcher::dispatchEvent(this, KeyboardEventDispatchMediator::create(KeyboardEvent::create(event, document()->defaultView())));
2733 bool Node::dispatchMouseEvent(const PlatformMouseEvent& event, const AtomicString& eventType,
2734 int detail, Node* relatedTarget)
2736 return EventDispatcher::dispatchEvent(this, MouseEventDispatchMediator::create(MouseEvent::create(eventType, document()->defaultView(), event, detail, relatedTarget)));
2739 void Node::dispatchSimulatedClick(PassRefPtr<Event> event, bool sendMouseEvents, bool showPressedLook)
2741 EventDispatcher::dispatchSimulatedClick(this, event, sendMouseEvents, showPressedLook);
2744 bool Node::dispatchWheelEvent(const PlatformWheelEvent& event)
2746 return EventDispatcher::dispatchEvent(this, WheelEventDispatchMediator::create(event, document()->defaultView()));
2749 void Node::dispatchFocusEvent(PassRefPtr<Node> oldFocusedNode)
2751 if (document()->page())
2752 document()->page()->chrome()->client()->elementDidFocus(this);
2754 EventDispatcher::dispatchEvent(this, FocusEventDispatchMediator::create(oldFocusedNode));
2757 void Node::willBlur()
2761 void Node::dispatchBlurEvent(PassRefPtr<Node> newFocusedNode)
2763 if (document()->page())
2764 document()->page()->chrome()->client()->elementDidBlur(this);
2766 EventDispatcher::dispatchEvent(this, BlurEventDispatchMediator::create(newFocusedNode));
2769 void Node::dispatchChangeEvent()
2771 dispatchEvent(Event::create(eventNames().changeEvent, true, false));
2774 void Node::dispatchInputEvent()
2776 dispatchEvent(Event::create(eventNames().inputEvent, true, false));
2779 bool Node::disabled() const
2784 void Node::defaultEventHandler(Event* event)
2786 if (event->target() != this)
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);
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())
2813 RenderObject* renderer = this->renderer();
2814 while (renderer && (!renderer->isBox() || !toRenderBox(renderer)->canBeScrolledAndHasScrollableArea()))
2815 renderer = renderer->parent();
2818 if (Frame* frame = document()->frame())
2819 frame->eventHandler()->startPanScrolling(renderer);
2823 } else if (eventType == eventNames().mousewheelEvent && event->isWheelEvent()) {
2824 WheelEvent* wheelEvent = static_cast<WheelEvent*>(event);
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();
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();
2840 } // namespace WebCore
2844 void showTree(const WebCore::Node* node)
2847 node->showTreeForThis();