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 "ComposedShadowTreeWalker.h"
44 #include "ContainerNodeAlgorithms.h"
45 #include "ContextMenuController.h"
46 #include "DOMImplementation.h"
47 #include "DOMSettableTokenList.h"
49 #include "DocumentFragment.h"
50 #include "DocumentType.h"
52 #include "ElementRareData.h"
53 #include "ElementShadow.h"
55 #include "EventContext.h"
56 #include "EventDispatchMediator.h"
57 #include "EventDispatcher.h"
58 #include "EventException.h"
59 #include "EventHandler.h"
60 #include "EventListener.h"
61 #include "EventNames.h"
62 #include "ExceptionCode.h"
64 #include "FrameView.h"
65 #include "HTMLElement.h"
66 #include "HTMLFrameOwnerElement.h"
67 #include "HTMLNames.h"
68 #include "HTMLStyleElement.h"
69 #include "InspectorCounters.h"
70 #include "KeyboardEvent.h"
71 #include "LabelsNodeList.h"
72 #include "LiveNodeList.h"
74 #include "MouseEvent.h"
75 #include "MutationEvent.h"
76 #include "NameNodeList.h"
77 #include "NamedNodeMap.h"
78 #include "NodeRareData.h"
79 #include "NodeRenderingContext.h"
80 #include "NodeTraversal.h"
82 #include "PlatformMouseEvent.h"
83 #include "PlatformWheelEvent.h"
84 #include "ProcessingInstruction.h"
85 #include "ProgressEvent.h"
86 #include "RadioNodeList.h"
87 #include "RegisteredEventListener.h"
88 #include "RenderBlock.h"
89 #include "RenderBox.h"
90 #include "RenderTextControl.h"
91 #include "RenderView.h"
92 #include "ScopedEventQueue.h"
93 #include "SelectorQuery.h"
95 #include "ShadowRoot.h"
96 #include "StaticNodeList.h"
97 #include "StorageEvent.h"
98 #include "StyleResolver.h"
99 #include "TagNodeList.h"
100 #include "TemplateContentDocumentFragment.h"
102 #include "TextEvent.h"
103 #include "TreeScopeAdopter.h"
105 #include "UIEventWithKeyState.h"
106 #include "UserActionElementSet.h"
107 #include "WebCoreMemoryInstrumentation.h"
108 #include "WheelEvent.h"
109 #include "WindowEventContext.h"
110 #include "XMLNames.h"
111 #include "htmlediting.h"
112 #include <wtf/HashSet.h>
113 #include <wtf/PassOwnPtr.h>
114 #include <wtf/RefCountedLeakCounter.h>
115 #include <wtf/UnusedParam.h>
116 #include <wtf/Vector.h>
117 #include <wtf/text/CString.h>
118 #include <wtf/text/StringBuilder.h>
121 #include "RenderLayer.h"
124 #if ENABLE(GESTURE_EVENTS)
125 #include "GestureEvent.h"
128 #if ENABLE(INSPECTOR)
129 #include "InspectorController.h"
133 #include <runtime/JSGlobalData.h>
136 #if ENABLE(MICRODATA)
137 #include "HTMLPropertiesCollection.h"
138 #include "PropertyNodeList.h"
145 using namespace HTMLNames;
147 bool Node::isSupported(const String& feature, const String& version)
149 return DOMImplementation::hasFeature(feature, version);
152 #if DUMP_NODE_STATISTICS
153 static HashSet<Node*> liveNodeSet;
156 void Node::dumpStatistics()
158 #if DUMP_NODE_STATISTICS
159 size_t nodesWithRareData = 0;
161 size_t elementNodes = 0;
162 size_t attrNodes = 0;
163 size_t textNodes = 0;
164 size_t cdataNodes = 0;
165 size_t commentNodes = 0;
166 size_t entityReferenceNodes = 0;
167 size_t entityNodes = 0;
169 size_t documentNodes = 0;
170 size_t docTypeNodes = 0;
171 size_t fragmentNodes = 0;
172 size_t notationNodes = 0;
173 size_t xpathNSNodes = 0;
174 size_t shadowRootNodes = 0;
176 HashMap<String, size_t> perTagCount;
178 size_t attributes = 0;
179 size_t attributesWithAttr = 0;
180 size_t elementsWithAttributeStorage = 0;
181 size_t elementsWithRareData = 0;
182 size_t elementsWithNamedNodeMap = 0;
184 for (HashSet<Node*>::iterator it = liveNodeSet.begin(); it != liveNodeSet.end(); ++it) {
187 if (node->hasRareData()) {
189 if (node->isElementNode()) {
190 ++elementsWithRareData;
191 if (toElement(node)->hasNamedNodeMap())
192 ++elementsWithNamedNodeMap;
196 switch (node->nodeType()) {
201 Element* element = static_cast<Element*>(node);
202 HashMap<String, size_t>::AddResult result = perTagCount.add(element->tagName(), 1);
203 if (!result.isNewEntry)
204 result.iterator->value++;
206 if (ElementAttributeData* attributeData = element->attributeData()) {
207 attributes += attributeData->length();
208 ++elementsWithAttributeStorage;
209 for (unsigned i = 0; i < attributeData->length(); ++i) {
210 Attribute* attr = attributeData->attributeItem(i);
212 ++attributesWithAttr;
217 case ATTRIBUTE_NODE: {
225 case CDATA_SECTION_NODE: {
233 case ENTITY_REFERENCE_NODE: {
234 ++entityReferenceNodes;
241 case PROCESSING_INSTRUCTION_NODE: {
245 case DOCUMENT_NODE: {
249 case DOCUMENT_TYPE_NODE: {
253 case DOCUMENT_FRAGMENT_NODE: {
254 if (node->isShadowRoot())
260 case NOTATION_NODE: {
264 case XPATH_NAMESPACE_NODE: {
271 printf("Number of Nodes: %d\n\n", liveNodeSet.size());
272 printf("Number of Nodes with RareData: %zu\n\n", nodesWithRareData);
274 printf("NodeType distribution:\n");
275 printf(" Number of Element nodes: %zu\n", elementNodes);
276 printf(" Number of Attribute nodes: %zu\n", attrNodes);
277 printf(" Number of Text nodes: %zu\n", textNodes);
278 printf(" Number of CDATASection nodes: %zu\n", cdataNodes);
279 printf(" Number of Comment nodes: %zu\n", commentNodes);
280 printf(" Number of EntityReference nodes: %zu\n", entityReferenceNodes);
281 printf(" Number of Entity nodes: %zu\n", entityNodes);
282 printf(" Number of ProcessingInstruction nodes: %zu\n", piNodes);
283 printf(" Number of Document nodes: %zu\n", documentNodes);
284 printf(" Number of DocumentType nodes: %zu\n", docTypeNodes);
285 printf(" Number of DocumentFragment nodes: %zu\n", fragmentNodes);
286 printf(" Number of Notation nodes: %zu\n", notationNodes);
287 printf(" Number of XPathNS nodes: %zu\n", xpathNSNodes);
288 printf(" Number of ShadowRoot nodes: %zu\n", shadowRootNodes);
290 printf("Element tag name distibution:\n");
291 for (HashMap<String, size_t>::iterator it = perTagCount.begin(); it != perTagCount.end(); ++it)
292 printf(" Number of <%s> tags: %zu\n", it->key.utf8().data(), it->value);
294 printf("Attributes:\n");
295 printf(" Number of Attributes (non-Node and Node): %zu [%zu]\n", attributes, sizeof(Attribute));
296 printf(" Number of Attributes with an Attr: %zu\n", attributesWithAttr);
297 printf(" Number of Elements with attribute storage: %zu [%zu]\n", elementsWithAttributeStorage, sizeof(ElementAttributeData));
298 printf(" Number of Elements with RareData: %zu\n", elementsWithRareData);
299 printf(" Number of Elements with NamedNodeMap: %zu [%zu]\n", elementsWithNamedNodeMap, sizeof(NamedNodeMap));
303 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, nodeCounter, ("WebCoreNode"));
304 DEFINE_DEBUG_ONLY_GLOBAL(HashSet<Node*>, ignoreSet, );
307 static bool shouldIgnoreLeaks = false;
310 void Node::startIgnoringLeaks()
313 shouldIgnoreLeaks = true;
317 void Node::stopIgnoringLeaks()
320 shouldIgnoreLeaks = false;
324 Node::StyleChange Node::diff(const RenderStyle* s1, const RenderStyle* s2, Document* doc)
326 StyleChange ch = NoInherit;
327 EDisplay display1 = s1 ? s1->display() : NONE;
328 bool fl1 = s1 && s1->hasPseudoStyle(FIRST_LETTER);
329 EDisplay display2 = s2 ? s2->display() : NONE;
330 bool fl2 = s2 && s2->hasPseudoStyle(FIRST_LETTER);
332 // We just detach if a renderer acquires or loses a column-span, since spanning elements
333 // typically won't contain much content.
334 bool colSpan1 = s1 && s1->columnSpan();
335 bool colSpan2 = s2 && s2->columnSpan();
337 bool specifiesColumns1 = s1 && (!s1->hasAutoColumnCount() || !s1->hasAutoColumnWidth());
338 bool specifiesColumns2 = s2 && (!s2->hasAutoColumnCount() || !s2->hasAutoColumnWidth());
340 if (display1 != display2 || fl1 != fl2 || colSpan1 != colSpan2
341 || (specifiesColumns1 != specifiesColumns2 && doc->settings()->regionBasedColumnsEnabled())
342 || (s1 && s2 && !s1->contentDataEquivalent(s2)))
348 else if (s1->inheritedNotEqual(s2))
350 else if (s1->hasExplicitlyInheritedProperties() || s2->hasExplicitlyInheritedProperties())
353 // If the pseudoStyles have changed, we want any StyleChange that is not NoChange
354 // because setStyle will do the right thing with anything else.
355 if (ch == NoChange && s1->hasAnyPublicPseudoStyles()) {
356 for (PseudoId pseudoId = FIRST_PUBLIC_PSEUDOID; ch == NoChange && pseudoId < FIRST_INTERNAL_PSEUDOID; pseudoId = static_cast<PseudoId>(pseudoId + 1)) {
357 if (s1->hasPseudoStyle(pseudoId)) {
358 RenderStyle* ps2 = s2->getCachedPseudoStyle(pseudoId);
362 RenderStyle* ps1 = s1->getCachedPseudoStyle(pseudoId);
363 ch = ps1 && *ps1 == *ps2 ? NoChange : NoInherit;
369 // When text-combine property has been changed, we need to prepare a separate renderer object.
370 // When text-combine is on, we use RenderCombineText, otherwise RenderText.
371 // https://bugs.webkit.org/show_bug.cgi?id=55069
372 if ((s1 && s2) && (s1->hasTextCombine() != s2->hasTextCombine()))
375 // We need to reattach the node, so that it is moved to the correct RenderFlowThread.
376 if ((s1 && s2) && (s1->flowThread() != s2->flowThread()))
379 // When the region thread has changed, we need to prepare a separate render region object.
380 if ((s1 && s2) && (s1->regionThread() != s2->regionThread()))
386 void Node::trackForDebugging()
389 if (shouldIgnoreLeaks)
392 nodeCounter.increment();
395 #if DUMP_NODE_STATISTICS
396 liveNodeSet.add(this);
403 HashSet<Node*>::iterator it = ignoreSet.find(this);
404 if (it != ignoreSet.end())
405 ignoreSet.remove(it);
407 nodeCounter.decrement();
410 #if DUMP_NODE_STATISTICS
411 liveNodeSet.remove(this);
417 if (hasEventTargetData()) {
418 #if ENABLE(TOUCH_EVENT_TRACKING)
420 m_document->didRemoveEventTargetNode(this);
422 clearEventTargetData();
428 Document* doc = m_document;
429 if (AXObjectCache::accessibilityEnabled() && doc && doc->axObjectCacheExists() && !isContainerNode())
430 doc->axObjectCache()->remove(this);
433 m_previous->setNextSibling(0);
435 m_next->setPreviousSibling(0);
440 InspectorCounters::decrementCounter(InspectorCounters::NodeCounter);
443 void Node::setDocument(Document* document)
445 ASSERT(!inDocument() || m_document == document);
446 if (inDocument() || m_document == document)
449 m_document = document;
452 void Node::setTreeScope(TreeScope* scope)
454 ASSERT(!isShadowRoot());
456 if (!hasRareData() && scope->rootNode()->isDocumentNode())
459 ensureRareData()->setTreeScope(scope);
462 NodeRareData* Node::rareData() const
464 ASSERT(hasRareData());
465 return static_cast<NodeRareData*>(m_data.m_rareData);
468 NodeRareData* Node::ensureRareData()
473 NodeRareData* data = createRareData().leakPtr();
475 data->setRenderer(m_data.m_renderer);
476 m_data.m_rareData = data;
477 setFlag(HasRareDataFlag);
481 PassOwnPtr<NodeRareData> Node::createRareData()
483 return adoptPtr(new NodeRareData(documentInternal()));
486 void Node::clearRareData()
488 ASSERT(hasRareData());
490 #if ENABLE(MUTATION_OBSERVERS)
491 ASSERT(!transientMutationObserverRegistry() || transientMutationObserverRegistry()->isEmpty());
494 RenderObject* renderer = m_data.m_rareData->renderer();
495 delete m_data.m_rareData;
496 m_data.m_renderer = renderer;
497 clearFlag(HasRareDataFlag);
505 HTMLInputElement* Node::toInputElement()
507 // If one of the below ASSERTs trigger, you are calling this function
508 // directly or indirectly from a constructor or destructor of this object.
510 ASSERT(!(isHTMLElement() && hasTagName(inputTag)));
514 short Node::tabIndex() const
516 return hasRareData() ? rareData()->tabIndex() : 0;
519 void Node::setTabIndexExplicitly(short i)
521 ensureRareData()->setTabIndexExplicitly(i);
524 void Node::clearTabIndexExplicitly()
526 ensureRareData()->clearTabIndexExplicitly();
529 String Node::nodeValue() const
534 void Node::setNodeValue(const String& /*nodeValue*/, ExceptionCode& ec)
536 // NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly
537 if (isReadOnlyNode()) {
538 ec = NO_MODIFICATION_ALLOWED_ERR;
542 // By default, setting nodeValue has no effect.
545 PassRefPtr<NodeList> Node::childNodes()
547 return ensureRareData()->ensureNodeLists()->ensureChildNodeList(this);
550 Node *Node::lastDescendant() const
552 Node *n = const_cast<Node *>(this);
553 while (n && n->lastChild())
558 Node* Node::firstDescendant() const
560 Node *n = const_cast<Node *>(this);
561 while (n && n->firstChild())
566 bool Node::insertBefore(PassRefPtr<Node> newChild, Node* refChild, ExceptionCode& ec, bool shouldLazyAttach)
568 if (!isContainerNode()) {
569 ec = HIERARCHY_REQUEST_ERR;
572 return toContainerNode(this)->insertBefore(newChild, refChild, ec, shouldLazyAttach);
575 bool Node::replaceChild(PassRefPtr<Node> newChild, Node* oldChild, ExceptionCode& ec, bool shouldLazyAttach)
577 if (!isContainerNode()) {
578 ec = HIERARCHY_REQUEST_ERR;
581 return toContainerNode(this)->replaceChild(newChild, oldChild, ec, shouldLazyAttach);
584 bool Node::removeChild(Node* oldChild, ExceptionCode& ec)
586 if (!isContainerNode()) {
590 return toContainerNode(this)->removeChild(oldChild, ec);
593 bool Node::appendChild(PassRefPtr<Node> newChild, ExceptionCode& ec, bool shouldLazyAttach)
595 if (!isContainerNode()) {
596 ec = HIERARCHY_REQUEST_ERR;
599 return toContainerNode(this)->appendChild(newChild, ec, shouldLazyAttach);
602 void Node::remove(ExceptionCode& ec)
604 if (ContainerNode* parent = parentNode())
605 parent->removeChild(this, ec);
608 void Node::normalize()
610 // Go through the subtree beneath us, normalizing all nodes. This means that
611 // any two adjacent text nodes are merged and any empty text nodes are removed.
613 RefPtr<Node> node = this;
614 while (Node* firstChild = node->firstChild())
617 NodeType type = node->nodeType();
618 if (type == ELEMENT_NODE)
619 static_cast<Element*>(node.get())->normalizeAttributes();
624 if (type != TEXT_NODE) {
625 node = NodeTraversal::nextPostOrder(node.get());
629 RefPtr<Text> text = toText(node.get());
631 // Remove empty text nodes.
632 if (!text->length()) {
633 // Care must be taken to get the next node before removing the current node.
634 node = NodeTraversal::nextPostOrder(node.get());
641 while (Node* nextSibling = node->nextSibling()) {
642 if (nextSibling->nodeType() != TEXT_NODE)
644 RefPtr<Text> nextText = toText(nextSibling);
646 // Remove empty text nodes.
647 if (!nextText->length()) {
649 nextText->remove(ec);
653 // Both non-empty text nodes. Merge them.
654 unsigned offset = text->length();
656 text->appendData(nextText->data(), ec);
657 document()->textNodesMerged(nextText.get(), offset);
658 nextText->remove(ec);
661 node = NodeTraversal::nextPostOrder(node.get());
665 const AtomicString& Node::virtualPrefix() const
667 // For nodes other than elements and attributes, the prefix is always null
671 void Node::setPrefix(const AtomicString& /*prefix*/, ExceptionCode& ec)
673 // The spec says that for nodes other than elements and attributes, prefix is always null.
674 // It does not say what to do when the user tries to set the prefix on another type of
675 // node, however Mozilla throws a NAMESPACE_ERR exception.
679 const AtomicString& Node::virtualLocalName() const
684 const AtomicString& Node::virtualNamespaceURI() const
689 bool Node::isContentEditable(UserSelectAllTreatment treatment)
691 document()->updateStyleIfNeeded();
692 return rendererIsEditable(Editable, treatment);
695 bool Node::isContentRichlyEditable()
697 document()->updateStyleIfNeeded();
698 return rendererIsEditable(RichlyEditable, UserSelectAllIsAlwaysNonEditable);
703 #if ENABLE(INSPECTOR)
704 if (document() && document()->page())
705 document()->page()->inspectorController()->inspect(this);
709 bool Node::rendererIsEditable(EditableLevel editableLevel, UserSelectAllTreatment treatment) const
711 if (document()->frame() && document()->frame()->page() && document()->frame()->page()->isEditable() && !containingShadowRoot())
714 if (isPseudoElement())
717 // Ideally we'd call ASSERT(!needsStyleRecalc()) here, but
718 // ContainerNode::setFocus() calls setNeedsStyleRecalc(), so the assertion
719 // would fire in the middle of Document::setFocusedNode().
721 for (const Node* node = this; node; node = node->parentNode()) {
722 if ((node->isHTMLElement() || node->isDocumentNode()) && node->renderer()) {
723 #if ENABLE(USERSELECT_ALL)
724 // Elements with user-select: all style are considered atomic
725 // therefore non editable.
726 if (node->renderer()->style()->userSelect() == SELECT_ALL && treatment == UserSelectAllIsAlwaysNonEditable)
729 UNUSED_PARAM(treatment);
731 switch (node->renderer()->style()->userModify()) {
736 case READ_WRITE_PLAINTEXT_ONLY:
737 return editableLevel != RichlyEditable;
739 ASSERT_NOT_REACHED();
747 bool Node::isEditableToAccessibility(EditableLevel editableLevel) const
749 if (rendererIsEditable(editableLevel))
752 // FIXME: Respect editableLevel for ARIA editable elements.
753 if (editableLevel == RichlyEditable)
757 ASSERT(AXObjectCache::accessibilityEnabled());
758 ASSERT(document()->axObjectCacheExists());
760 if (document() && AXObjectCache::accessibilityEnabled() && document()->axObjectCacheExists())
761 return document()->axObjectCache()->rootAXEditableElement(this);
766 bool Node::shouldUseInputMethod()
768 return isContentEditable(UserSelectAllIsAlwaysNonEditable);
771 RenderBox* Node::renderBox() const
773 RenderObject* renderer = this->renderer();
774 return renderer && renderer->isBox() ? toRenderBox(renderer) : 0;
777 RenderBoxModelObject* Node::renderBoxModelObject() const
779 RenderObject* renderer = this->renderer();
780 return renderer && renderer->isBoxModelObject() ? toRenderBoxModelObject(renderer) : 0;
783 LayoutRect Node::boundingBox() const
786 return renderer()->absoluteBoundingBoxRect();
790 LayoutRect Node::renderRect(bool* isReplaced)
792 RenderObject* hitRenderer = this->renderer();
794 RenderObject* renderer = hitRenderer;
795 while (renderer && !renderer->isBody() && !renderer->isRoot()) {
796 if (renderer->isRenderBlock() || renderer->isInlineBlockOrInlineTable() || renderer->isReplaced()) {
797 *isReplaced = renderer->isReplaced();
798 return renderer->absoluteBoundingBoxRect();
800 renderer = renderer->parent();
805 bool Node::hasNonEmptyBoundingBox() const
807 // Before calling absoluteRects, check for the common case where the renderer
808 // is non-empty, since this is a faster check and almost always returns true.
809 RenderBoxModelObject* box = renderBoxModelObject();
812 if (!box->borderBoundingBox().isEmpty())
815 Vector<IntRect> rects;
816 FloatPoint absPos = renderer()->localToAbsolute();
817 renderer()->absoluteRects(rects, flooredLayoutPoint(absPos));
818 size_t n = rects.size();
819 for (size_t i = 0; i < n; ++i)
820 if (!rects[i].isEmpty())
826 inline static ShadowRoot* oldestShadowRootFor(const Node* node)
828 if (!node->isElementNode())
830 if (ElementShadow* shadow = toElement(node)->shadow())
831 return shadow->oldestShadowRoot();
835 inline void Node::setStyleChange(StyleChangeType changeType)
837 m_nodeFlags = (m_nodeFlags & ~StyleChangeMask) | changeType;
840 inline void Node::markAncestorsWithChildNeedsStyleRecalc()
842 for (ContainerNode* p = parentOrHostNode(); p && !p->childNeedsStyleRecalc(); p = p->parentOrHostNode())
843 p->setChildNeedsStyleRecalc();
845 if (document()->childNeedsStyleRecalc())
846 document()->scheduleStyleRecalc();
849 void Node::refEventTarget()
854 void Node::derefEventTarget()
859 void Node::setNeedsStyleRecalc(StyleChangeType changeType)
861 ASSERT(changeType != NoStyleChange);
862 if (!attached()) // changed compared to what?
865 StyleChangeType existingChangeType = styleChangeType();
866 if (changeType > existingChangeType)
867 setStyleChange(changeType);
869 if (existingChangeType == NoStyleChange)
870 markAncestorsWithChildNeedsStyleRecalc();
873 void Node::lazyAttach(ShouldSetAttached shouldSetAttached)
875 for (Node* n = this; n; n = NodeTraversal::next(n, this)) {
876 if (n->hasChildNodes())
877 n->setChildNeedsStyleRecalc();
878 n->setStyleChange(FullStyleChange);
879 if (shouldSetAttached == SetAttached)
882 markAncestorsWithChildNeedsStyleRecalc();
885 bool Node::supportsFocus() const
887 return hasRareData() && rareData()->tabIndexSetExplicitly();
890 bool Node::isFocusable() const
892 if (!inDocument() || !supportsFocus())
895 // Elements in canvas fallback content are not rendered, but they are allowed to be
896 // focusable as long as their canvas is displayed and visible.
897 if (isElementNode() && toElement(this)->isInCanvasSubtree()) {
898 const Element* e = toElement(this);
899 while (e && !e->hasLocalName(canvasTag))
900 e = e->parentElement();
902 return e->renderer() && e->renderer()->style()->visibility() == VISIBLE;
906 ASSERT(!renderer()->needsLayout());
908 // If the node is in a display:none tree it might say it needs style recalc but
909 // the whole document is actually up to date.
910 ASSERT(!document()->childNeedsStyleRecalc());
912 // FIXME: Even if we are not visible, we might have a child that is visible.
913 // Hyatt wants to fix that some day with a "has visible content" flag or the like.
914 if (!renderer() || renderer()->style()->visibility() != VISIBLE)
920 bool Node::isTreeScope() const
922 return treeScope()->rootNode() == this;
925 bool Node::isKeyboardFocusable(KeyboardEvent*) const
927 return isFocusable() && tabIndex() >= 0;
930 bool Node::isMouseFocusable() const
932 return isFocusable();
935 Node* Node::focusDelegate()
940 unsigned Node::nodeIndex() const
942 Node *_tempNode = previousSibling();
944 for ( count=0; _tempNode; count++ )
945 _tempNode = _tempNode->previousSibling();
949 template<unsigned type>
950 bool shouldInvalidateNodeListCachesForAttr(const unsigned nodeListCounts[], const QualifiedName& attrName)
952 if (nodeListCounts[type] && LiveNodeListBase::shouldInvalidateTypeOnAttributeChange(static_cast<NodeListInvalidationType>(type), attrName))
954 return shouldInvalidateNodeListCachesForAttr<type + 1>(nodeListCounts, attrName);
958 bool shouldInvalidateNodeListCachesForAttr<numNodeListInvalidationTypes>(const unsigned[], const QualifiedName&)
963 bool Document::shouldInvalidateNodeListCaches(const QualifiedName* attrName) const
966 return shouldInvalidateNodeListCachesForAttr<DoNotInvalidateOnAttributeChanges + 1>(m_nodeListCounts, *attrName);
968 for (int type = 0; type < numNodeListInvalidationTypes; type++) {
969 if (m_nodeListCounts[type])
976 void Document::invalidateNodeListCaches(const QualifiedName* attrName)
978 HashSet<LiveNodeListBase*>::iterator end = m_listsInvalidatedAtDocument.end();
979 for (HashSet<LiveNodeListBase*>::iterator it = m_listsInvalidatedAtDocument.begin(); it != end; ++it)
980 (*it)->invalidateCache(attrName);
983 void Node::invalidateNodeListCachesInAncestors(const QualifiedName* attrName, Element* attributeOwnerElement)
985 if (hasRareData() && (!attrName || isAttributeNode())) {
986 if (NodeListsNodeData* lists = rareData()->nodeLists())
987 lists->clearChildNodeListCache();
990 // Modifications to attributes that are not associated with an Element can't invalidate NodeList caches.
991 if (attrName && !attributeOwnerElement)
994 if (!document()->shouldInvalidateNodeListCaches(attrName))
997 document()->invalidateNodeListCaches(attrName);
999 for (Node* node = this; node; node = node->parentNode()) {
1000 if (!node->hasRareData())
1002 NodeRareData* data = node->rareData();
1003 if (data->nodeLists())
1004 data->nodeLists()->invalidateCaches(attrName);
1008 NodeListsNodeData* Node::nodeLists()
1010 return hasRareData() ? rareData()->nodeLists() : 0;
1013 void Node::checkSetPrefix(const AtomicString& prefix, ExceptionCode& ec)
1015 // Perform error checking as required by spec for setting Node.prefix. Used by
1016 // Element::setPrefix() and Attr::setPrefix()
1018 if (!prefix.isEmpty() && !Document::isValidName(prefix)) {
1019 ec = INVALID_CHARACTER_ERR;
1023 if (isReadOnlyNode()) {
1024 ec = NO_MODIFICATION_ALLOWED_ERR;
1028 // FIXME: Raise NAMESPACE_ERR if prefix is malformed per the Namespaces in XML specification.
1030 const AtomicString& nodeNamespaceURI = namespaceURI();
1031 if ((nodeNamespaceURI.isEmpty() && !prefix.isEmpty())
1032 || (prefix == xmlAtom && nodeNamespaceURI != XMLNames::xmlNamespaceURI)) {
1036 // Attribute-specific checks are in Attr::setPrefix().
1039 bool Node::isDescendantOf(const Node *other) const
1041 // Return true if other is an ancestor of this, otherwise false
1042 if (!other || !other->hasChildNodes() || inDocument() != other->inDocument())
1044 if (other->isDocumentNode())
1045 return document() == other && !isDocumentNode() && inDocument();
1046 for (const ContainerNode* n = parentNode(); n; n = n->parentNode()) {
1053 bool Node::contains(const Node* node) const
1057 return this == node || node->isDescendantOf(this);
1060 bool Node::containsIncludingShadowDOM(const Node* node) const
1062 for (; node; node = node->parentOrHostNode()) {
1069 bool Node::containsIncludingHostElements(const Node* node) const
1071 #if ENABLE(TEMPLATE_ELEMENT)
1075 if (node->isDocumentFragment() && static_cast<const DocumentFragment*>(node)->isTemplateContent())
1076 node = static_cast<const TemplateContentDocumentFragment*>(node)->host();
1078 node = node->parentOrHostNode();
1082 return containsIncludingShadowDOM(node);
1088 ASSERT(!attached());
1089 ASSERT(!renderer() || (renderer()->style() && renderer()->parent()));
1091 // FIXME: This is O(N^2) for the innerHTML case, where all children are replaced at once (and not attached).
1092 // If this node got a renderer it may be the previousRenderer() of sibling text nodes and thus affect the
1093 // result of Text::textRendererIsNeeded() for those nodes.
1095 for (Node* next = nextSibling(); next; next = next->nextSibling()) {
1096 if (next->renderer())
1098 if (!next->attached())
1099 break; // Assume this means none of the following siblings are attached.
1100 if (next->isTextNode())
1101 toText(next)->createTextRendererIfNeeded();
1106 clearNeedsStyleRecalc();
1108 Document* doc = m_document;
1109 if (AXObjectCache::accessibilityEnabled() && doc && doc->axObjectCacheExists())
1110 doc->axObjectCache()->updateCacheAfterNodeIsAttached(this);
1114 static Node* detachingNode;
1116 bool Node::inDetach() const
1118 return detachingNode == this;
1125 ASSERT(!detachingNode);
1126 detachingNode = this;
1130 renderer()->destroyAndCleanupAnonymousWrappers();
1132 for (Node* node = this; node; node = NodeTraversal::next(node, this)) {
1133 RenderObject* renderer = node->renderer();
1134 // RenderFlowThread and the top layer remove elements from the regular tree
1135 // hierarchy. They will be cleaned up when we call detach on them.
1136 #if ENABLE(DIALOG_ELEMENT)
1137 ASSERT(!renderer || renderer->inRenderFlowThread() || (renderer->enclosingLayer()->isInTopLayerSubtree()));
1139 ASSERT(!renderer || renderer->inRenderFlowThread());
1145 ASSERT(!renderer());
1147 Document* doc = document();
1148 if (isUserActionElement()) {
1150 doc->hoveredNodeDetached(this);
1151 if (inActiveChain())
1152 doc->activeChainNodeDetached(this);
1153 doc->userActionElements().didDetach(this);
1156 clearFlag(IsAttachedFlag);
1163 // FIXME: This code is used by editing. Seems like it could move over there and not pollute Node.
1164 Node *Node::previousNodeConsideringAtomicNodes() const
1166 if (previousSibling()) {
1167 Node *n = previousSibling();
1168 while (!isAtomicNode(n) && n->lastChild())
1172 else if (parentNode()) {
1173 return parentNode();
1180 Node *Node::nextNodeConsideringAtomicNodes() const
1182 if (!isAtomicNode(this) && firstChild())
1183 return firstChild();
1185 return nextSibling();
1186 const Node *n = this;
1187 while (n && !n->nextSibling())
1188 n = n->parentNode();
1190 return n->nextSibling();
1194 Node *Node::previousLeafNode() const
1196 Node *node = previousNodeConsideringAtomicNodes();
1198 if (isAtomicNode(node))
1200 node = node->previousNodeConsideringAtomicNodes();
1205 Node *Node::nextLeafNode() const
1207 Node *node = nextNodeConsideringAtomicNodes();
1209 if (isAtomicNode(node))
1211 node = node->nextNodeConsideringAtomicNodes();
1216 ContainerNode* Node::parentNodeForRenderingAndStyle()
1218 return NodeRenderingContext(this).parentNodeForRenderingAndStyle();
1221 RenderStyle* Node::virtualComputedStyle(PseudoId pseudoElementSpecifier)
1223 return parentOrHostNode() ? parentOrHostNode()->computedStyle(pseudoElementSpecifier) : 0;
1226 int Node::maxCharacterOffset() const
1228 ASSERT_NOT_REACHED();
1232 // FIXME: Shouldn't these functions be in the editing code? Code that asks questions about HTML in the core DOM class
1233 // is obviously misplaced.
1234 bool Node::canStartSelection() const
1236 if (rendererIsEditable())
1240 RenderStyle* style = renderer()->style();
1241 // We allow selections to begin within an element that has -webkit-user-select: none set,
1242 // but if the element is draggable then dragging should take priority over selection.
1243 if (style->userDrag() == DRAG_ELEMENT && style->userSelect() == SELECT_NONE)
1246 return parentOrHostNode() ? parentOrHostNode()->canStartSelection() : true;
1249 Element* Node::shadowHost() const
1251 if (ShadowRoot* root = containingShadowRoot())
1252 return root->host();
1256 Node* Node::shadowAncestorNode() const
1258 if (ShadowRoot* root = containingShadowRoot())
1259 return root->host();
1261 return const_cast<Node*>(this);
1264 ShadowRoot* Node::containingShadowRoot() const
1266 Node* root = const_cast<Node*>(this);
1268 if (root->isShadowRoot())
1269 return toShadowRoot(root);
1270 root = root->parentNodeGuaranteedHostFree();
1275 Node* Node::nonBoundaryShadowTreeRootNode()
1277 ASSERT(!isShadowRoot());
1280 if (root->isShadowRoot())
1282 Node* parent = root->parentNodeGuaranteedHostFree();
1283 if (parent && parent->isShadowRoot())
1290 ContainerNode* Node::nonShadowBoundaryParentNode() const
1292 ContainerNode* parent = parentNode();
1293 return parent && !parent->isShadowRoot() ? parent : 0;
1296 Element* Node::parentOrHostElement() const
1298 ContainerNode* parent = parentOrHostNode();
1302 if (parent->isShadowRoot())
1303 return toShadowRoot(parent)->host();
1305 if (!parent->isElementNode())
1308 return toElement(parent);
1311 bool Node::needsShadowTreeWalkerSlow() const
1313 return (isShadowRoot() || (isElementNode() && (isInsertionPoint() || isPseudoElement() || toElement(this)->hasPseudoElements() || toElement(this)->shadow())));
1316 bool Node::isBlockFlow() const
1318 return renderer() && renderer()->isBlockFlow();
1321 Element *Node::enclosingBlockFlowElement() const
1323 Node *n = const_cast<Node *>(this);
1325 return static_cast<Element *>(n);
1328 n = n->parentNode();
1331 if (n->isBlockFlow() || n->hasTagName(bodyTag))
1332 return static_cast<Element *>(n);
1337 bool Node::isRootEditableElement() const
1339 return rendererIsEditable() && isElementNode() && (!parentNode() || !parentNode()->rendererIsEditable()
1340 || !parentNode()->isElementNode() || hasTagName(bodyTag));
1343 Element* Node::rootEditableElement(EditableType editableType) const
1345 if (editableType == HasEditableAXRole)
1346 return const_cast<Element*>(document()->axObjectCache()->rootAXEditableElement(this));
1348 return rootEditableElement();
1351 Element* Node::rootEditableElement() const
1353 Element* result = 0;
1354 for (Node* n = const_cast<Node*>(this); n && n->rendererIsEditable(); n = n->parentNode()) {
1355 if (n->isElementNode())
1356 result = static_cast<Element*>(n);
1357 if (n->hasTagName(bodyTag))
1363 bool Node::inSameContainingBlockFlowElement(Node *n)
1365 return n ? enclosingBlockFlowElement() == n->enclosingBlockFlowElement() : false;
1368 // FIXME: End of obviously misplaced HTML editing functions. Try to move these out of Node.
1370 PassRefPtr<NodeList> Node::getElementsByTagName(const AtomicString& localName)
1372 if (localName.isNull())
1375 if (document()->isHTMLDocument())
1376 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLTagNodeList>(this, HTMLTagNodeListType, localName);
1377 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<TagNodeList>(this, TagNodeListType, localName);
1380 PassRefPtr<NodeList> Node::getElementsByTagNameNS(const AtomicString& namespaceURI, const AtomicString& localName)
1382 if (localName.isNull())
1385 if (namespaceURI == starAtom)
1386 return getElementsByTagName(localName);
1388 return ensureRareData()->ensureNodeLists()->addCacheWithQualifiedName(this, namespaceURI.isEmpty() ? nullAtom : namespaceURI, localName);
1391 PassRefPtr<NodeList> Node::getElementsByName(const String& elementName)
1393 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<NameNodeList>(this, NameNodeListType, elementName);
1396 PassRefPtr<NodeList> Node::getElementsByClassName(const String& classNames)
1398 return ensureRareData()->ensureNodeLists()->addCacheWithName<ClassNodeList>(this, ClassNodeListType, classNames);
1401 PassRefPtr<RadioNodeList> Node::radioNodeList(const AtomicString& name)
1403 ASSERT(hasTagName(formTag) || hasTagName(fieldsetTag));
1404 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<RadioNodeList>(this, RadioNodeListType, name);
1407 PassRefPtr<Element> Node::querySelector(const AtomicString& selectors, ExceptionCode& ec)
1409 if (selectors.isEmpty()) {
1414 SelectorQuery* selectorQuery = document()->selectorQueryCache()->add(selectors, document(), ec);
1417 return selectorQuery->queryFirst(this);
1420 PassRefPtr<NodeList> Node::querySelectorAll(const AtomicString& selectors, ExceptionCode& ec)
1422 if (selectors.isEmpty()) {
1427 SelectorQuery* selectorQuery = document()->selectorQueryCache()->add(selectors, document(), ec);
1430 return selectorQuery->queryAll(this);
1433 Document *Node::ownerDocument() const
1435 Document *doc = document();
1436 return doc == this ? 0 : doc;
1439 KURL Node::baseURI() const
1441 return parentNode() ? parentNode()->baseURI() : KURL();
1444 bool Node::isEqualNode(Node* other) const
1449 NodeType nodeType = this->nodeType();
1450 if (nodeType != other->nodeType())
1453 if (nodeName() != other->nodeName())
1456 if (localName() != other->localName())
1459 if (namespaceURI() != other->namespaceURI())
1462 if (prefix() != other->prefix())
1465 if (nodeValue() != other->nodeValue())
1468 if (isElementNode() && !toElement(this)->hasEquivalentAttributes(toElement(other)))
1471 Node* child = firstChild();
1472 Node* otherChild = other->firstChild();
1475 if (!child->isEqualNode(otherChild))
1478 child = child->nextSibling();
1479 otherChild = otherChild->nextSibling();
1485 if (nodeType == DOCUMENT_TYPE_NODE) {
1486 const DocumentType* documentTypeThis = static_cast<const DocumentType*>(this);
1487 const DocumentType* documentTypeOther = static_cast<const DocumentType*>(other);
1489 if (documentTypeThis->publicId() != documentTypeOther->publicId())
1492 if (documentTypeThis->systemId() != documentTypeOther->systemId())
1495 if (documentTypeThis->internalSubset() != documentTypeOther->internalSubset())
1498 // FIXME: We don't compare entities or notations because currently both are always empty.
1504 bool Node::isDefaultNamespace(const AtomicString& namespaceURIMaybeEmpty) const
1506 const AtomicString& namespaceURI = namespaceURIMaybeEmpty.isEmpty() ? nullAtom : namespaceURIMaybeEmpty;
1508 switch (nodeType()) {
1509 case ELEMENT_NODE: {
1510 const Element* elem = static_cast<const Element*>(this);
1512 if (elem->prefix().isNull())
1513 return elem->namespaceURI() == namespaceURI;
1515 if (elem->hasAttributes()) {
1516 for (unsigned i = 0; i < elem->attributeCount(); i++) {
1517 const Attribute* attr = elem->attributeItem(i);
1519 if (attr->localName() == xmlnsAtom)
1520 return attr->value() == namespaceURI;
1524 if (Element* ancestor = ancestorElement())
1525 return ancestor->isDefaultNamespace(namespaceURI);
1530 if (Element* de = static_cast<const Document*>(this)->documentElement())
1531 return de->isDefaultNamespace(namespaceURI);
1535 case DOCUMENT_TYPE_NODE:
1536 case DOCUMENT_FRAGMENT_NODE:
1538 case ATTRIBUTE_NODE: {
1539 const Attr* attr = static_cast<const Attr*>(this);
1540 if (attr->ownerElement())
1541 return attr->ownerElement()->isDefaultNamespace(namespaceURI);
1545 if (Element* ancestor = ancestorElement())
1546 return ancestor->isDefaultNamespace(namespaceURI);
1551 String Node::lookupPrefix(const AtomicString &namespaceURI) const
1553 // Implemented according to
1554 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/namespaces-algorithms.html#lookupNamespacePrefixAlgo
1556 if (namespaceURI.isEmpty())
1559 switch (nodeType()) {
1561 return lookupNamespacePrefix(namespaceURI, static_cast<const Element *>(this));
1563 if (Element* de = static_cast<const Document*>(this)->documentElement())
1564 return de->lookupPrefix(namespaceURI);
1568 case DOCUMENT_FRAGMENT_NODE:
1569 case DOCUMENT_TYPE_NODE:
1571 case ATTRIBUTE_NODE: {
1572 const Attr *attr = static_cast<const Attr *>(this);
1573 if (attr->ownerElement())
1574 return attr->ownerElement()->lookupPrefix(namespaceURI);
1578 if (Element* ancestor = ancestorElement())
1579 return ancestor->lookupPrefix(namespaceURI);
1584 String Node::lookupNamespaceURI(const String &prefix) const
1586 // Implemented according to
1587 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/namespaces-algorithms.html#lookupNamespaceURIAlgo
1589 if (!prefix.isNull() && prefix.isEmpty())
1592 switch (nodeType()) {
1593 case ELEMENT_NODE: {
1594 const Element *elem = static_cast<const Element *>(this);
1596 if (!elem->namespaceURI().isNull() && elem->prefix() == prefix)
1597 return elem->namespaceURI();
1599 if (elem->hasAttributes()) {
1600 for (unsigned i = 0; i < elem->attributeCount(); i++) {
1601 const Attribute* attr = elem->attributeItem(i);
1603 if (attr->prefix() == xmlnsAtom && attr->localName() == prefix) {
1604 if (!attr->value().isEmpty())
1605 return attr->value();
1608 } else if (attr->localName() == xmlnsAtom && prefix.isNull()) {
1609 if (!attr->value().isEmpty())
1610 return attr->value();
1616 if (Element* ancestor = ancestorElement())
1617 return ancestor->lookupNamespaceURI(prefix);
1621 if (Element* de = static_cast<const Document*>(this)->documentElement())
1622 return de->lookupNamespaceURI(prefix);
1626 case DOCUMENT_TYPE_NODE:
1627 case DOCUMENT_FRAGMENT_NODE:
1629 case ATTRIBUTE_NODE: {
1630 const Attr *attr = static_cast<const Attr *>(this);
1632 if (attr->ownerElement())
1633 return attr->ownerElement()->lookupNamespaceURI(prefix);
1638 if (Element* ancestor = ancestorElement())
1639 return ancestor->lookupNamespaceURI(prefix);
1644 String Node::lookupNamespacePrefix(const AtomicString &_namespaceURI, const Element *originalElement) const
1646 if (_namespaceURI.isNull())
1649 if (originalElement->lookupNamespaceURI(prefix()) == _namespaceURI)
1652 ASSERT(isElementNode());
1653 const Element* thisElement = toElement(this);
1654 if (thisElement->hasAttributes()) {
1655 for (unsigned i = 0; i < thisElement->attributeCount(); i++) {
1656 const Attribute* attr = thisElement->attributeItem(i);
1658 if (attr->prefix() == xmlnsAtom && attr->value() == _namespaceURI
1659 && originalElement->lookupNamespaceURI(attr->localName()) == _namespaceURI)
1660 return attr->localName();
1664 if (Element* ancestor = ancestorElement())
1665 return ancestor->lookupNamespacePrefix(_namespaceURI, originalElement);
1669 static void appendTextContent(const Node* node, bool convertBRsToNewlines, bool& isNullString, StringBuilder& content)
1671 switch (node->nodeType()) {
1672 case Node::TEXT_NODE:
1673 case Node::CDATA_SECTION_NODE:
1674 case Node::COMMENT_NODE:
1675 isNullString = false;
1676 content.append(static_cast<const CharacterData*>(node)->data());
1679 case Node::PROCESSING_INSTRUCTION_NODE:
1680 isNullString = false;
1681 content.append(static_cast<const ProcessingInstruction*>(node)->data());
1684 case Node::ELEMENT_NODE:
1685 if (node->hasTagName(brTag) && convertBRsToNewlines) {
1686 isNullString = false;
1687 content.append('\n');
1691 case Node::ATTRIBUTE_NODE:
1692 case Node::ENTITY_NODE:
1693 case Node::ENTITY_REFERENCE_NODE:
1694 case Node::DOCUMENT_FRAGMENT_NODE:
1695 isNullString = false;
1696 for (Node* child = node->firstChild(); child; child = child->nextSibling()) {
1697 if (child->nodeType() == Node::COMMENT_NODE || child->nodeType() == Node::PROCESSING_INSTRUCTION_NODE)
1699 appendTextContent(child, convertBRsToNewlines, isNullString, content);
1703 case Node::DOCUMENT_NODE:
1704 case Node::DOCUMENT_TYPE_NODE:
1705 case Node::NOTATION_NODE:
1706 case Node::XPATH_NAMESPACE_NODE:
1711 String Node::textContent(bool convertBRsToNewlines) const
1713 StringBuilder content;
1714 bool isNullString = true;
1715 appendTextContent(this, convertBRsToNewlines, isNullString, content);
1716 return isNullString ? String() : content.toString();
1719 void Node::setTextContent(const String& text, ExceptionCode& ec)
1721 switch (nodeType()) {
1723 case CDATA_SECTION_NODE:
1725 case PROCESSING_INSTRUCTION_NODE:
1726 setNodeValue(text, ec);
1729 case ATTRIBUTE_NODE:
1731 case ENTITY_REFERENCE_NODE:
1732 case DOCUMENT_FRAGMENT_NODE: {
1733 RefPtr<ContainerNode> container = toContainerNode(this);
1734 #if ENABLE(MUTATION_OBSERVERS)
1735 ChildListMutationScope mutation(this);
1737 container->removeChildren();
1738 if (!text.isEmpty())
1739 container->appendChild(document()->createTextNode(text), ec);
1743 case DOCUMENT_TYPE_NODE:
1745 case XPATH_NAMESPACE_NODE:
1749 ASSERT_NOT_REACHED();
1752 Element* Node::ancestorElement() const
1754 // In theory, there can be EntityReference nodes between elements, but this is currently not supported.
1755 for (ContainerNode* n = parentNode(); n; n = n->parentNode()) {
1756 if (n->isElementNode())
1757 return static_cast<Element*>(n);
1762 bool Node::offsetInCharacters() const
1767 unsigned short Node::compareDocumentPosition(Node* otherNode)
1769 // It is not clear what should be done if |otherNode| is 0.
1771 return DOCUMENT_POSITION_DISCONNECTED;
1773 if (otherNode == this)
1774 return DOCUMENT_POSITION_EQUIVALENT;
1776 Attr* attr1 = nodeType() == ATTRIBUTE_NODE ? static_cast<Attr*>(this) : 0;
1777 Attr* attr2 = otherNode->nodeType() == ATTRIBUTE_NODE ? static_cast<Attr*>(otherNode) : 0;
1779 Node* start1 = attr1 ? attr1->ownerElement() : this;
1780 Node* start2 = attr2 ? attr2->ownerElement() : otherNode;
1782 // If either of start1 or start2 is null, then we are disconnected, since one of the nodes is
1783 // an orphaned attribute node.
1784 if (!start1 || !start2)
1785 return DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC;
1787 Vector<Node*, 16> chain1;
1788 Vector<Node*, 16> chain2;
1790 chain1.append(attr1);
1792 chain2.append(attr2);
1794 if (attr1 && attr2 && start1 == start2 && start1) {
1795 // We are comparing two attributes on the same node. Crawl our attribute map and see which one we hit first.
1796 Element* owner1 = attr1->ownerElement();
1797 owner1->updatedAttributeData(); // Force update invalid attributes.
1798 unsigned length = owner1->attributeCount();
1799 for (unsigned i = 0; i < length; ++i) {
1800 // If neither of the two determining nodes is a child node and nodeType is the same for both determining nodes, then an
1801 // implementation-dependent order between the determining nodes is returned. This order is stable as long as no nodes of
1802 // the same nodeType are inserted into or removed from the direct container. This would be the case, for example,
1803 // when comparing two attributes of the same element, and inserting or removing additional attributes might change
1804 // the order between existing attributes.
1805 const Attribute* attribute = owner1->attributeItem(i);
1806 if (attr1->qualifiedName() == attribute->name())
1807 return DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | DOCUMENT_POSITION_FOLLOWING;
1808 if (attr2->qualifiedName() == attribute->name())
1809 return DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | DOCUMENT_POSITION_PRECEDING;
1812 ASSERT_NOT_REACHED();
1813 return DOCUMENT_POSITION_DISCONNECTED;
1816 // If one node is in the document and the other is not, we must be disconnected.
1817 // If the nodes have different owning documents, they must be disconnected. Note that we avoid
1818 // comparing Attr nodes here, since they return false from inDocument() all the time (which seems like a bug).
1819 if (start1->inDocument() != start2->inDocument() ||
1820 start1->treeScope() != start2->treeScope())
1821 return DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC;
1823 // We need to find a common ancestor container, and then compare the indices of the two immediate children.
1825 for (current = start1; current; current = current->parentNode())
1826 chain1.append(current);
1827 for (current = start2; current; current = current->parentNode())
1828 chain2.append(current);
1830 // Walk the two chains backwards and look for the first difference.
1831 unsigned index1 = chain1.size();
1832 unsigned index2 = chain2.size();
1833 for (unsigned i = min(index1, index2); i; --i) {
1834 Node* child1 = chain1[--index1];
1835 Node* child2 = chain2[--index2];
1836 if (child1 != child2) {
1837 // If one of the children is an attribute, it wins.
1838 if (child1->nodeType() == ATTRIBUTE_NODE)
1839 return DOCUMENT_POSITION_FOLLOWING;
1840 if (child2->nodeType() == ATTRIBUTE_NODE)
1841 return DOCUMENT_POSITION_PRECEDING;
1843 if (!child2->nextSibling())
1844 return DOCUMENT_POSITION_FOLLOWING;
1845 if (!child1->nextSibling())
1846 return DOCUMENT_POSITION_PRECEDING;
1848 // Otherwise we need to see which node occurs first. Crawl backwards from child2 looking for child1.
1849 for (Node* child = child2->previousSibling(); child; child = child->previousSibling()) {
1850 if (child == child1)
1851 return DOCUMENT_POSITION_FOLLOWING;
1853 return DOCUMENT_POSITION_PRECEDING;
1857 // There was no difference between the two parent chains, i.e., one was a subset of the other. The shorter
1858 // chain is the ancestor.
1859 return index1 < index2 ?
1860 DOCUMENT_POSITION_FOLLOWING | DOCUMENT_POSITION_CONTAINED_BY :
1861 DOCUMENT_POSITION_PRECEDING | DOCUMENT_POSITION_CONTAINS;
1864 FloatPoint Node::convertToPage(const FloatPoint& p) const
1866 // If there is a renderer, just ask it to do the conversion
1868 return renderer()->localToAbsolute(p, UseTransforms);
1870 // Otherwise go up the tree looking for a renderer
1871 Element *parent = ancestorElement();
1873 return parent->convertToPage(p);
1875 // No parent - no conversion needed
1879 FloatPoint Node::convertFromPage(const FloatPoint& p) const
1881 // If there is a renderer, just ask it to do the conversion
1883 return renderer()->absoluteToLocal(p, UseTransforms);
1885 // Otherwise go up the tree looking for a renderer
1886 Element *parent = ancestorElement();
1888 return parent->convertFromPage(p);
1890 // No parent - no conversion needed
1896 static void appendAttributeDesc(const Node* node, StringBuilder& stringBuilder, const QualifiedName& name, const char* attrDesc)
1898 if (!node->isElementNode())
1901 String attr = static_cast<const Element*>(node)->getAttribute(name);
1905 stringBuilder.append(attrDesc);
1906 stringBuilder.append(attr);
1909 void Node::showNode(const char* prefix) const
1914 String value = nodeValue();
1915 value.replaceWithLiteral('\\', "\\\\");
1916 value.replaceWithLiteral('\n', "\\n");
1917 fprintf(stderr, "%s%s\t%p \"%s\"\n", prefix, nodeName().utf8().data(), this, value.utf8().data());
1919 StringBuilder attrs;
1920 appendAttributeDesc(this, attrs, classAttr, " CLASS=");
1921 appendAttributeDesc(this, attrs, styleAttr, " STYLE=");
1922 fprintf(stderr, "%s%s\t%p%s\n", prefix, nodeName().utf8().data(), this, attrs.toString().utf8().data());
1926 void Node::showTreeForThis() const
1928 showTreeAndMark(this, "*");
1931 void Node::showNodePathForThis() const
1933 Vector<const Node*, 16> chain;
1934 const Node* node = this;
1935 while (node->parentOrHostNode()) {
1937 node = node->parentOrHostNode();
1939 for (unsigned index = chain.size(); index > 0; --index) {
1940 const Node* node = chain[index - 1];
1941 if (node->isShadowRoot()) {
1943 for (ShadowRoot* shadowRoot = oldestShadowRootFor(toShadowRoot(node)->host()); shadowRoot && shadowRoot != node; shadowRoot = shadowRoot->youngerShadowRoot())
1945 fprintf(stderr, "/#shadow-root[%d]", count);
1949 switch (node->nodeType()) {
1950 case ELEMENT_NODE: {
1951 fprintf(stderr, "/%s", node->nodeName().utf8().data());
1953 const Element* element = toElement(node);
1954 const AtomicString& idattr = element->getIdAttribute();
1955 bool hasIdAttr = !idattr.isNull() && !idattr.isEmpty();
1956 if (node->previousSibling() || node->nextSibling()) {
1958 for (Node* previous = node->previousSibling(); previous; previous = previous->previousSibling())
1959 if (previous->nodeName() == node->nodeName())
1962 fprintf(stderr, "[@id=\"%s\" and position()=%d]", idattr.string().utf8().data(), count);
1964 fprintf(stderr, "[%d]", count);
1965 } else if (hasIdAttr)
1966 fprintf(stderr, "[@id=\"%s\"]", idattr.string().utf8().data());
1970 fprintf(stderr, "/text()");
1972 case ATTRIBUTE_NODE:
1973 fprintf(stderr, "/@%s", node->nodeName().utf8().data());
1979 fprintf(stderr, "\n");
1982 static void traverseTreeAndMark(const String& baseIndent, const Node* rootNode, const Node* markedNode1, const char* markedLabel1, const Node* markedNode2, const char* markedLabel2)
1984 for (const Node* node = rootNode; node; node = NodeTraversal::next(node)) {
1985 if (node == markedNode1)
1986 fprintf(stderr, "%s", markedLabel1);
1987 if (node == markedNode2)
1988 fprintf(stderr, "%s", markedLabel2);
1990 StringBuilder indent;
1991 indent.append(baseIndent);
1992 for (const Node* tmpNode = node; tmpNode && tmpNode != rootNode; tmpNode = tmpNode->parentOrHostNode())
1993 indent.append('\t');
1994 fprintf(stderr, "%s", indent.toString().utf8().data());
1996 indent.append('\t');
1997 if (node->isShadowRoot()) {
1998 if (ShadowRoot* youngerShadowRoot = toShadowRoot(node)->youngerShadowRoot())
1999 traverseTreeAndMark(indent.toString(), youngerShadowRoot, markedNode1, markedLabel1, markedNode2, markedLabel2);
2000 } else if (ShadowRoot* oldestShadowRoot = oldestShadowRootFor(node))
2001 traverseTreeAndMark(indent.toString(), oldestShadowRoot, markedNode1, markedLabel1, markedNode2, markedLabel2);
2005 void Node::showTreeAndMark(const Node* markedNode1, const char* markedLabel1, const Node* markedNode2, const char* markedLabel2) const
2007 const Node* rootNode;
2008 const Node* node = this;
2009 while (node->parentOrHostNode() && !node->hasTagName(bodyTag))
2010 node = node->parentOrHostNode();
2013 String startingIndent;
2014 traverseTreeAndMark(startingIndent, rootNode, markedNode1, markedLabel1, markedNode2, markedLabel2);
2017 void Node::formatForDebugger(char* buffer, unsigned length) const
2028 strncpy(buffer, result.utf8().data(), length - 1);
2031 static ContainerNode* parentOrHostOrFrameOwner(const Node* node)
2033 ContainerNode* parent = node->parentOrHostNode();
2034 if (!parent && node->document() && node->document()->frame())
2035 parent = node->document()->frame()->ownerElement();
2039 static void showSubTreeAcrossFrame(const Node* node, const Node* markedNode, const String& indent)
2041 if (node == markedNode)
2043 fputs(indent.utf8().data(), stderr);
2045 if (node->isShadowRoot()) {
2046 if (ShadowRoot* youngerShadowRoot = toShadowRoot(node)->youngerShadowRoot())
2047 showSubTreeAcrossFrame(youngerShadowRoot, markedNode, indent + "\t");
2049 if (node->isFrameOwnerElement())
2050 showSubTreeAcrossFrame(static_cast<const HTMLFrameOwnerElement*>(node)->contentDocument(), markedNode, indent + "\t");
2051 if (ShadowRoot* oldestShadowRoot = oldestShadowRootFor(node))
2052 showSubTreeAcrossFrame(oldestShadowRoot, markedNode, indent + "\t");
2054 for (Node* child = node->firstChild(); child; child = child->nextSibling())
2055 showSubTreeAcrossFrame(child, markedNode, indent + "\t");
2058 void Node::showTreeForThisAcrossFrame() const
2060 Node* rootNode = const_cast<Node*>(this);
2061 while (parentOrHostOrFrameOwner(rootNode))
2062 rootNode = parentOrHostOrFrameOwner(rootNode);
2063 showSubTreeAcrossFrame(rootNode, this, "");
2070 void NodeListsNodeData::invalidateCaches(const QualifiedName* attrName)
2072 NodeListAtomicNameCacheMap::const_iterator atomicNameCacheEnd = m_atomicNameCaches.end();
2073 for (NodeListAtomicNameCacheMap::const_iterator it = m_atomicNameCaches.begin(); it != atomicNameCacheEnd; ++it)
2074 it->value->invalidateCache(attrName);
2076 NodeListNameCacheMap::const_iterator nameCacheEnd = m_nameCaches.end();
2077 for (NodeListNameCacheMap::const_iterator it = m_nameCaches.begin(); it != nameCacheEnd; ++it)
2078 it->value->invalidateCache(attrName);
2083 TagNodeListCacheNS::iterator tagCacheEnd = m_tagNodeListCacheNS.end();
2084 for (TagNodeListCacheNS::iterator it = m_tagNodeListCacheNS.begin(); it != tagCacheEnd; ++it)
2085 it->value->invalidateCache();
2088 void Node::getSubresourceURLs(ListHashSet<KURL>& urls) const
2090 addSubresourceAttributeURLs(urls);
2093 Node* Node::enclosingLinkEventParentOrSelf()
2095 for (Node* node = this; node; node = node->parentOrHostNode()) {
2096 // For imagemaps, the enclosing link node is the associated area element not the image itself.
2097 // So we don't let images be the enclosingLinkNode, even though isLink sometimes returns true
2099 if (node->isLink() && !node->hasTagName(imgTag))
2106 const AtomicString& Node::interfaceName() const
2108 return eventNames().interfaceForNode;
2111 ScriptExecutionContext* Node::scriptExecutionContext() const
2116 void Node::didMoveToNewDocument(Document* oldDocument)
2118 TreeScopeAdopter::ensureDidMoveToNewDocumentWasCalled(oldDocument);
2120 // FIXME: Event listener types for this node should be set on the new owner document here.
2122 const EventListenerVector& wheelListeners = getEventListeners(eventNames().mousewheelEvent);
2123 for (size_t i = 0; i < wheelListeners.size(); ++i) {
2124 oldDocument->didRemoveWheelEventHandler();
2125 document()->didAddWheelEventHandler();
2128 Vector<AtomicString> touchEventNames = eventNames().touchEventNames();
2129 for (size_t i = 0; i < touchEventNames.size(); ++i) {
2130 const EventListenerVector& listeners = getEventListeners(touchEventNames[i]);
2131 for (size_t j = 0; j < listeners.size(); ++j) {
2132 oldDocument->didRemoveTouchEventHandler(this);
2133 document()->didAddTouchEventHandler(this);
2137 #if ENABLE(MUTATION_OBSERVERS)
2138 if (Vector<OwnPtr<MutationObserverRegistration> >* registry = mutationObserverRegistry()) {
2139 for (size_t i = 0; i < registry->size(); ++i) {
2140 document()->addMutationObserverTypes(registry->at(i)->mutationTypes());
2144 if (HashSet<MutationObserverRegistration*>* transientRegistry = transientMutationObserverRegistry()) {
2145 for (HashSet<MutationObserverRegistration*>::iterator iter = transientRegistry->begin(); iter != transientRegistry->end(); ++iter) {
2146 document()->addMutationObserverTypes((*iter)->mutationTypes());
2152 static inline bool tryAddEventListener(Node* targetNode, const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
2154 if (!targetNode->EventTarget::addEventListener(eventType, listener, useCapture))
2157 if (Document* document = targetNode->document()) {
2158 document->addListenerTypeIfNeeded(eventType);
2159 if (eventType == eventNames().mousewheelEvent)
2160 document->didAddWheelEventHandler();
2161 else if (eventNames().isTouchEventType(eventType))
2162 document->didAddTouchEventHandler(targetNode);
2168 bool Node::addEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
2170 return tryAddEventListener(this, eventType, listener, useCapture);
2173 static inline bool tryRemoveEventListener(Node* targetNode, const AtomicString& eventType, EventListener* listener, bool useCapture)
2175 if (!targetNode->EventTarget::removeEventListener(eventType, listener, useCapture))
2178 // FIXME: Notify Document that the listener has vanished. We need to keep track of a number of
2179 // listeners for each type, not just a bool - see https://bugs.webkit.org/show_bug.cgi?id=33861
2180 if (Document* document = targetNode->document()) {
2181 if (eventType == eventNames().mousewheelEvent)
2182 document->didRemoveWheelEventHandler();
2183 else if (eventNames().isTouchEventType(eventType))
2184 document->didRemoveTouchEventHandler(targetNode);
2190 bool Node::removeEventListener(const AtomicString& eventType, EventListener* listener, bool useCapture)
2192 return tryRemoveEventListener(this, eventType, listener, useCapture);
2195 typedef HashMap<Node*, OwnPtr<EventTargetData> > EventTargetDataMap;
2197 static EventTargetDataMap& eventTargetDataMap()
2199 DEFINE_STATIC_LOCAL(EventTargetDataMap, map, ());
2203 EventTargetData* Node::eventTargetData()
2205 return hasEventTargetData() ? eventTargetDataMap().get(this) : 0;
2208 EventTargetData* Node::ensureEventTargetData()
2210 if (hasEventTargetData())
2211 return eventTargetDataMap().get(this);
2212 setHasEventTargetData(true);
2213 EventTargetData* data = new EventTargetData;
2214 eventTargetDataMap().set(this, adoptPtr(data));
2218 void Node::clearEventTargetData()
2220 eventTargetDataMap().remove(this);
2223 #if ENABLE(MUTATION_OBSERVERS)
2224 Vector<OwnPtr<MutationObserverRegistration> >* Node::mutationObserverRegistry()
2226 return hasRareData() ? rareData()->mutationObserverRegistry() : 0;
2229 HashSet<MutationObserverRegistration*>* Node::transientMutationObserverRegistry()
2231 return hasRareData() ? rareData()->transientMutationObserverRegistry() : 0;
2234 template<typename Registry>
2235 static inline void collectMatchingObserversForMutation(HashMap<MutationObserver*, MutationRecordDeliveryOptions>& observers, Registry* registry, Node* target, MutationObserver::MutationType type, const QualifiedName* attributeName)
2239 for (typename Registry::iterator iter = registry->begin(); iter != registry->end(); ++iter) {
2240 const MutationObserverRegistration& registration = **iter;
2241 if (registration.shouldReceiveMutationFrom(target, type, attributeName)) {
2242 MutationRecordDeliveryOptions deliveryOptions = registration.deliveryOptions();
2243 HashMap<MutationObserver*, MutationRecordDeliveryOptions>::AddResult result = observers.add(registration.observer(), deliveryOptions);
2244 if (!result.isNewEntry)
2245 result.iterator->value |= deliveryOptions;
2250 void Node::getRegisteredMutationObserversOfType(HashMap<MutationObserver*, MutationRecordDeliveryOptions>& observers, MutationObserver::MutationType type, const QualifiedName* attributeName)
2252 ASSERT((type == MutationObserver::Attributes && attributeName) || !attributeName);
2253 collectMatchingObserversForMutation(observers, mutationObserverRegistry(), this, type, attributeName);
2254 collectMatchingObserversForMutation(observers, transientMutationObserverRegistry(), this, type, attributeName);
2255 for (Node* node = parentNode(); node; node = node->parentNode()) {
2256 collectMatchingObserversForMutation(observers, node->mutationObserverRegistry(), this, type, attributeName);
2257 collectMatchingObserversForMutation(observers, node->transientMutationObserverRegistry(), this, type, attributeName);
2261 void Node::registerMutationObserver(MutationObserver* observer, MutationObserverOptions options, const HashSet<AtomicString>& attributeFilter)
2263 MutationObserverRegistration* registration = 0;
2264 Vector<OwnPtr<MutationObserverRegistration> >* registry = ensureRareData()->ensureMutationObserverRegistry();
2265 for (size_t i = 0; i < registry->size(); ++i) {
2266 if (registry->at(i)->observer() == observer) {
2267 registration = registry->at(i).get();
2268 registration->resetObservation(options, attributeFilter);
2272 if (!registration) {
2273 registry->append(MutationObserverRegistration::create(observer, this, options, attributeFilter));
2274 registration = registry->last().get();
2277 document()->addMutationObserverTypes(registration->mutationTypes());
2280 void Node::unregisterMutationObserver(MutationObserverRegistration* registration)
2282 Vector<OwnPtr<MutationObserverRegistration> >* registry = mutationObserverRegistry();
2287 size_t index = registry->find(registration);
2288 ASSERT(index != notFound);
2289 if (index == notFound)
2292 registry->remove(index);
2295 void Node::registerTransientMutationObserver(MutationObserverRegistration* registration)
2297 ensureRareData()->ensureTransientMutationObserverRegistry()->add(registration);
2300 void Node::unregisterTransientMutationObserver(MutationObserverRegistration* registration)
2302 HashSet<MutationObserverRegistration*>* transientRegistry = transientMutationObserverRegistry();
2303 ASSERT(transientRegistry);
2304 if (!transientRegistry)
2307 ASSERT(transientRegistry->contains(registration));
2308 transientRegistry->remove(registration);
2311 void Node::notifyMutationObserversNodeWillDetach()
2313 if (!document()->hasMutationObservers())
2316 for (Node* node = parentNode(); node; node = node->parentNode()) {
2317 if (Vector<OwnPtr<MutationObserverRegistration> >* registry = node->mutationObserverRegistry()) {
2318 const size_t size = registry->size();
2319 for (size_t i = 0; i < size; ++i)
2320 registry->at(i)->observedSubtreeNodeWillDetach(this);
2323 if (HashSet<MutationObserverRegistration*>* transientRegistry = node->transientMutationObserverRegistry()) {
2324 for (HashSet<MutationObserverRegistration*>::iterator iter = transientRegistry->begin(); iter != transientRegistry->end(); ++iter)
2325 (*iter)->observedSubtreeNodeWillDetach(this);
2329 #endif // ENABLE(MUTATION_OBSERVERS)
2331 void Node::handleLocalEvents(Event* event)
2333 if (!hasEventTargetData())
2336 if (disabled() && event->isMouseEvent())
2339 fireEventListeners(event);
2342 void Node::dispatchScopedEvent(PassRefPtr<Event> event)
2344 dispatchScopedEventDispatchMediator(EventDispatchMediator::create(event));
2347 void Node::dispatchScopedEventDispatchMediator(PassRefPtr<EventDispatchMediator> eventDispatchMediator)
2349 EventDispatcher::dispatchScopedEvent(this, eventDispatchMediator);
2352 bool Node::dispatchEvent(PassRefPtr<Event> event)
2354 if (event->isMouseEvent())
2355 return EventDispatcher::dispatchEvent(this, MouseEventDispatchMediator::create(adoptRef(toMouseEvent(event.leakRef())), MouseEventDispatchMediator::SyntheticMouseEvent));
2356 return EventDispatcher::dispatchEvent(this, EventDispatchMediator::create(event));
2359 void Node::dispatchSubtreeModifiedEvent()
2361 if (isInShadowTree())
2364 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2366 if (!document()->hasListenerType(Document::DOMSUBTREEMODIFIED_LISTENER))
2369 dispatchScopedEvent(MutationEvent::create(eventNames().DOMSubtreeModifiedEvent, true));
2372 void Node::dispatchFocusInEvent(const AtomicString& eventType, PassRefPtr<Node> oldFocusedNode)
2374 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2375 ASSERT(eventType == eventNames().focusinEvent || eventType == eventNames().DOMFocusInEvent);
2376 dispatchScopedEventDispatchMediator(FocusInEventDispatchMediator::create(UIEvent::create(eventType, true, false, document()->defaultView(), 0), oldFocusedNode));
2379 void Node::dispatchFocusOutEvent(const AtomicString& eventType, PassRefPtr<Node> newFocusedNode)
2381 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2382 ASSERT(eventType == eventNames().focusoutEvent || eventType == eventNames().DOMFocusOutEvent);
2383 dispatchScopedEventDispatchMediator(FocusOutEventDispatchMediator::create(UIEvent::create(eventType, true, false, document()->defaultView(), 0), newFocusedNode));
2386 bool Node::dispatchDOMActivateEvent(int detail, PassRefPtr<Event> underlyingEvent)
2388 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2389 RefPtr<UIEvent> event = UIEvent::create(eventNames().DOMActivateEvent, true, true, document()->defaultView(), detail);
2390 event->setUnderlyingEvent(underlyingEvent);
2391 dispatchScopedEvent(event);
2392 return event->defaultHandled();
2395 bool Node::dispatchKeyEvent(const PlatformKeyboardEvent& event)
2397 return EventDispatcher::dispatchEvent(this, KeyboardEventDispatchMediator::create(KeyboardEvent::create(event, document()->defaultView())));
2400 bool Node::dispatchMouseEvent(const PlatformMouseEvent& event, const AtomicString& eventType,
2401 int detail, Node* relatedTarget)
2403 return EventDispatcher::dispatchEvent(this, MouseEventDispatchMediator::create(MouseEvent::create(eventType, document()->defaultView(), event, detail, relatedTarget)));
2406 #if ENABLE(GESTURE_EVENTS)
2407 bool Node::dispatchGestureEvent(const PlatformGestureEvent& event)
2409 RefPtr<GestureEvent> gestureEvent = GestureEvent::create(document()->defaultView(), event);
2410 if (!gestureEvent.get())
2412 return EventDispatcher::dispatchEvent(this, GestureEventDispatchMediator::create(gestureEvent));
2416 void Node::dispatchSimulatedClick(Event* underlyingEvent, SimulatedClickMouseEventOptions eventOptions, SimulatedClickVisualOptions visualOptions)
2418 EventDispatcher::dispatchSimulatedClick(this, underlyingEvent, eventOptions, visualOptions);
2421 bool Node::dispatchBeforeLoadEvent(const String& sourceURL)
2423 if (!document()->hasListenerType(Document::BEFORELOAD_LISTENER))
2426 RefPtr<Node> protector(this);
2427 RefPtr<BeforeLoadEvent> beforeLoadEvent = BeforeLoadEvent::create(sourceURL);
2428 dispatchEvent(beforeLoadEvent.get());
2429 return !beforeLoadEvent->defaultPrevented();
2432 bool Node::dispatchWheelEvent(const PlatformWheelEvent& event)
2434 return EventDispatcher::dispatchEvent(this, WheelEventDispatchMediator::create(event, document()->defaultView()));
2437 void Node::dispatchFocusEvent(PassRefPtr<Node> oldFocusedNode)
2439 if (document()->page())
2440 document()->page()->chrome()->client()->elementDidFocus(this);
2442 EventDispatcher::dispatchEvent(this, FocusEventDispatchMediator::create(oldFocusedNode));
2445 void Node::dispatchBlurEvent(PassRefPtr<Node> newFocusedNode)
2447 if (document()->page())
2448 document()->page()->chrome()->client()->elementDidBlur(this);
2450 EventDispatcher::dispatchEvent(this, BlurEventDispatchMediator::create(newFocusedNode));
2453 void Node::dispatchChangeEvent()
2455 dispatchScopedEvent(Event::create(eventNames().changeEvent, true, false));
2458 void Node::dispatchInputEvent()
2460 dispatchScopedEvent(Event::create(eventNames().inputEvent, true, false));
2463 bool Node::disabled() const
2468 void Node::defaultEventHandler(Event* event)
2470 if (event->target() != this)
2472 const AtomicString& eventType = event->type();
2473 if (eventType == eventNames().keydownEvent || eventType == eventNames().keypressEvent) {
2474 if (event->isKeyboardEvent())
2475 if (Frame* frame = document()->frame())
2476 frame->eventHandler()->defaultKeyboardEventHandler(static_cast<KeyboardEvent*>(event));
2477 } else if (eventType == eventNames().clickEvent) {
2478 int detail = event->isUIEvent() ? static_cast<UIEvent*>(event)->detail() : 0;
2479 if (dispatchDOMActivateEvent(detail, event))
2480 event->setDefaultHandled();
2481 #if ENABLE(CONTEXT_MENUS)
2482 } else if (eventType == eventNames().contextmenuEvent) {
2483 if (Frame* frame = document()->frame())
2484 if (Page* page = frame->page())
2485 page->contextMenuController()->handleContextMenuEvent(event);
2487 } else if (eventType == eventNames().textInputEvent) {
2488 if (event->hasInterface(eventNames().interfaceForTextEvent))
2489 if (Frame* frame = document()->frame())
2490 frame->eventHandler()->defaultTextInputEventHandler(static_cast<TextEvent*>(event));
2491 #if ENABLE(PAN_SCROLLING)
2492 } else if (eventType == eventNames().mousedownEvent && event->isMouseEvent()) {
2493 MouseEvent* mouseEvent = static_cast<MouseEvent*>(event);
2494 if (mouseEvent->button() == MiddleButton) {
2495 if (enclosingLinkEventParentOrSelf())
2498 RenderObject* renderer = this->renderer();
2499 while (renderer && (!renderer->isBox() || !toRenderBox(renderer)->canBeScrolledAndHasScrollableArea()))
2500 renderer = renderer->parent();
2503 if (Frame* frame = document()->frame())
2504 frame->eventHandler()->startPanScrolling(renderer);
2508 } else if (eventType == eventNames().mousewheelEvent && event->hasInterface(eventNames().interfaceForWheelEvent)) {
2509 WheelEvent* wheelEvent = static_cast<WheelEvent*>(event);
2511 // If we don't have a renderer, send the wheel event to the first node we find with a renderer.
2512 // This is needed for <option> and <optgroup> elements so that <select>s get a wheel scroll.
2513 Node* startNode = this;
2514 while (startNode && !startNode->renderer())
2515 startNode = startNode->parentOrHostNode();
2517 if (startNode && startNode->renderer())
2518 if (Frame* frame = document()->frame())
2519 frame->eventHandler()->defaultWheelEventHandler(startNode, wheelEvent);
2520 } else if (event->type() == eventNames().webkitEditableContentChangedEvent) {
2521 dispatchInputEvent();
2525 bool Node::willRespondToMouseMoveEvents()
2529 return hasEventListeners(eventNames().mousemoveEvent) || hasEventListeners(eventNames().mouseoverEvent) || hasEventListeners(eventNames().mouseoutEvent);
2532 bool Node::willRespondToMouseClickEvents()
2536 return isContentEditable(UserSelectAllIsAlwaysNonEditable) || hasEventListeners(eventNames().mouseupEvent) || hasEventListeners(eventNames().mousedownEvent) || hasEventListeners(eventNames().clickEvent) || hasEventListeners(eventNames().DOMActivateEvent);
2539 bool Node::willRespondToTouchEvents()
2541 #if ENABLE(TOUCH_EVENTS)
2544 return hasEventListeners(eventNames().touchstartEvent) || hasEventListeners(eventNames().touchmoveEvent) || hasEventListeners(eventNames().touchcancelEvent) || hasEventListeners(eventNames().touchendEvent);
2550 #if ENABLE(MICRODATA)
2551 DOMSettableTokenList* Node::itemProp()
2553 return ensureRareData()->itemProp();
2556 void Node::setItemProp(const String& value)
2558 ensureRareData()->setItemProp(value);
2561 DOMSettableTokenList* Node::itemRef()
2563 return ensureRareData()->itemRef();
2566 void Node::setItemRef(const String& value)
2568 ensureRareData()->setItemRef(value);
2571 DOMSettableTokenList* Node::itemType()
2573 return ensureRareData()->itemType();
2576 void Node::setItemType(const String& value)
2578 ensureRareData()->setItemType(value);
2581 PassRefPtr<PropertyNodeList> Node::propertyNodeList(const String& name)
2583 return ensureRareData()->ensureNodeLists()->addCacheWithName<PropertyNodeList>(this, PropertyNodeListType, name);
2587 // It's important not to inline removedLastRef, because we don't want to inline the code to
2588 // delete a Node at each deref call site.
2589 void Node::removedLastRef()
2591 // An explicit check for Document here is better than a virtual function since it is
2592 // faster for non-Document nodes, and because the call to removedLastRef that is inlined
2593 // at all deref call sites is smaller if it's a non-virtual function.
2594 if (isDocumentNode()) {
2595 static_cast<Document*>(this)->removedLastRef();
2599 m_deletionHasBegun = true;
2604 void Node::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
2606 MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::DOM);
2607 TreeShared<Node, ContainerNode>::reportMemoryUsage(memoryObjectInfo);
2608 ScriptWrappable::reportMemoryUsage(memoryObjectInfo);
2609 info.addMember(m_document);
2610 info.addMember(m_next);
2611 info.addMember(m_previous);
2612 info.addMember(this->renderer());
2614 info.addMember(rareData());
2617 void Node::textRects(Vector<IntRect>& rects) const
2619 RefPtr<Range> range = Range::create(document());
2620 WebCore::ExceptionCode ec = 0;
2621 range->selectNodeContents(const_cast<Node*>(this), ec);
2622 range->textRects(rects);
2625 void Node::registerScopedHTMLStyleChild()
2627 setHasScopedHTMLStyleChild(true);
2630 void Node::unregisterScopedHTMLStyleChild()
2632 ASSERT(hasScopedHTMLStyleChild());
2633 setHasScopedHTMLStyleChild(numberOfScopedHTMLStyleChildren());
2636 size_t Node::numberOfScopedHTMLStyleChildren() const
2639 for (Node* child = firstChild(); child; child = child->nextSibling()) {
2640 if (child->hasTagName(HTMLNames::styleTag) && static_cast<HTMLStyleElement*>(child)->isRegisteredAsScoped())
2647 void Node::setFocus(bool flag)
2649 if (Document* document = this->document())
2650 document->userActionElements().setFocused(this, flag);
2653 void Node::setActive(bool flag, bool)
2655 if (Document* document = this->document())
2656 document->userActionElements().setActive(this, flag);
2659 void Node::setHovered(bool flag)
2661 if (Document* document = this->document())
2662 document->userActionElements().setHovered(this, flag);
2665 bool Node::isUserActionElementActive() const
2667 ASSERT(isUserActionElement());
2668 return document()->userActionElements().isActive(this);
2671 bool Node::isUserActionElementInActiveChain() const
2673 ASSERT(isUserActionElement());
2674 return document()->userActionElements().isInActiveChain(this);
2677 bool Node::isUserActionElementHovered() const
2679 ASSERT(isUserActionElement());
2680 return document()->userActionElements().isHovered(this);
2683 bool Node::isUserActionElementFocused() const
2685 ASSERT(isUserActionElement());
2686 return document()->userActionElements().isFocused(this);
2689 } // namespace WebCore
2693 void showTree(const WebCore::Node* node)
2696 node->showTreeForThis();
2699 void showNodePath(const WebCore::Node* node)
2702 node->showNodePathForThis();