2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * (C) 1999 Antti Koivisto (koivisto@kde.org)
4 * (C) 2001 Dirk Mueller (mueller@kde.org)
5 * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
6 * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
7 * Copyright (C) 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
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"
31 #include "BeforeLoadEvent.h"
32 #include "ChildListMutationScope.h"
34 #include "ChromeClient.h"
35 #include "CSSParser.h"
37 #include "CSSSelector.h"
38 #include "CSSSelectorList.h"
39 #include "CSSStyleRule.h"
40 #include "CSSStyleSheet.h"
41 #include "ChildNodeList.h"
42 #include "ClassNodeList.h"
43 #include "ContextMenuController.h"
44 #include "DOMImplementation.h"
45 #include "DOMSettableTokenList.h"
47 #include "DocumentType.h"
48 #include "DynamicNodeList.h"
50 #include "ElementRareData.h"
51 #include "ElementShadow.h"
53 #include "EventContext.h"
54 #include "EventDispatchMediator.h"
55 #include "EventDispatcher.h"
56 #include "EventException.h"
57 #include "EventHandler.h"
58 #include "EventListener.h"
59 #include "EventNames.h"
60 #include "ExceptionCode.h"
62 #include "FrameView.h"
63 #include "HTMLElement.h"
64 #include "HTMLFrameOwnerElement.h"
65 #include "HTMLNames.h"
66 #include "InspectorCounters.h"
67 #include "KeyboardEvent.h"
68 #include "LabelsNodeList.h"
70 #include "MouseEvent.h"
71 #include "MutationEvent.h"
72 #include "NameNodeList.h"
73 #include "NamedNodeMap.h"
74 #include "NodeRareData.h"
75 #include "NodeRenderingContext.h"
77 #include "PlatformMouseEvent.h"
78 #include "PlatformWheelEvent.h"
79 #include "ProcessingInstruction.h"
80 #include "ProgressEvent.h"
81 #include "RadioNodeList.h"
82 #include "RegisteredEventListener.h"
83 #include "RenderBlock.h"
84 #include "RenderBox.h"
85 #include "RenderTextControl.h"
86 #include "RenderView.h"
87 #include "ScopedEventQueue.h"
88 #include "SelectorQuery.h"
90 #include "ShadowRoot.h"
91 #include "StaticNodeList.h"
92 #include "StorageEvent.h"
93 #include "StyleResolver.h"
94 #include "TagNodeList.h"
96 #include "TextEvent.h"
97 #include "TreeScopeAdopter.h"
99 #include "UIEventWithKeyState.h"
100 #include "WheelEvent.h"
101 #include "WindowEventContext.h"
102 #include "XMLNames.h"
103 #include "htmlediting.h"
104 #include <wtf/HashSet.h>
105 #include <wtf/PassOwnPtr.h>
106 #include <wtf/RefCountedLeakCounter.h>
107 #include <wtf/UnusedParam.h>
108 #include <wtf/Vector.h>
109 #include <wtf/text/CString.h>
110 #include <wtf/text/StringBuilder.h>
112 #if ENABLE(INSPECTOR)
113 #include "InspectorController.h"
117 #include <runtime/JSGlobalData.h>
120 #if ENABLE(MICRODATA)
121 #include "HTMLPropertiesCollection.h"
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 attributesWithAttr = 0;
163 size_t elementsWithAttributeStorage = 0;
164 size_t elementsWithRareData = 0;
165 size_t elementsWithNamedNodeMap = 0;
167 for (HashSet<Node*>::iterator it = liveNodeSet.begin(); it != liveNodeSet.end(); ++it) {
170 if (node->hasRareData()) {
172 if (node->isElementNode()) {
173 ++elementsWithRareData;
174 if (toElement(node)->hasNamedNodeMap())
175 ++elementsWithNamedNodeMap;
179 switch (node->nodeType()) {
184 Element* element = static_cast<Element*>(node);
185 HashMap<String, size_t>::AddResult result = perTagCount.add(element->tagName(), 1);
186 if (!result.isNewEntry)
187 result.iterator->second++;
189 if (ElementAttributeData* attributeData = element->attributeData()) {
190 attributes += attributeData->length();
191 ++elementsWithAttributeStorage;
192 for (unsigned i = 0; i < attributeData->length(); ++i) {
193 Attribute* attr = attributeData->attributeItem(i);
195 ++attributesWithAttr;
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: {
237 if (node->isShadowRoot())
243 case NOTATION_NODE: {
247 case XPATH_NAMESPACE_NODE: {
254 printf("Number of Nodes: %d\n\n", liveNodeSet.size());
255 printf("Number of Nodes with RareData: %zu\n\n", nodesWithRareData);
257 printf("NodeType distribution:\n");
258 printf(" Number of Element nodes: %zu\n", elementNodes);
259 printf(" Number of Attribute nodes: %zu\n", attrNodes);
260 printf(" Number of Text nodes: %zu\n", textNodes);
261 printf(" Number of CDATASection nodes: %zu\n", cdataNodes);
262 printf(" Number of Comment nodes: %zu\n", commentNodes);
263 printf(" Number of EntityReference nodes: %zu\n", entityReferenceNodes);
264 printf(" Number of Entity nodes: %zu\n", entityNodes);
265 printf(" Number of ProcessingInstruction nodes: %zu\n", piNodes);
266 printf(" Number of Document nodes: %zu\n", documentNodes);
267 printf(" Number of DocumentType nodes: %zu\n", docTypeNodes);
268 printf(" Number of DocumentFragment nodes: %zu\n", fragmentNodes);
269 printf(" Number of Notation nodes: %zu\n", notationNodes);
270 printf(" Number of XPathNS nodes: %zu\n", xpathNSNodes);
271 printf(" Number of ShadowRoot nodes: %zu\n", shadowRootNodes);
273 printf("Element tag name distibution:\n");
274 for (HashMap<String, size_t>::iterator it = perTagCount.begin(); it != perTagCount.end(); ++it)
275 printf(" Number of <%s> tags: %zu\n", it->first.utf8().data(), it->second);
277 printf("Attributes:\n");
278 printf(" Number of Attributes (non-Node and Node): %zu [%zu]\n", attributes, sizeof(Attribute));
279 printf(" Number of Attributes with an Attr: %zu\n", attributesWithAttr);
280 printf(" Number of Elements with attribute storage: %zu [%zu]\n", elementsWithAttributeStorage, sizeof(ElementAttributeData));
281 printf(" Number of Elements with RareData: %zu\n", elementsWithRareData);
282 printf(" Number of Elements with NamedNodeMap: %zu [%zu]\n", elementsWithNamedNodeMap, sizeof(NamedNodeMap));
286 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, nodeCounter, ("WebCoreNode"));
287 DEFINE_DEBUG_ONLY_GLOBAL(HashSet<Node*>, ignoreSet, );
290 static bool shouldIgnoreLeaks = false;
293 void Node::startIgnoringLeaks()
296 shouldIgnoreLeaks = true;
300 void Node::stopIgnoringLeaks()
303 shouldIgnoreLeaks = false;
307 Node::StyleChange Node::diff(const RenderStyle* s1, const RenderStyle* s2, Document* doc)
309 StyleChange ch = NoInherit;
310 EDisplay display1 = s1 ? s1->display() : NONE;
311 bool fl1 = s1 && s1->hasPseudoStyle(FIRST_LETTER);
312 EDisplay display2 = s2 ? s2->display() : NONE;
313 bool fl2 = s2 && s2->hasPseudoStyle(FIRST_LETTER);
315 // We just detach if a renderer acquires or loses a column-span, since spanning elements
316 // typically won't contain much content.
317 bool colSpan1 = s1 && s1->columnSpan();
318 bool colSpan2 = s2 && s2->columnSpan();
320 bool specifiesColumns1 = s1 && (!s1->hasAutoColumnCount() || !s1->hasAutoColumnWidth());
321 bool specifiesColumns2 = s2 && (!s2->hasAutoColumnCount() || !s2->hasAutoColumnWidth());
323 if (display1 != display2 || fl1 != fl2 || colSpan1 != colSpan2
324 || (specifiesColumns1 != specifiesColumns2 && doc->settings()->regionBasedColumnsEnabled())
325 || (s1 && s2 && !s1->contentDataEquivalent(s2)))
331 else if (s1->inheritedNotEqual(s2))
333 else if (s1->hasExplicitlyInheritedProperties() || s2->hasExplicitlyInheritedProperties())
336 // For nth-child and other positional rules, treat styles as different if they have
337 // changed positionally in the DOM. This way subsequent sibling resolutions won't be confused
338 // by the wrong child index and evaluate to incorrect results.
339 if (ch == NoChange && s1->childIndex() != s2->childIndex())
342 // If the pseudoStyles have changed, we want any StyleChange that is not NoChange
343 // because setStyle will do the right thing with anything else.
344 if (ch == NoChange && s1->hasAnyPublicPseudoStyles()) {
345 for (PseudoId pseudoId = FIRST_PUBLIC_PSEUDOID; ch == NoChange && pseudoId < FIRST_INTERNAL_PSEUDOID; pseudoId = static_cast<PseudoId>(pseudoId + 1)) {
346 if (s1->hasPseudoStyle(pseudoId)) {
347 RenderStyle* ps2 = s2->getCachedPseudoStyle(pseudoId);
351 RenderStyle* ps1 = s1->getCachedPseudoStyle(pseudoId);
352 ch = ps1 && *ps1 == *ps2 ? NoChange : NoInherit;
358 // When text-combine property has been changed, we need to prepare a separate renderer object.
359 // When text-combine is on, we use RenderCombineText, otherwise RenderText.
360 // https://bugs.webkit.org/show_bug.cgi?id=55069
361 if ((s1 && s2) && (s1->hasTextCombine() != s2->hasTextCombine()))
364 // We need to reattach the node, so that it is moved to the correct RenderFlowThread.
365 if ((s1 && s2) && (s1->flowThread() != s2->flowThread()))
368 // When the region thread has changed, we need to prepare a separate render region object.
369 if ((s1 && s2) && (s1->regionThread() != s2->regionThread()))
375 void Node::trackForDebugging()
378 if (shouldIgnoreLeaks)
381 nodeCounter.increment();
384 #if DUMP_NODE_STATISTICS
385 liveNodeSet.add(this);
392 HashSet<Node*>::iterator it = ignoreSet.find(this);
393 if (it != ignoreSet.end())
394 ignoreSet.remove(it);
396 nodeCounter.decrement();
399 #if DUMP_NODE_STATISTICS
400 liveNodeSet.remove(this);
409 Document* doc = m_document;
410 if (AXObjectCache::accessibilityEnabled() && doc && doc->axObjectCacheExists())
411 doc->axObjectCache()->removeNodeForUse(this);
414 m_previous->setNextSibling(0);
416 m_next->setPreviousSibling(0);
421 InspectorCounters::decrementCounter(InspectorCounters::NodeCounter);
424 void Node::setDocument(Document* document)
426 ASSERT(!inDocument() || m_document == document);
427 if (inDocument() || m_document == document)
430 m_document = document;
433 NodeRareData* Node::setTreeScope(TreeScope* scope)
437 NodeRareData* data = rareData();
438 data->setTreeScope(0);
445 NodeRareData* data = ensureRareData();
446 data->setTreeScope(scope);
450 TreeScope* Node::treeScope() const
452 // FIXME: Using m_document directly is not good -> see comment with document() in the header file.
455 TreeScope* scope = rareData()->treeScope();
456 return scope ? scope : m_document;
459 NodeRareData* Node::rareData() const
461 ASSERT(hasRareData());
462 NodeRareData* data = isDocumentNode() ? static_cast<const Document*>(this)->documentRareData() : NodeRareData::rareDataFromMap(this);
467 NodeRareData* Node::ensureRareData()
472 NodeRareData* data = createRareData().leakPtr();
473 if (isDocumentNode()) {
474 // Fast path for a Document. A Document knows a pointer to NodeRareData.
475 ASSERT(!static_cast<Document*>(this)->documentRareData());
476 static_cast<Document*>(this)->setDocumentRareData(data);
478 ASSERT(!NodeRareData::rareDataMap().contains(this));
479 NodeRareData::rareDataMap().set(this, data);
481 setFlag(HasRareDataFlag);
485 OwnPtr<NodeRareData> Node::createRareData()
487 return adoptPtr(new NodeRareData);
490 void Node::clearRareData()
492 ASSERT(hasRareData());
494 #if ENABLE(MUTATION_OBSERVERS)
495 ASSERT(!transientMutationObserverRegistry() || transientMutationObserverRegistry()->isEmpty());
498 if (isDocumentNode()) {
499 Document* document = static_cast<Document*>(this);
500 NodeRareData* data = document->documentRareData();
503 document->setDocumentRareData(0);
505 NodeRareData::NodeRareDataMap& dataMap = NodeRareData::rareDataMap();
506 NodeRareData::NodeRareDataMap::iterator it = dataMap.find(this);
507 ASSERT(it != dataMap.end());
511 clearFlag(HasRareDataFlag);
519 HTMLInputElement* Node::toInputElement()
521 // If one of the below ASSERTs trigger, you are calling this function
522 // directly or indirectly from a constructor or destructor of this object.
524 ASSERT(!(isHTMLElement() && hasTagName(inputTag)));
528 short Node::tabIndex() const
530 return hasRareData() ? rareData()->tabIndex() : 0;
533 void Node::setTabIndexExplicitly(short i)
535 ensureRareData()->setTabIndexExplicitly(i);
538 void Node::clearTabIndexExplicitly()
540 ensureRareData()->clearTabIndexExplicitly();
543 String Node::nodeValue() const
548 void Node::setNodeValue(const String& /*nodeValue*/, ExceptionCode& ec)
550 // NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly
551 if (isReadOnlyNode()) {
552 ec = NO_MODIFICATION_ALLOWED_ERR;
556 // By default, setting nodeValue has no effect.
559 PassRefPtr<NodeList> Node::childNodes()
561 NodeRareData* data = ensureRareData();
562 if (data->childNodeList())
563 return PassRefPtr<NodeList>(data->childNodeList());
565 RefPtr<ChildNodeList> list = ChildNodeList::create(this);
566 data->setChildNodeList(list.get());
567 return list.release();
570 Node *Node::lastDescendant() const
572 Node *n = const_cast<Node *>(this);
573 while (n && n->lastChild())
578 Node* Node::firstDescendant() const
580 Node *n = const_cast<Node *>(this);
581 while (n && n->firstChild())
586 bool Node::insertBefore(PassRefPtr<Node> newChild, Node* refChild, ExceptionCode& ec, bool shouldLazyAttach)
588 if (!isContainerNode()) {
589 ec = HIERARCHY_REQUEST_ERR;
592 return toContainerNode(this)->insertBefore(newChild, refChild, ec, shouldLazyAttach);
595 bool Node::replaceChild(PassRefPtr<Node> newChild, Node* oldChild, ExceptionCode& ec, bool shouldLazyAttach)
597 if (!isContainerNode()) {
598 ec = HIERARCHY_REQUEST_ERR;
601 return toContainerNode(this)->replaceChild(newChild, oldChild, ec, shouldLazyAttach);
604 bool Node::removeChild(Node* oldChild, ExceptionCode& ec)
606 if (!isContainerNode()) {
610 return toContainerNode(this)->removeChild(oldChild, ec);
613 bool Node::appendChild(PassRefPtr<Node> newChild, ExceptionCode& ec, bool shouldLazyAttach)
615 if (!isContainerNode()) {
616 ec = HIERARCHY_REQUEST_ERR;
619 return toContainerNode(this)->appendChild(newChild, ec, shouldLazyAttach);
622 void Node::remove(ExceptionCode& ec)
624 if (ContainerNode* parent = parentNode())
625 parent->removeChild(this, ec);
627 ec = HIERARCHY_REQUEST_ERR;
630 void Node::normalize()
632 // Go through the subtree beneath us, normalizing all nodes. This means that
633 // any two adjacent text nodes are merged and any empty text nodes are removed.
635 RefPtr<Node> node = this;
636 while (Node* firstChild = node->firstChild())
639 NodeType type = node->nodeType();
640 if (type == ELEMENT_NODE)
641 static_cast<Element*>(node.get())->normalizeAttributes();
646 if (type != TEXT_NODE) {
647 node = node->traverseNextNodePostOrder();
651 RefPtr<Text> text = toText(node.get());
653 // Remove empty text nodes.
654 if (!text->length()) {
655 // Care must be taken to get the next node before removing the current node.
656 node = node->traverseNextNodePostOrder();
663 while (Node* nextSibling = node->nextSibling()) {
664 if (nextSibling->nodeType() != TEXT_NODE)
666 RefPtr<Text> nextText = toText(nextSibling);
668 // Remove empty text nodes.
669 if (!nextText->length()) {
671 nextText->remove(ec);
675 // Both non-empty text nodes. Merge them.
676 unsigned offset = text->length();
678 text->appendData(nextText->data(), ec);
679 document()->textNodesMerged(nextText.get(), offset);
680 nextText->remove(ec);
683 node = node->traverseNextNodePostOrder();
687 const AtomicString& Node::virtualPrefix() const
689 // For nodes other than elements and attributes, the prefix is always null
693 void Node::setPrefix(const AtomicString& /*prefix*/, ExceptionCode& ec)
695 // The spec says that for nodes other than elements and attributes, prefix is always null.
696 // It does not say what to do when the user tries to set the prefix on another type of
697 // node, however Mozilla throws a NAMESPACE_ERR exception.
701 const AtomicString& Node::virtualLocalName() const
706 const AtomicString& Node::virtualNamespaceURI() const
711 bool Node::isContentEditable()
713 document()->updateStyleIfNeeded();
714 return rendererIsEditable(Editable);
717 bool Node::isContentRichlyEditable()
719 document()->updateStyleIfNeeded();
720 return rendererIsEditable(RichlyEditable);
725 #if ENABLE(INSPECTOR)
726 if (document() && document()->page())
727 document()->page()->inspectorController()->inspect(this);
731 bool Node::rendererIsEditable(EditableLevel editableLevel) const
733 if (document()->frame() && document()->frame()->page() && document()->frame()->page()->isEditable() && !shadowRoot())
736 // Ideally we'd call ASSERT(!needsStyleRecalc()) here, but
737 // ContainerNode::setFocus() calls setNeedsStyleRecalc(), so the assertion
738 // would fire in the middle of Document::setFocusedNode().
740 for (const Node* node = this; node; node = node->parentNode()) {
741 if ((node->isHTMLElement() || node->isDocumentNode()) && node->renderer()) {
742 switch (node->renderer()->style()->userModify()) {
747 case READ_WRITE_PLAINTEXT_ONLY:
748 return editableLevel != RichlyEditable;
750 ASSERT_NOT_REACHED();
758 bool Node::isEditableToAccessibility(EditableLevel editableLevel) const
760 if (rendererIsEditable(editableLevel))
763 // FIXME: Respect editableLevel for ARIA editable elements.
764 if (editableLevel == RichlyEditable)
768 ASSERT(AXObjectCache::accessibilityEnabled());
769 ASSERT(document()->axObjectCacheExists());
771 if (document() && AXObjectCache::accessibilityEnabled() && document()->axObjectCacheExists())
772 return document()->axObjectCache()->rootAXEditableElement(this);
777 bool Node::shouldUseInputMethod()
779 return isContentEditable();
782 RenderBox* Node::renderBox() const
784 return m_renderer && m_renderer->isBox() ? toRenderBox(m_renderer) : 0;
787 RenderBoxModelObject* Node::renderBoxModelObject() const
789 return m_renderer && m_renderer->isBoxModelObject() ? toRenderBoxModelObject(m_renderer) : 0;
792 LayoutRect Node::getRect() const
795 return renderer()->absoluteBoundingBoxRect();
799 LayoutRect Node::renderRect(bool* isReplaced)
801 RenderObject* hitRenderer = this->renderer();
803 RenderObject* renderer = hitRenderer;
804 while (renderer && !renderer->isBody() && !renderer->isRoot()) {
805 if (renderer->isRenderBlock() || renderer->isInlineBlockOrInlineTable() || renderer->isReplaced()) {
806 *isReplaced = renderer->isReplaced();
807 return renderer->absoluteBoundingBoxRect();
809 renderer = renderer->parent();
814 bool Node::hasNonEmptyBoundingBox() const
816 // Before calling absoluteRects, check for the common case where the renderer
817 // is non-empty, since this is a faster check and almost always returns true.
818 RenderBoxModelObject* box = renderBoxModelObject();
821 if (!box->borderBoundingBox().isEmpty())
824 Vector<IntRect> rects;
825 FloatPoint absPos = renderer()->localToAbsolute();
826 renderer()->absoluteRects(rects, flooredLayoutPoint(absPos));
827 size_t n = rects.size();
828 for (size_t i = 0; i < n; ++i)
829 if (!rects[i].isEmpty())
835 inline static ShadowRoot* oldestShadowRootFor(const Node* node)
837 if (!node->isElementNode())
839 if (ElementShadow* shadow = toElement(node)->shadow())
840 return shadow->oldestShadowRoot();
844 inline void Node::setStyleChange(StyleChangeType changeType)
846 m_nodeFlags = (m_nodeFlags & ~StyleChangeMask) | changeType;
849 inline void Node::markAncestorsWithChildNeedsStyleRecalc()
851 for (ContainerNode* p = parentOrHostNode(); p && !p->childNeedsStyleRecalc(); p = p->parentOrHostNode())
852 p->setChildNeedsStyleRecalc();
854 if (document()->childNeedsStyleRecalc())
855 document()->scheduleStyleRecalc();
858 void Node::refEventTarget()
863 void Node::derefEventTarget()
868 void Node::setNeedsStyleRecalc(StyleChangeType changeType)
870 ASSERT(changeType != NoStyleChange);
871 if (!attached()) // changed compared to what?
874 StyleChangeType existingChangeType = styleChangeType();
875 if (changeType > existingChangeType)
876 setStyleChange(changeType);
878 if (existingChangeType == NoStyleChange)
879 markAncestorsWithChildNeedsStyleRecalc();
882 void Node::lazyAttach(ShouldSetAttached shouldSetAttached)
884 for (Node* n = this; n; n = n->traverseNextNode(this)) {
885 if (n->hasChildNodes())
886 n->setChildNeedsStyleRecalc();
887 n->setStyleChange(FullStyleChange);
888 if (shouldSetAttached == SetAttached)
891 markAncestorsWithChildNeedsStyleRecalc();
894 void Node::setFocus(bool b)
896 if (b || hasRareData())
897 ensureRareData()->setFocused(b);
900 bool Node::rareDataFocused() const
902 ASSERT(hasRareData());
903 return rareData()->isFocused();
906 bool Node::supportsFocus() const
908 return hasRareData() && rareData()->tabIndexSetExplicitly();
911 bool Node::isFocusable() const
913 if (!inDocument() || !supportsFocus())
917 ASSERT(!renderer()->needsLayout());
919 // If the node is in a display:none tree it might say it needs style recalc but
920 // the whole document is actually up to date.
921 ASSERT(!document()->childNeedsStyleRecalc());
923 // Elements in canvas fallback content are not rendered, but they are allowed to be
924 // focusable as long as their canvas is displayed and visible.
925 if (isElementNode() && toElement(this)->isInCanvasSubtree()) {
926 const Element* e = toElement(this);
927 while (e && !e->hasLocalName(canvasTag))
928 e = e->parentElement();
930 return e->renderer() && e->renderer()->style()->visibility() == VISIBLE;
933 // FIXME: Even if we are not visible, we might have a child that is visible.
934 // Hyatt wants to fix that some day with a "has visible content" flag or the like.
935 if (!renderer() || renderer()->style()->visibility() != VISIBLE)
941 bool Node::isKeyboardFocusable(KeyboardEvent*) const
943 return isFocusable() && tabIndex() >= 0;
946 bool Node::isMouseFocusable() const
948 return isFocusable();
951 Node* Node::focusDelegate()
956 unsigned Node::nodeIndex() const
958 Node *_tempNode = previousSibling();
960 for ( count=0; _tempNode; count++ )
961 _tempNode = _tempNode->previousSibling();
965 template<unsigned type>
966 bool shouldInvalidateNodeListCachesForAttr(const unsigned nodeListCounts[], const QualifiedName& attrName)
968 if (nodeListCounts[type] && DynamicNodeListCacheBase::shouldInvalidateTypeOnAttributeChange(static_cast<NodeListInvalidationType>(type), attrName))
970 return shouldInvalidateNodeListCachesForAttr<type + 1>(nodeListCounts, attrName);
974 bool shouldInvalidateNodeListCachesForAttr<numNodeListInvalidationTypes>(const unsigned[], const QualifiedName&)
979 bool Document::shouldInvalidateNodeListCaches(const QualifiedName* attrName) const
982 return shouldInvalidateNodeListCachesForAttr<DoNotInvalidateOnAttributeChanges + 1>(m_nodeListCounts, *attrName);
984 for (int type = 0; type < numNodeListInvalidationTypes; type++) {
985 if (m_nodeListCounts[type])
992 void Document::invalidateNodeListCaches(const QualifiedName* attrName)
994 HashSet<DynamicNodeListCacheBase*>::iterator end = m_listsInvalidatedAtDocument.end();
995 for (HashSet<DynamicNodeListCacheBase*>::iterator it = m_listsInvalidatedAtDocument.begin(); it != end; ++it)
996 (*it)->invalidateCache(attrName);
999 void Node::invalidateNodeListCachesInAncestors(const QualifiedName* attrName, Element* attributeOwnerElement)
1001 if (hasRareData() && (!attrName || isAttributeNode()))
1002 rareData()->clearChildNodeListCache();
1004 // Modifications to attributes that are not associated with an Element can't invalidate NodeList caches.
1005 if (attrName && !attributeOwnerElement)
1008 if (!document()->shouldInvalidateNodeListCaches(attrName))
1011 document()->invalidateNodeListCaches(attrName);
1013 for (Node* node = this; node; node = node->parentNode()) {
1014 if (!node->hasRareData())
1016 NodeRareData* data = node->rareData();
1017 if (data->nodeLists())
1018 data->nodeLists()->invalidateCaches(attrName);
1019 if (node->isElementNode())
1020 static_cast<ElementRareData*>(data)->clearHTMLCollectionCaches(attrName);
1024 NodeListsNodeData* Node::nodeLists()
1026 return hasRareData() ? rareData()->nodeLists() : 0;
1029 void Node::removeCachedChildNodeList()
1032 rareData()->setChildNodeList(0);
1035 Node* Node::traverseNextAncestorSibling() const
1037 ASSERT(!nextSibling());
1038 for (const Node* node = parentNode(); node; node = node->parentNode()) {
1039 if (node->nextSibling())
1040 return node->nextSibling();
1045 Node* Node::traverseNextAncestorSibling(const Node* stayWithin) const
1047 ASSERT(!nextSibling());
1048 ASSERT(this != stayWithin);
1049 for (const Node* node = parentNode(); node; node = node->parentNode()) {
1050 if (node == stayWithin)
1052 if (node->nextSibling())
1053 return node->nextSibling();
1058 Node* Node::traverseNextNodePostOrder() const
1060 Node* next = nextSibling();
1062 return parentNode();
1063 while (Node* firstChild = next->firstChild())
1068 Node* Node::traversePreviousNode(const Node* stayWithin) const
1070 if (this == stayWithin)
1072 if (previousSibling()) {
1073 Node *n = previousSibling();
1074 while (n->lastChild())
1078 return parentNode();
1081 Node* Node::traversePreviousSibling(const Node* stayWithin) const
1083 if (this == stayWithin)
1085 if (previousSibling())
1086 return previousSibling();
1087 const Node *n = this;
1088 while (n && !n->previousSibling() && (!stayWithin || n->parentNode() != stayWithin))
1089 n = n->parentNode();
1091 return n->previousSibling();
1095 Node* Node::traversePreviousNodePostOrder(const Node* stayWithin) const
1099 if (this == stayWithin)
1101 if (previousSibling())
1102 return previousSibling();
1103 const Node *n = this;
1104 while (n && !n->previousSibling() && (!stayWithin || n->parentNode() != stayWithin))
1105 n = n->parentNode();
1107 return n->previousSibling();
1111 Node* Node::traversePreviousSiblingPostOrder(const Node* stayWithin) const
1113 if (this == stayWithin)
1115 if (previousSibling())
1116 return previousSibling();
1117 const Node *n = this;
1118 while (n && !n->previousSibling() && (!stayWithin || n->parentNode() != stayWithin))
1119 n = n->parentNode();
1121 return n->previousSibling();
1125 void Node::checkSetPrefix(const AtomicString& prefix, ExceptionCode& ec)
1127 // Perform error checking as required by spec for setting Node.prefix. Used by
1128 // Element::setPrefix() and Attr::setPrefix()
1130 if (!prefix.isEmpty() && !Document::isValidName(prefix)) {
1131 ec = INVALID_CHARACTER_ERR;
1135 if (isReadOnlyNode()) {
1136 ec = NO_MODIFICATION_ALLOWED_ERR;
1140 // FIXME: Raise NAMESPACE_ERR if prefix is malformed per the Namespaces in XML specification.
1142 const AtomicString& nodeNamespaceURI = namespaceURI();
1143 if ((nodeNamespaceURI.isEmpty() && !prefix.isEmpty())
1144 || (prefix == xmlAtom && nodeNamespaceURI != XMLNames::xmlNamespaceURI)) {
1148 // Attribute-specific checks are in Attr::setPrefix().
1151 static bool isChildTypeAllowed(Node* newParent, Node* child)
1153 if (child->nodeType() != Node::DOCUMENT_FRAGMENT_NODE) {
1154 if (!newParent->childTypeAllowed(child->nodeType()))
1159 for (Node *n = child->firstChild(); n; n = n->nextSibling()) {
1160 if (!newParent->childTypeAllowed(n->nodeType()))
1166 bool Node::canReplaceChild(Node* newChild, Node*)
1168 return isChildTypeAllowed(this, newChild);
1171 static void checkAcceptChild(Node* newParent, Node* newChild, ExceptionCode& ec)
1173 // Not mentioned in spec: throw NOT_FOUND_ERR if newChild is null
1179 if (newParent->isReadOnlyNode()) {
1180 ec = NO_MODIFICATION_ALLOWED_ERR;
1184 if (newChild->inDocument() && newChild->nodeType() == Node::DOCUMENT_TYPE_NODE) {
1185 ec = HIERARCHY_REQUEST_ERR;
1189 // HIERARCHY_REQUEST_ERR: Raised if this node is of a type that does not allow children of the type of the
1190 // newChild node, or if the node to append is one of this node's ancestors.
1192 if (newChild == newParent || newParent->isDescendantOf(newChild)) {
1193 ec = HIERARCHY_REQUEST_ERR;
1198 void Node::checkReplaceChild(Node* newChild, Node* oldChild, ExceptionCode& ec)
1205 checkAcceptChild(this, newChild, ec);
1209 if (!canReplaceChild(newChild, oldChild)) {
1210 ec = HIERARCHY_REQUEST_ERR;
1215 void Node::checkAddChild(Node *newChild, ExceptionCode& ec)
1217 checkAcceptChild(this, newChild, ec);
1221 if (!isChildTypeAllowed(this, newChild)) {
1222 ec = HIERARCHY_REQUEST_ERR;
1227 bool Node::isDescendantOf(const Node *other) const
1229 // Return true if other is an ancestor of this, otherwise false
1230 if (!other || !other->hasChildNodes() || inDocument() != other->inDocument())
1232 if (other == other->document())
1233 return document() == other && this != document() && inDocument();
1234 for (const ContainerNode* n = parentNode(); n; n = n->parentNode()) {
1241 bool Node::contains(const Node* node) const
1245 return this == node || node->isDescendantOf(this);
1248 bool Node::containsIncludingShadowDOM(Node* node)
1252 for (Node* n = node; n; n = n->parentOrHostNode()) {
1261 ASSERT(!attached());
1262 ASSERT(!renderer() || (renderer()->style() && renderer()->parent()));
1264 // FIXME: This is O(N^2) for the innerHTML case, where all children are replaced at once (and not attached).
1265 // If this node got a renderer it may be the previousRenderer() of sibling text nodes and thus affect the
1266 // result of Text::rendererIsNeeded() for those nodes.
1268 for (Node* next = nextSibling(); next; next = next->nextSibling()) {
1269 if (next->renderer())
1271 if (!next->attached())
1272 break; // Assume this means none of the following siblings are attached.
1273 if (next->isTextNode())
1274 next->createRendererIfNeeded();
1279 clearNeedsStyleRecalc();
1283 static Node* detachingNode;
1285 bool Node::inDetach() const
1287 return detachingNode == this;
1294 ASSERT(!detachingNode);
1295 detachingNode = this;
1299 renderer()->destroyAndCleanupAnonymousWrappers();
1302 Document* doc = document();
1304 doc->hoveredNodeDetached(this);
1305 if (inActiveChain())
1306 doc->activeChainNodeDetached(this);
1308 clearFlag(IsActiveFlag);
1309 clearFlag(IsHoveredFlag);
1310 clearFlag(InActiveChainFlag);
1311 clearFlag(IsAttachedFlag);
1318 // FIXME: This code is used by editing. Seems like it could move over there and not pollute Node.
1319 Node *Node::previousNodeConsideringAtomicNodes() const
1321 if (previousSibling()) {
1322 Node *n = previousSibling();
1323 while (!isAtomicNode(n) && n->lastChild())
1327 else if (parentNode()) {
1328 return parentNode();
1335 Node *Node::nextNodeConsideringAtomicNodes() const
1337 if (!isAtomicNode(this) && firstChild())
1338 return firstChild();
1340 return nextSibling();
1341 const Node *n = this;
1342 while (n && !n->nextSibling())
1343 n = n->parentNode();
1345 return n->nextSibling();
1349 Node *Node::previousLeafNode() const
1351 Node *node = previousNodeConsideringAtomicNodes();
1353 if (isAtomicNode(node))
1355 node = node->previousNodeConsideringAtomicNodes();
1360 Node *Node::nextLeafNode() const
1362 Node *node = nextNodeConsideringAtomicNodes();
1364 if (isAtomicNode(node))
1366 node = node->nextNodeConsideringAtomicNodes();
1371 ContainerNode* Node::parentNodeForRenderingAndStyle()
1373 return NodeRenderingContext(this).parentNodeForRenderingAndStyle();
1376 void Node::createRendererIfNeeded()
1378 NodeRendererFactory(this).createRendererIfNeeded();
1381 bool Node::rendererIsNeeded(const NodeRenderingContext& context)
1383 return (document()->documentElement() == this) || (context.style()->display() != NONE);
1386 RenderObject* Node::createRenderer(RenderArena*, RenderStyle*)
1388 ASSERT_NOT_REACHED();
1392 RenderStyle* Node::nonRendererRenderStyle() const
1397 void Node::setRenderStyle(PassRefPtr<RenderStyle> s)
1400 m_renderer->setAnimatableStyle(s);
1403 RenderStyle* Node::virtualComputedStyle(PseudoId pseudoElementSpecifier)
1405 return parentOrHostNode() ? parentOrHostNode()->computedStyle(pseudoElementSpecifier) : 0;
1408 int Node::maxCharacterOffset() const
1410 ASSERT_NOT_REACHED();
1414 // FIXME: Shouldn't these functions be in the editing code? Code that asks questions about HTML in the core DOM class
1415 // is obviously misplaced.
1416 bool Node::canStartSelection() const
1418 if (rendererIsEditable())
1422 RenderStyle* style = renderer()->style();
1423 // We allow selections to begin within an element that has -webkit-user-select: none set,
1424 // but if the element is draggable then dragging should take priority over selection.
1425 if (style->userDrag() == DRAG_ELEMENT && style->userSelect() == SELECT_NONE)
1428 return parentOrHostNode() ? parentOrHostNode()->canStartSelection() : true;
1431 Element* Node::shadowHost() const
1433 if (ShadowRoot* root = shadowRoot())
1434 return root->host();
1438 Node* Node::shadowAncestorNode() const
1440 if (ShadowRoot* root = shadowRoot())
1441 return root->host();
1443 return const_cast<Node*>(this);
1446 ShadowRoot* Node::shadowRoot() const
1448 Node* root = const_cast<Node*>(this);
1450 if (root->isShadowRoot())
1451 return toShadowRoot(root);
1452 root = root->parentNodeGuaranteedHostFree();
1457 Node* Node::nonBoundaryShadowTreeRootNode()
1459 ASSERT(!isShadowRoot());
1462 if (root->isShadowRoot())
1464 Node* parent = root->parentNodeGuaranteedHostFree();
1465 if (parent && parent->isShadowRoot())
1472 ContainerNode* Node::nonShadowBoundaryParentNode() const
1474 ContainerNode* parent = parentNode();
1475 return parent && !parent->isShadowRoot() ? parent : 0;
1478 bool Node::isInShadowTree() const
1480 return treeScope() != document();
1483 Element* Node::parentOrHostElement() const
1485 ContainerNode* parent = parentOrHostNode();
1489 if (parent->isShadowRoot())
1490 return toShadowRoot(parent)->host();
1492 if (!parent->isElementNode())
1495 return toElement(parent);
1499 bool Node::isBlockFlow() const
1501 return renderer() && renderer()->isBlockFlow();
1504 bool Node::isBlockFlowOrBlockTable() const
1506 return renderer() && (renderer()->isBlockFlow() || (renderer()->isTable() && !renderer()->isInline()));
1509 Element *Node::enclosingBlockFlowElement() const
1511 Node *n = const_cast<Node *>(this);
1513 return static_cast<Element *>(n);
1516 n = n->parentNode();
1519 if (n->isBlockFlow() || n->hasTagName(bodyTag))
1520 return static_cast<Element *>(n);
1525 bool Node::isRootEditableElement() const
1527 return rendererIsEditable() && isElementNode() && (!parentNode() || !parentNode()->rendererIsEditable()
1528 || !parentNode()->isElementNode() || hasTagName(bodyTag));
1531 Element* Node::rootEditableElement(EditableType editableType) const
1533 if (editableType == HasEditableAXRole)
1534 return const_cast<Element*>(document()->axObjectCache()->rootAXEditableElement(this));
1536 return rootEditableElement();
1539 Element* Node::rootEditableElement() const
1541 Element* result = 0;
1542 for (Node* n = const_cast<Node*>(this); n && n->rendererIsEditable(); n = n->parentNode()) {
1543 if (n->isElementNode())
1544 result = static_cast<Element*>(n);
1545 if (n->hasTagName(bodyTag))
1551 bool Node::inSameContainingBlockFlowElement(Node *n)
1553 return n ? enclosingBlockFlowElement() == n->enclosingBlockFlowElement() : false;
1556 // FIXME: End of obviously misplaced HTML editing functions. Try to move these out of Node.
1558 PassRefPtr<NodeList> Node::getElementsByTagName(const AtomicString& localName)
1560 if (localName.isNull())
1563 if (document()->isHTMLDocument())
1564 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLTagNodeList>(this, DynamicNodeList::TagNodeListType, localName);
1565 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<TagNodeList>(this, DynamicNodeList::TagNodeListType, localName);
1568 PassRefPtr<NodeList> Node::getElementsByTagNameNS(const AtomicString& namespaceURI, const AtomicString& localName)
1570 if (localName.isNull())
1573 if (namespaceURI == starAtom)
1574 return getElementsByTagName(localName);
1576 return ensureRareData()->ensureNodeLists()->addCacheWithQualifiedName(this, namespaceURI.isEmpty() ? nullAtom : namespaceURI, localName);
1579 PassRefPtr<NodeList> Node::getElementsByName(const String& elementName)
1581 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<NameNodeList>(this, DynamicNodeList::NameNodeListType, elementName);
1584 PassRefPtr<NodeList> Node::getElementsByClassName(const String& classNames)
1586 return ensureRareData()->ensureNodeLists()->addCacheWithName<ClassNodeList>(this, DynamicNodeList::ClassNodeListType, classNames);
1589 PassRefPtr<RadioNodeList> Node::radioNodeList(const AtomicString& name)
1591 ASSERT(hasTagName(formTag) || hasTagName(fieldsetTag));
1592 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<RadioNodeList>(this, DynamicNodeList::RadioNodeListType, name);
1595 PassRefPtr<Element> Node::querySelector(const AtomicString& selectors, ExceptionCode& ec)
1597 if (selectors.isEmpty()) {
1602 SelectorQuery* selectorQuery = document()->selectorQueryCache()->add(selectors, document(), ec);
1605 return selectorQuery->queryFirst(this);
1608 PassRefPtr<NodeList> Node::querySelectorAll(const AtomicString& selectors, ExceptionCode& ec)
1610 if (selectors.isEmpty()) {
1615 SelectorQuery* selectorQuery = document()->selectorQueryCache()->add(selectors, document(), ec);
1618 return selectorQuery->queryAll(this);
1621 Document *Node::ownerDocument() const
1623 Document *doc = document();
1624 return doc == this ? 0 : doc;
1627 KURL Node::baseURI() const
1629 return parentNode() ? parentNode()->baseURI() : KURL();
1632 bool Node::isEqualNode(Node* other) const
1637 NodeType nodeType = this->nodeType();
1638 if (nodeType != other->nodeType())
1641 if (nodeName() != other->nodeName())
1644 if (localName() != other->localName())
1647 if (namespaceURI() != other->namespaceURI())
1650 if (prefix() != other->prefix())
1653 if (nodeValue() != other->nodeValue())
1656 if (isElementNode() && !toElement(this)->hasEquivalentAttributes(toElement(other)))
1659 Node* child = firstChild();
1660 Node* otherChild = other->firstChild();
1663 if (!child->isEqualNode(otherChild))
1666 child = child->nextSibling();
1667 otherChild = otherChild->nextSibling();
1673 if (nodeType == DOCUMENT_TYPE_NODE) {
1674 const DocumentType* documentTypeThis = static_cast<const DocumentType*>(this);
1675 const DocumentType* documentTypeOther = static_cast<const DocumentType*>(other);
1677 if (documentTypeThis->publicId() != documentTypeOther->publicId())
1680 if (documentTypeThis->systemId() != documentTypeOther->systemId())
1683 if (documentTypeThis->internalSubset() != documentTypeOther->internalSubset())
1686 // FIXME: We don't compare entities or notations because currently both are always empty.
1692 bool Node::isDefaultNamespace(const AtomicString& namespaceURIMaybeEmpty) const
1694 const AtomicString& namespaceURI = namespaceURIMaybeEmpty.isEmpty() ? nullAtom : namespaceURIMaybeEmpty;
1696 switch (nodeType()) {
1697 case ELEMENT_NODE: {
1698 const Element* elem = static_cast<const Element*>(this);
1700 if (elem->prefix().isNull())
1701 return elem->namespaceURI() == namespaceURI;
1703 if (elem->hasAttributes()) {
1704 for (unsigned i = 0; i < elem->attributeCount(); i++) {
1705 Attribute* attr = elem->attributeItem(i);
1707 if (attr->localName() == xmlnsAtom)
1708 return attr->value() == namespaceURI;
1712 if (Element* ancestor = ancestorElement())
1713 return ancestor->isDefaultNamespace(namespaceURI);
1718 if (Element* de = static_cast<const Document*>(this)->documentElement())
1719 return de->isDefaultNamespace(namespaceURI);
1723 case DOCUMENT_TYPE_NODE:
1724 case DOCUMENT_FRAGMENT_NODE:
1726 case ATTRIBUTE_NODE: {
1727 const Attr* attr = static_cast<const Attr*>(this);
1728 if (attr->ownerElement())
1729 return attr->ownerElement()->isDefaultNamespace(namespaceURI);
1733 if (Element* ancestor = ancestorElement())
1734 return ancestor->isDefaultNamespace(namespaceURI);
1739 String Node::lookupPrefix(const AtomicString &namespaceURI) const
1741 // Implemented according to
1742 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/namespaces-algorithms.html#lookupNamespacePrefixAlgo
1744 if (namespaceURI.isEmpty())
1747 switch (nodeType()) {
1749 return lookupNamespacePrefix(namespaceURI, static_cast<const Element *>(this));
1751 if (Element* de = static_cast<const Document*>(this)->documentElement())
1752 return de->lookupPrefix(namespaceURI);
1756 case DOCUMENT_FRAGMENT_NODE:
1757 case DOCUMENT_TYPE_NODE:
1759 case ATTRIBUTE_NODE: {
1760 const Attr *attr = static_cast<const Attr *>(this);
1761 if (attr->ownerElement())
1762 return attr->ownerElement()->lookupPrefix(namespaceURI);
1766 if (Element* ancestor = ancestorElement())
1767 return ancestor->lookupPrefix(namespaceURI);
1772 String Node::lookupNamespaceURI(const String &prefix) const
1774 // Implemented according to
1775 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/namespaces-algorithms.html#lookupNamespaceURIAlgo
1777 if (!prefix.isNull() && prefix.isEmpty())
1780 switch (nodeType()) {
1781 case ELEMENT_NODE: {
1782 const Element *elem = static_cast<const Element *>(this);
1784 if (!elem->namespaceURI().isNull() && elem->prefix() == prefix)
1785 return elem->namespaceURI();
1787 if (elem->hasAttributes()) {
1788 for (unsigned i = 0; i < elem->attributeCount(); i++) {
1789 Attribute* attr = elem->attributeItem(i);
1791 if (attr->prefix() == xmlnsAtom && attr->localName() == prefix) {
1792 if (!attr->value().isEmpty())
1793 return attr->value();
1796 } else if (attr->localName() == xmlnsAtom && prefix.isNull()) {
1797 if (!attr->value().isEmpty())
1798 return attr->value();
1804 if (Element* ancestor = ancestorElement())
1805 return ancestor->lookupNamespaceURI(prefix);
1809 if (Element* de = static_cast<const Document*>(this)->documentElement())
1810 return de->lookupNamespaceURI(prefix);
1814 case DOCUMENT_TYPE_NODE:
1815 case DOCUMENT_FRAGMENT_NODE:
1817 case ATTRIBUTE_NODE: {
1818 const Attr *attr = static_cast<const Attr *>(this);
1820 if (attr->ownerElement())
1821 return attr->ownerElement()->lookupNamespaceURI(prefix);
1826 if (Element* ancestor = ancestorElement())
1827 return ancestor->lookupNamespaceURI(prefix);
1832 String Node::lookupNamespacePrefix(const AtomicString &_namespaceURI, const Element *originalElement) const
1834 if (_namespaceURI.isNull())
1837 if (originalElement->lookupNamespaceURI(prefix()) == _namespaceURI)
1840 ASSERT(isElementNode());
1841 const Element* thisElement = toElement(this);
1842 if (thisElement->hasAttributes()) {
1843 for (unsigned i = 0; i < thisElement->attributeCount(); i++) {
1844 Attribute* attr = thisElement->attributeItem(i);
1846 if (attr->prefix() == xmlnsAtom && attr->value() == _namespaceURI
1847 && originalElement->lookupNamespaceURI(attr->localName()) == _namespaceURI)
1848 return attr->localName();
1852 if (Element* ancestor = ancestorElement())
1853 return ancestor->lookupNamespacePrefix(_namespaceURI, originalElement);
1857 static void appendTextContent(const Node* node, bool convertBRsToNewlines, bool& isNullString, StringBuilder& content)
1859 switch (node->nodeType()) {
1860 case Node::TEXT_NODE:
1861 case Node::CDATA_SECTION_NODE:
1862 case Node::COMMENT_NODE:
1863 isNullString = false;
1864 content.append(static_cast<const CharacterData*>(node)->data());
1867 case Node::PROCESSING_INSTRUCTION_NODE:
1868 isNullString = false;
1869 content.append(static_cast<const ProcessingInstruction*>(node)->data());
1872 case Node::ELEMENT_NODE:
1873 if (node->hasTagName(brTag) && convertBRsToNewlines) {
1874 isNullString = false;
1875 content.append('\n');
1879 case Node::ATTRIBUTE_NODE:
1880 case Node::ENTITY_NODE:
1881 case Node::ENTITY_REFERENCE_NODE:
1882 case Node::DOCUMENT_FRAGMENT_NODE:
1883 isNullString = false;
1884 for (Node* child = node->firstChild(); child; child = child->nextSibling()) {
1885 if (child->nodeType() == Node::COMMENT_NODE || child->nodeType() == Node::PROCESSING_INSTRUCTION_NODE)
1887 appendTextContent(child, convertBRsToNewlines, isNullString, content);
1891 case Node::DOCUMENT_NODE:
1892 case Node::DOCUMENT_TYPE_NODE:
1893 case Node::NOTATION_NODE:
1894 case Node::XPATH_NAMESPACE_NODE:
1899 String Node::textContent(bool convertBRsToNewlines) const
1901 StringBuilder content;
1902 bool isNullString = true;
1903 appendTextContent(this, convertBRsToNewlines, isNullString, content);
1904 return isNullString ? String() : content.toString();
1907 void Node::setTextContent(const String& text, ExceptionCode& ec)
1909 switch (nodeType()) {
1911 case CDATA_SECTION_NODE:
1913 case PROCESSING_INSTRUCTION_NODE:
1914 setNodeValue(text, ec);
1917 case ATTRIBUTE_NODE:
1919 case ENTITY_REFERENCE_NODE:
1920 case DOCUMENT_FRAGMENT_NODE: {
1921 RefPtr<ContainerNode> container = toContainerNode(this);
1922 #if ENABLE(MUTATION_OBSERVERS)
1923 ChildListMutationScope mutation(this);
1925 container->removeChildren();
1926 if (!text.isEmpty())
1927 container->appendChild(document()->createTextNode(text), ec);
1931 case DOCUMENT_TYPE_NODE:
1933 case XPATH_NAMESPACE_NODE:
1937 ASSERT_NOT_REACHED();
1940 Element* Node::ancestorElement() const
1942 // In theory, there can be EntityReference nodes between elements, but this is currently not supported.
1943 for (ContainerNode* n = parentNode(); n; n = n->parentNode()) {
1944 if (n->isElementNode())
1945 return static_cast<Element*>(n);
1950 bool Node::offsetInCharacters() const
1955 unsigned short Node::compareDocumentPosition(Node* otherNode)
1957 // It is not clear what should be done if |otherNode| is 0.
1959 return DOCUMENT_POSITION_DISCONNECTED;
1961 if (otherNode == this)
1962 return DOCUMENT_POSITION_EQUIVALENT;
1964 Attr* attr1 = nodeType() == ATTRIBUTE_NODE ? static_cast<Attr*>(this) : 0;
1965 Attr* attr2 = otherNode->nodeType() == ATTRIBUTE_NODE ? static_cast<Attr*>(otherNode) : 0;
1967 Node* start1 = attr1 ? attr1->ownerElement() : this;
1968 Node* start2 = attr2 ? attr2->ownerElement() : otherNode;
1970 // If either of start1 or start2 is null, then we are disconnected, since one of the nodes is
1971 // an orphaned attribute node.
1972 if (!start1 || !start2)
1973 return DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC;
1975 Vector<Node*, 16> chain1;
1976 Vector<Node*, 16> chain2;
1978 chain1.append(attr1);
1980 chain2.append(attr2);
1982 if (attr1 && attr2 && start1 == start2 && start1) {
1983 // We are comparing two attributes on the same node. Crawl our attribute map and see which one we hit first.
1984 Element* owner1 = attr1->ownerElement();
1985 owner1->updatedAttributeData(); // Force update invalid attributes.
1986 unsigned length = owner1->attributeCount();
1987 for (unsigned i = 0; i < length; ++i) {
1988 // If neither of the two determining nodes is a child node and nodeType is the same for both determining nodes, then an
1989 // implementation-dependent order between the determining nodes is returned. This order is stable as long as no nodes of
1990 // the same nodeType are inserted into or removed from the direct container. This would be the case, for example,
1991 // when comparing two attributes of the same element, and inserting or removing additional attributes might change
1992 // the order between existing attributes.
1993 Attribute* attribute = owner1->attributeItem(i);
1994 if (attr1->qualifiedName() == attribute->name())
1995 return DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | DOCUMENT_POSITION_FOLLOWING;
1996 if (attr2->qualifiedName() == attribute->name())
1997 return DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | DOCUMENT_POSITION_PRECEDING;
2000 ASSERT_NOT_REACHED();
2001 return DOCUMENT_POSITION_DISCONNECTED;
2004 // If one node is in the document and the other is not, we must be disconnected.
2005 // If the nodes have different owning documents, they must be disconnected. Note that we avoid
2006 // comparing Attr nodes here, since they return false from inDocument() all the time (which seems like a bug).
2007 if (start1->inDocument() != start2->inDocument() ||
2008 start1->document() != start2->document())
2009 return DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC;
2011 // We need to find a common ancestor container, and then compare the indices of the two immediate children.
2013 for (current = start1; current; current = current->parentNode())
2014 chain1.append(current);
2015 for (current = start2; current; current = current->parentNode())
2016 chain2.append(current);
2018 // Walk the two chains backwards and look for the first difference.
2019 unsigned index1 = chain1.size();
2020 unsigned index2 = chain2.size();
2021 for (unsigned i = min(index1, index2); i; --i) {
2022 Node* child1 = chain1[--index1];
2023 Node* child2 = chain2[--index2];
2024 if (child1 != child2) {
2025 // If one of the children is an attribute, it wins.
2026 if (child1->nodeType() == ATTRIBUTE_NODE)
2027 return DOCUMENT_POSITION_FOLLOWING;
2028 if (child2->nodeType() == ATTRIBUTE_NODE)
2029 return DOCUMENT_POSITION_PRECEDING;
2031 if (!child2->nextSibling())
2032 return DOCUMENT_POSITION_FOLLOWING;
2033 if (!child1->nextSibling())
2034 return DOCUMENT_POSITION_PRECEDING;
2036 // Otherwise we need to see which node occurs first. Crawl backwards from child2 looking for child1.
2037 for (Node* child = child2->previousSibling(); child; child = child->previousSibling()) {
2038 if (child == child1)
2039 return DOCUMENT_POSITION_FOLLOWING;
2041 return DOCUMENT_POSITION_PRECEDING;
2045 // There was no difference between the two parent chains, i.e., one was a subset of the other. The shorter
2046 // chain is the ancestor.
2047 return index1 < index2 ?
2048 DOCUMENT_POSITION_FOLLOWING | DOCUMENT_POSITION_CONTAINED_BY :
2049 DOCUMENT_POSITION_PRECEDING | DOCUMENT_POSITION_CONTAINS;
2052 FloatPoint Node::convertToPage(const FloatPoint& p) const
2054 // If there is a renderer, just ask it to do the conversion
2056 return renderer()->localToAbsolute(p, false, true);
2058 // Otherwise go up the tree looking for a renderer
2059 Element *parent = ancestorElement();
2061 return parent->convertToPage(p);
2063 // No parent - no conversion needed
2067 FloatPoint Node::convertFromPage(const FloatPoint& p) const
2069 // If there is a renderer, just ask it to do the conversion
2071 return renderer()->absoluteToLocal(p, false, true);
2073 // Otherwise go up the tree looking for a renderer
2074 Element *parent = ancestorElement();
2076 return parent->convertFromPage(p);
2078 // No parent - no conversion needed
2084 static void appendAttributeDesc(const Node* node, String& string, const QualifiedName& name, const char* attrDesc)
2086 if (node->isElementNode()) {
2087 String attr = static_cast<const Element*>(node)->getAttribute(name);
2088 if (!attr.isEmpty()) {
2095 void Node::showNode(const char* prefix) const
2100 String value = nodeValue();
2101 value.replace('\\', "\\\\");
2102 value.replace('\n', "\\n");
2103 fprintf(stderr, "%s%s\t%p \"%s\"\n", prefix, nodeName().utf8().data(), this, value.utf8().data());
2106 appendAttributeDesc(this, attrs, classAttr, " CLASS=");
2107 appendAttributeDesc(this, attrs, styleAttr, " STYLE=");
2108 fprintf(stderr, "%s%s\t%p%s\n", prefix, nodeName().utf8().data(), this, attrs.utf8().data());
2112 void Node::showTreeForThis() const
2114 showTreeAndMark(this, "*");
2117 void Node::showNodePathForThis() const
2119 Vector<const Node*, 16> chain;
2120 const Node* node = this;
2121 while (node->parentOrHostNode()) {
2123 node = node->parentOrHostNode();
2125 for (unsigned index = chain.size(); index > 0; --index) {
2126 const Node* node = chain[index - 1];
2127 if (node->isShadowRoot()) {
2129 for (ShadowRoot* shadowRoot = oldestShadowRootFor(node); shadowRoot && shadowRoot != node; shadowRoot = shadowRoot->youngerShadowRoot())
2131 fprintf(stderr, "/#shadow-root[%d]", count);
2135 switch (node->nodeType()) {
2136 case ELEMENT_NODE: {
2137 fprintf(stderr, "/%s", node->nodeName().utf8().data());
2139 const Element* element = toElement(node);
2140 const AtomicString& idattr = element->getIdAttribute();
2141 bool hasIdAttr = !idattr.isNull() && !idattr.isEmpty();
2142 if (node->previousSibling() || node->nextSibling()) {
2144 for (Node* previous = node->previousSibling(); previous; previous = previous->previousSibling())
2145 if (previous->nodeName() == node->nodeName())
2148 fprintf(stderr, "[@id=\"%s\" and position()=%d]", idattr.string().utf8().data(), count);
2150 fprintf(stderr, "[%d]", count);
2151 } else if (hasIdAttr)
2152 fprintf(stderr, "[@id=\"%s\"]", idattr.string().utf8().data());
2156 fprintf(stderr, "/text()");
2158 case ATTRIBUTE_NODE:
2159 fprintf(stderr, "/@%s", node->nodeName().utf8().data());
2165 fprintf(stderr, "\n");
2168 static void traverseTreeAndMark(const String& baseIndent, const Node* rootNode, const Node* markedNode1, const char* markedLabel1, const Node* markedNode2, const char* markedLabel2)
2170 for (const Node* node = rootNode; node; node = node->traverseNextNode()) {
2171 if (node == markedNode1)
2172 fprintf(stderr, "%s", markedLabel1);
2173 if (node == markedNode2)
2174 fprintf(stderr, "%s", markedLabel2);
2176 String indent = baseIndent;
2177 for (const Node* tmpNode = node; tmpNode && tmpNode != rootNode; tmpNode = tmpNode->parentOrHostNode())
2179 fprintf(stderr, "%s", indent.utf8().data());
2181 if (node->isShadowRoot()) {
2182 if (ShadowRoot* youngerShadowRoot = toShadowRoot(node)->youngerShadowRoot())
2183 traverseTreeAndMark(indent + "\t", youngerShadowRoot, markedNode1, markedLabel1, markedNode2, markedLabel2);
2184 } else if (ShadowRoot* oldestShadowRoot = oldestShadowRootFor(node))
2185 traverseTreeAndMark(indent + "\t", oldestShadowRoot, markedNode1, markedLabel1, markedNode2, markedLabel2);
2189 void Node::showTreeAndMark(const Node* markedNode1, const char* markedLabel1, const Node* markedNode2, const char* markedLabel2) const
2191 const Node* rootNode;
2192 const Node* node = this;
2193 while (node->parentOrHostNode() && !node->hasTagName(bodyTag))
2194 node = node->parentOrHostNode();
2197 String startingIndent;
2198 traverseTreeAndMark(startingIndent, rootNode, markedNode1, markedLabel1, markedNode2, markedLabel2);
2201 void Node::formatForDebugger(char* buffer, unsigned length) const
2207 if (s.length() == 0)
2212 strncpy(buffer, result.utf8().data(), length - 1);
2215 static ContainerNode* parentOrHostOrFrameOwner(const Node* node)
2217 ContainerNode* parent = node->parentOrHostNode();
2218 if (!parent && node->document() && node->document()->frame())
2219 parent = node->document()->frame()->ownerElement();
2223 static void showSubTreeAcrossFrame(const Node* node, const Node* markedNode, const String& indent)
2225 if (node == markedNode)
2227 fputs(indent.utf8().data(), stderr);
2229 if (node->isShadowRoot()) {
2230 if (ShadowRoot* youngerShadowRoot = toShadowRoot(node)->youngerShadowRoot())
2231 showSubTreeAcrossFrame(youngerShadowRoot, markedNode, indent + "\t");
2233 if (node->isFrameOwnerElement())
2234 showSubTreeAcrossFrame(static_cast<const HTMLFrameOwnerElement*>(node)->contentDocument(), markedNode, indent + "\t");
2235 if (ShadowRoot* oldestShadowRoot = oldestShadowRootFor(node))
2236 showSubTreeAcrossFrame(oldestShadowRoot, markedNode, indent + "\t");
2238 for (Node* child = node->firstChild(); child; child = child->nextSibling())
2239 showSubTreeAcrossFrame(child, markedNode, indent + "\t");
2242 void Node::showTreeForThisAcrossFrame() const
2244 Node* rootNode = const_cast<Node*>(this);
2245 while (parentOrHostOrFrameOwner(rootNode))
2246 rootNode = parentOrHostOrFrameOwner(rootNode);
2247 showSubTreeAcrossFrame(rootNode, this, "");
2254 void NodeListsNodeData::invalidateCaches(const QualifiedName* attrName)
2256 NodeListAtomicNameCacheMap::const_iterator atomicNameCacheEnd = m_atomicNameCaches.end();
2257 for (NodeListAtomicNameCacheMap::const_iterator it = m_atomicNameCaches.begin(); it != atomicNameCacheEnd; ++it)
2258 it->second->invalidateCache(attrName);
2260 NodeListNameCacheMap::const_iterator nameCacheEnd = m_nameCaches.end();
2261 for (NodeListNameCacheMap::const_iterator it = m_nameCaches.begin(); it != nameCacheEnd; ++it)
2262 it->second->invalidateCache(attrName);
2267 TagNodeListCacheNS::iterator tagCacheEnd = m_tagNodeListCacheNS.end();
2268 for (TagNodeListCacheNS::iterator it = m_tagNodeListCacheNS.begin(); it != tagCacheEnd; ++it)
2269 it->second->invalidateCache();
2272 void Node::getSubresourceURLs(ListHashSet<KURL>& urls) const
2274 addSubresourceAttributeURLs(urls);
2277 Node* Node::enclosingLinkEventParentOrSelf()
2279 for (Node* node = this; node; node = node->parentOrHostNode()) {
2280 // For imagemaps, the enclosing link node is the associated area element not the image itself.
2281 // So we don't let images be the enclosingLinkNode, even though isLink sometimes returns true
2283 if (node->isLink() && !node->hasTagName(imgTag))
2290 const AtomicString& Node::interfaceName() const
2292 return eventNames().interfaceForNode;
2295 ScriptExecutionContext* Node::scriptExecutionContext() const
2300 Node::InsertionNotificationRequest Node::insertedInto(ContainerNode* insertionPoint)
2302 ASSERT(insertionPoint->inDocument() || isContainerNode());
2303 if (insertionPoint->inDocument())
2304 setFlag(InDocumentFlag);
2305 return InsertionDone;
2308 void Node::removedFrom(ContainerNode* insertionPoint)
2310 ASSERT(insertionPoint->inDocument() || isContainerNode());
2311 if (insertionPoint->inDocument())
2312 clearFlag(InDocumentFlag);
2315 void Node::didMoveToNewDocument(Document* oldDocument)
2317 TreeScopeAdopter::ensureDidMoveToNewDocumentWasCalled(oldDocument);
2319 // FIXME: Event listener types for this node should be set on the new owner document here.
2321 const EventListenerVector& wheelListeners = getEventListeners(eventNames().mousewheelEvent);
2322 for (size_t i = 0; i < wheelListeners.size(); ++i) {
2323 oldDocument->didRemoveWheelEventHandler();
2324 document()->didAddWheelEventHandler();
2327 Vector<AtomicString> touchEventNames = eventNames().touchEventNames();
2328 for (size_t i = 0; i < touchEventNames.size(); ++i) {
2329 const EventListenerVector& listeners = getEventListeners(touchEventNames[i]);
2330 for (size_t j = 0; j < listeners.size(); ++j) {
2331 oldDocument->didRemoveTouchEventHandler();
2332 document()->didAddTouchEventHandler();
2336 #if ENABLE(MUTATION_OBSERVERS)
2337 if (Vector<OwnPtr<MutationObserverRegistration> >* registry = mutationObserverRegistry()) {
2338 for (size_t i = 0; i < registry->size(); ++i) {
2339 document()->addMutationObserverTypes(registry->at(i)->mutationTypes());
2343 if (HashSet<MutationObserverRegistration*>* transientRegistry = transientMutationObserverRegistry()) {
2344 for (HashSet<MutationObserverRegistration*>::iterator iter = transientRegistry->begin(); iter != transientRegistry->end(); ++iter) {
2345 document()->addMutationObserverTypes((*iter)->mutationTypes());
2351 static inline bool tryAddEventListener(Node* targetNode, const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
2353 if (!targetNode->EventTarget::addEventListener(eventType, listener, useCapture))
2356 if (Document* document = targetNode->document()) {
2357 document->addListenerTypeIfNeeded(eventType);
2358 if (eventType == eventNames().mousewheelEvent)
2359 document->didAddWheelEventHandler();
2360 else if (eventNames().isTouchEventType(eventType))
2361 document->didAddTouchEventHandler();
2367 bool Node::addEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
2369 return tryAddEventListener(this, eventType, listener, useCapture);
2372 static inline bool tryRemoveEventListener(Node* targetNode, const AtomicString& eventType, EventListener* listener, bool useCapture)
2374 if (!targetNode->EventTarget::removeEventListener(eventType, listener, useCapture))
2377 // FIXME: Notify Document that the listener has vanished. We need to keep track of a number of
2378 // listeners for each type, not just a bool - see https://bugs.webkit.org/show_bug.cgi?id=33861
2379 if (Document* document = targetNode->document()) {
2380 if (eventType == eventNames().mousewheelEvent)
2381 document->didRemoveWheelEventHandler();
2382 else if (eventNames().isTouchEventType(eventType))
2383 document->didRemoveTouchEventHandler();
2389 bool Node::removeEventListener(const AtomicString& eventType, EventListener* listener, bool useCapture)
2391 return tryRemoveEventListener(this, eventType, listener, useCapture);
2394 EventTargetData* Node::eventTargetData()
2396 return hasRareData() ? rareData()->eventTargetData() : 0;
2399 EventTargetData* Node::ensureEventTargetData()
2401 return ensureRareData()->ensureEventTargetData();
2404 #if ENABLE(MUTATION_OBSERVERS)
2405 Vector<OwnPtr<MutationObserverRegistration> >* Node::mutationObserverRegistry()
2407 return hasRareData() ? rareData()->mutationObserverRegistry() : 0;
2410 HashSet<MutationObserverRegistration*>* Node::transientMutationObserverRegistry()
2412 return hasRareData() ? rareData()->transientMutationObserverRegistry() : 0;
2415 void Node::collectMatchingObserversForMutation(HashMap<MutationObserver*, MutationRecordDeliveryOptions>& observers, Node* fromNode, MutationObserver::MutationType type, const QualifiedName* attributeName)
2417 ASSERT((type == MutationObserver::Attributes && attributeName) || !attributeName);
2418 if (Vector<OwnPtr<MutationObserverRegistration> >* registry = fromNode->mutationObserverRegistry()) {
2419 const size_t size = registry->size();
2420 for (size_t i = 0; i < size; ++i) {
2421 MutationObserverRegistration* registration = registry->at(i).get();
2422 if (registration->shouldReceiveMutationFrom(this, type, attributeName)) {
2423 MutationRecordDeliveryOptions deliveryOptions = registration->deliveryOptions();
2424 HashMap<MutationObserver*, MutationRecordDeliveryOptions>::AddResult result = observers.add(registration->observer(), deliveryOptions);
2425 if (!result.isNewEntry)
2426 result.iterator->second |= deliveryOptions;
2432 if (HashSet<MutationObserverRegistration*>* transientRegistry = fromNode->transientMutationObserverRegistry()) {
2433 for (HashSet<MutationObserverRegistration*>::iterator iter = transientRegistry->begin(); iter != transientRegistry->end(); ++iter) {
2434 MutationObserverRegistration* registration = *iter;
2435 if (registration->shouldReceiveMutationFrom(this, type, attributeName)) {
2436 MutationRecordDeliveryOptions deliveryOptions = registration->deliveryOptions();
2437 HashMap<MutationObserver*, MutationRecordDeliveryOptions>::AddResult result = observers.add(registration->observer(), deliveryOptions);
2438 if (!result.isNewEntry)
2439 result.iterator->second |= deliveryOptions;
2445 void Node::getRegisteredMutationObserversOfType(HashMap<MutationObserver*, MutationRecordDeliveryOptions>& observers, MutationObserver::MutationType type, const QualifiedName* attributeName)
2447 ASSERT((type == MutationObserver::Attributes && attributeName) || !attributeName);
2448 collectMatchingObserversForMutation(observers, this, type, attributeName);
2449 for (Node* node = parentNode(); node; node = node->parentNode())
2450 collectMatchingObserversForMutation(observers, node, type, attributeName);
2453 MutationObserverRegistration* Node::registerMutationObserver(PassRefPtr<MutationObserver> observer)
2455 Vector<OwnPtr<MutationObserverRegistration> >* registry = ensureRareData()->ensureMutationObserverRegistry();
2456 for (size_t i = 0; i < registry->size(); ++i) {
2457 if (registry->at(i)->observer() == observer)
2458 return registry->at(i).get();
2461 OwnPtr<MutationObserverRegistration> registration = MutationObserverRegistration::create(observer, this);
2462 MutationObserverRegistration* registrationPtr = registration.get();
2463 registry->append(registration.release());
2464 return registrationPtr;
2467 void Node::unregisterMutationObserver(MutationObserverRegistration* registration)
2469 Vector<OwnPtr<MutationObserverRegistration> >* registry = mutationObserverRegistry();
2474 size_t index = registry->find(registration);
2475 ASSERT(index != notFound);
2476 if (index == notFound)
2479 registry->remove(index);
2482 void Node::registerTransientMutationObserver(MutationObserverRegistration* registration)
2484 ensureRareData()->ensureTransientMutationObserverRegistry()->add(registration);
2487 void Node::unregisterTransientMutationObserver(MutationObserverRegistration* registration)
2489 HashSet<MutationObserverRegistration*>* transientRegistry = transientMutationObserverRegistry();
2490 ASSERT(transientRegistry);
2491 if (!transientRegistry)
2494 ASSERT(transientRegistry->contains(registration));
2495 transientRegistry->remove(registration);
2498 void Node::notifyMutationObserversNodeWillDetach()
2500 if (!document()->hasMutationObservers())
2503 for (Node* node = parentNode(); node; node = node->parentNode()) {
2504 if (Vector<OwnPtr<MutationObserverRegistration> >* registry = node->mutationObserverRegistry()) {
2505 const size_t size = registry->size();
2506 for (size_t i = 0; i < size; ++i)
2507 registry->at(i)->observedSubtreeNodeWillDetach(this);
2510 if (HashSet<MutationObserverRegistration*>* transientRegistry = node->transientMutationObserverRegistry()) {
2511 for (HashSet<MutationObserverRegistration*>::iterator iter = transientRegistry->begin(); iter != transientRegistry->end(); ++iter)
2512 (*iter)->observedSubtreeNodeWillDetach(this);
2516 #endif // ENABLE(MUTATION_OBSERVERS)
2518 #if ENABLE(STYLE_SCOPED)
2519 bool Node::hasScopedHTMLStyleChild() const
2521 return hasRareData() && rareData()->hasScopedHTMLStyleChild();
2524 size_t Node::numberOfScopedHTMLStyleChildren() const
2526 return hasRareData() ? rareData()->numberOfScopedHTMLStyleChildren() : 0;
2529 void Node::registerScopedHTMLStyleChild()
2531 ensureRareData()->registerScopedHTMLStyleChild();
2534 void Node::unregisterScopedHTMLStyleChild()
2536 ASSERT(hasRareData());
2538 rareData()->unregisterScopedHTMLStyleChild();
2541 bool Node::hasScopedHTMLStyleChild() const
2546 size_t Node::numberOfScopedHTMLStyleChildren() const
2552 void Node::handleLocalEvents(Event* event)
2554 if (!hasRareData() || !rareData()->eventTargetData())
2557 if (disabled() && event->isMouseEvent())
2560 fireEventListeners(event);
2563 void Node::dispatchScopedEvent(PassRefPtr<Event> event)
2565 dispatchScopedEventDispatchMediator(EventDispatchMediator::create(event));
2568 void Node::dispatchScopedEventDispatchMediator(PassRefPtr<EventDispatchMediator> eventDispatchMediator)
2570 EventDispatcher::dispatchScopedEvent(this, eventDispatchMediator);
2573 bool Node::dispatchEvent(PassRefPtr<Event> event)
2575 return EventDispatcher::dispatchEvent(this, EventDispatchMediator::create(event));
2578 void Node::dispatchRegionLayoutUpdateEvent()
2580 ASSERT(!eventDispatchForbidden());
2582 if (!document()->hasListenerType(Document::REGIONLAYOUTUPDATE_LISTENER))
2585 dispatchScopedEvent(UIEvent::create(eventNames().webkitRegionLayoutUpdateEvent, true, true, document()->defaultView(), 0));
2588 void Node::dispatchSubtreeModifiedEvent()
2590 if (isInShadowTree())
2593 ASSERT(!eventDispatchForbidden());
2595 if (!document()->hasListenerType(Document::DOMSUBTREEMODIFIED_LISTENER))
2598 dispatchScopedEvent(MutationEvent::create(eventNames().DOMSubtreeModifiedEvent, true));
2601 void Node::dispatchFocusInEvent(const AtomicString& eventType, PassRefPtr<Node> oldFocusedNode)
2603 ASSERT(!eventDispatchForbidden());
2604 ASSERT(eventType == eventNames().focusinEvent || eventType == eventNames().DOMFocusInEvent);
2605 dispatchScopedEventDispatchMediator(FocusInEventDispatchMediator::create(UIEvent::create(eventType, true, false, document()->defaultView(), 0), oldFocusedNode));
2608 void Node::dispatchFocusOutEvent(const AtomicString& eventType, PassRefPtr<Node> newFocusedNode)
2610 ASSERT(!eventDispatchForbidden());
2611 ASSERT(eventType == eventNames().focusoutEvent || eventType == eventNames().DOMFocusOutEvent);
2612 dispatchScopedEventDispatchMediator(FocusOutEventDispatchMediator::create(UIEvent::create(eventType, true, false, document()->defaultView(), 0), newFocusedNode));
2615 bool Node::dispatchDOMActivateEvent(int detail, PassRefPtr<Event> underlyingEvent)
2617 ASSERT(!eventDispatchForbidden());
2618 RefPtr<UIEvent> event = UIEvent::create(eventNames().DOMActivateEvent, true, true, document()->defaultView(), detail);
2619 event->setUnderlyingEvent(underlyingEvent);
2620 dispatchScopedEvent(event);
2621 return event->defaultHandled();
2624 bool Node::dispatchKeyEvent(const PlatformKeyboardEvent& event)
2626 return EventDispatcher::dispatchEvent(this, KeyboardEventDispatchMediator::create(KeyboardEvent::create(event, document()->defaultView())));
2629 bool Node::dispatchMouseEvent(const PlatformMouseEvent& event, const AtomicString& eventType,
2630 int detail, Node* relatedTarget)
2632 return EventDispatcher::dispatchEvent(this, MouseEventDispatchMediator::create(MouseEvent::create(eventType, document()->defaultView(), event, detail, relatedTarget)));
2635 void Node::dispatchSimulatedClick(PassRefPtr<Event> event, bool sendMouseEvents, bool showPressedLook)
2637 EventDispatcher::dispatchSimulatedClick(this, event, sendMouseEvents, showPressedLook);
2640 bool Node::dispatchBeforeLoadEvent(const String& sourceURL)
2642 if (!document()->hasListenerType(Document::BEFORELOAD_LISTENER))
2645 RefPtr<Node> protector(this);
2646 RefPtr<BeforeLoadEvent> beforeLoadEvent = BeforeLoadEvent::create(sourceURL);
2647 dispatchEvent(beforeLoadEvent.get());
2648 return !beforeLoadEvent->defaultPrevented();
2651 bool Node::dispatchWheelEvent(const PlatformWheelEvent& event)
2653 return EventDispatcher::dispatchEvent(this, WheelEventDispatchMediator::create(event, document()->defaultView()));
2656 void Node::dispatchFocusEvent(PassRefPtr<Node> oldFocusedNode)
2658 if (document()->page())
2659 document()->page()->chrome()->client()->elementDidFocus(this);
2661 EventDispatcher::dispatchEvent(this, FocusEventDispatchMediator::create(oldFocusedNode));
2664 void Node::dispatchBlurEvent(PassRefPtr<Node> newFocusedNode)
2666 if (document()->page())
2667 document()->page()->chrome()->client()->elementDidBlur(this);
2669 EventDispatcher::dispatchEvent(this, BlurEventDispatchMediator::create(newFocusedNode));
2672 void Node::dispatchChangeEvent()
2674 dispatchEvent(Event::create(eventNames().changeEvent, true, false));
2677 void Node::dispatchInputEvent()
2679 dispatchEvent(Event::create(eventNames().inputEvent, true, false));
2682 bool Node::disabled() const
2687 void Node::defaultEventHandler(Event* event)
2689 if (event->target() != this)
2691 const AtomicString& eventType = event->type();
2692 if (eventType == eventNames().keydownEvent || eventType == eventNames().keypressEvent) {
2693 if (event->isKeyboardEvent())
2694 if (Frame* frame = document()->frame())
2695 frame->eventHandler()->defaultKeyboardEventHandler(static_cast<KeyboardEvent*>(event));
2696 } else if (eventType == eventNames().clickEvent) {
2697 int detail = event->isUIEvent() ? static_cast<UIEvent*>(event)->detail() : 0;
2698 if (dispatchDOMActivateEvent(detail, event))
2699 event->setDefaultHandled();
2700 #if ENABLE(CONTEXT_MENUS)
2701 } else if (eventType == eventNames().contextmenuEvent) {
2702 if (Frame* frame = document()->frame())
2703 if (Page* page = frame->page())
2704 page->contextMenuController()->handleContextMenuEvent(event);
2706 } else if (eventType == eventNames().textInputEvent) {
2707 if (event->hasInterface(eventNames().interfaceForTextEvent))
2708 if (Frame* frame = document()->frame())
2709 frame->eventHandler()->defaultTextInputEventHandler(static_cast<TextEvent*>(event));
2710 #if ENABLE(PAN_SCROLLING)
2711 } else if (eventType == eventNames().mousedownEvent && event->isMouseEvent()) {
2712 MouseEvent* mouseEvent = static_cast<MouseEvent*>(event);
2713 if (mouseEvent->button() == MiddleButton) {
2714 if (enclosingLinkEventParentOrSelf())
2717 RenderObject* renderer = this->renderer();
2718 while (renderer && (!renderer->isBox() || !toRenderBox(renderer)->canBeScrolledAndHasScrollableArea()))
2719 renderer = renderer->parent();
2722 if (Frame* frame = document()->frame())
2723 frame->eventHandler()->startPanScrolling(renderer);
2727 } else if (eventType == eventNames().mousewheelEvent && event->hasInterface(eventNames().interfaceForWheelEvent)) {
2728 WheelEvent* wheelEvent = static_cast<WheelEvent*>(event);
2730 // If we don't have a renderer, send the wheel event to the first node we find with a renderer.
2731 // This is needed for <option> and <optgroup> elements so that <select>s get a wheel scroll.
2732 Node* startNode = this;
2733 while (startNode && !startNode->renderer())
2734 startNode = startNode->parentOrHostNode();
2736 if (startNode && startNode->renderer())
2737 if (Frame* frame = document()->frame())
2738 frame->eventHandler()->defaultWheelEventHandler(startNode, wheelEvent);
2739 } else if (event->type() == eventNames().webkitEditableContentChangedEvent) {
2740 dispatchInputEvent();
2744 #if ENABLE(MICRODATA)
2745 DOMSettableTokenList* Node::itemProp()
2747 return ensureRareData()->itemProp();
2750 void Node::setItemProp(const String& value)
2752 ensureRareData()->setItemProp(value);
2755 DOMSettableTokenList* Node::itemRef()
2757 return ensureRareData()->itemRef();
2760 void Node::setItemRef(const String& value)
2762 ensureRareData()->setItemRef(value);
2765 DOMSettableTokenList* Node::itemType()
2767 return ensureRareData()->itemType();
2770 void Node::setItemType(const String& value)
2772 ensureRareData()->setItemType(value);
2777 // It's important not to inline removedLastRef, because we don't want to inline the code to
2778 // delete a Node at each deref call site.
2779 void Node::removedLastRef()
2781 // An explicit check for Document here is better than a virtual function since it is
2782 // faster for non-Document nodes, and because the call to removedLastRef that is inlined
2783 // at all deref call sites is smaller if it's a non-virtual function.
2784 if (isDocumentNode()) {
2785 static_cast<Document*>(this)->removedLastRef();
2789 m_deletionHasBegun = true;
2794 void Node::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
2796 MemoryClassInfo<Node> info(memoryObjectInfo, this, MemoryInstrumentation::DOM);
2797 info.visitBaseClass<TreeShared<Node, ContainerNode> >(this);
2798 info.visitBaseClass<ScriptWrappable>(this);
2799 info.addInstrumentedMember(m_document);
2800 info.addInstrumentedMember(m_next);
2801 info.addInstrumentedMember(m_previous);
2804 } // namespace WebCore
2808 void showTree(const WebCore::Node* node)
2811 node->showTreeForThis();
2814 void showNodePath(const WebCore::Node* node)
2817 node->showNodePathForThis();