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 "DocumentType.h"
51 #include "ElementRareData.h"
52 #include "ElementShadow.h"
54 #include "EventContext.h"
55 #include "EventDispatchMediator.h"
56 #include "EventDispatcher.h"
57 #include "EventException.h"
58 #include "EventHandler.h"
59 #include "EventListener.h"
60 #include "EventNames.h"
61 #include "ExceptionCode.h"
63 #include "FrameView.h"
64 #include "HTMLElement.h"
65 #include "HTMLFrameOwnerElement.h"
66 #include "HTMLNames.h"
67 #include "HTMLStyleElement.h"
68 #include "InspectorCounters.h"
69 #include "KeyboardEvent.h"
70 #include "LabelsNodeList.h"
71 #include "LiveNodeList.h"
73 #include "MouseEvent.h"
74 #include "MutationEvent.h"
75 #include "NameNodeList.h"
76 #include "NamedNodeMap.h"
77 #include "NodeRareData.h"
78 #include "NodeRenderingContext.h"
79 #include "NodeTraversal.h"
81 #include "PlatformMouseEvent.h"
82 #include "PlatformWheelEvent.h"
83 #include "ProcessingInstruction.h"
84 #include "ProgressEvent.h"
85 #include "RadioNodeList.h"
86 #include "RegisteredEventListener.h"
87 #include "RenderBlock.h"
88 #include "RenderBox.h"
89 #include "RenderTextControl.h"
90 #include "RenderView.h"
91 #include "ScopedEventQueue.h"
92 #include "SelectorQuery.h"
94 #include "ShadowRoot.h"
95 #include "StaticNodeList.h"
96 #include "StorageEvent.h"
97 #include "StyleResolver.h"
98 #include "TagNodeList.h"
100 #include "TextEvent.h"
101 #include "TreeScopeAdopter.h"
103 #include "UIEventWithKeyState.h"
104 #include "UserActionElementSet.h"
105 #include "WebCoreMemoryInstrumentation.h"
106 #include "WheelEvent.h"
107 #include "WindowEventContext.h"
108 #include "XMLNames.h"
109 #include "htmlediting.h"
110 #include <wtf/HashSet.h>
111 #include <wtf/PassOwnPtr.h>
112 #include <wtf/RefCountedLeakCounter.h>
113 #include <wtf/UnusedParam.h>
114 #include <wtf/Vector.h>
115 #include <wtf/text/CString.h>
116 #include <wtf/text/StringBuilder.h>
119 #include "RenderLayer.h"
122 #if ENABLE(GESTURE_EVENTS)
123 #include "GestureEvent.h"
126 #if ENABLE(INSPECTOR)
127 #include "InspectorController.h"
131 #include <runtime/JSGlobalData.h>
134 #if ENABLE(MICRODATA)
135 #include "HTMLPropertiesCollection.h"
136 #include "PropertyNodeList.h"
143 using namespace HTMLNames;
145 bool Node::isSupported(const String& feature, const String& version)
147 return DOMImplementation::hasFeature(feature, version);
150 #if DUMP_NODE_STATISTICS
151 static HashSet<Node*> liveNodeSet;
154 void Node::dumpStatistics()
156 #if DUMP_NODE_STATISTICS
157 size_t nodesWithRareData = 0;
159 size_t elementNodes = 0;
160 size_t attrNodes = 0;
161 size_t textNodes = 0;
162 size_t cdataNodes = 0;
163 size_t commentNodes = 0;
164 size_t entityReferenceNodes = 0;
165 size_t entityNodes = 0;
167 size_t documentNodes = 0;
168 size_t docTypeNodes = 0;
169 size_t fragmentNodes = 0;
170 size_t notationNodes = 0;
171 size_t xpathNSNodes = 0;
172 size_t shadowRootNodes = 0;
174 HashMap<String, size_t> perTagCount;
176 size_t attributes = 0;
177 size_t attributesWithAttr = 0;
178 size_t elementsWithAttributeStorage = 0;
179 size_t elementsWithRareData = 0;
180 size_t elementsWithNamedNodeMap = 0;
182 for (HashSet<Node*>::iterator it = liveNodeSet.begin(); it != liveNodeSet.end(); ++it) {
185 if (node->hasRareData()) {
187 if (node->isElementNode()) {
188 ++elementsWithRareData;
189 if (toElement(node)->hasNamedNodeMap())
190 ++elementsWithNamedNodeMap;
194 switch (node->nodeType()) {
199 Element* element = static_cast<Element*>(node);
200 HashMap<String, size_t>::AddResult result = perTagCount.add(element->tagName(), 1);
201 if (!result.isNewEntry)
202 result.iterator->value++;
204 if (ElementAttributeData* attributeData = element->attributeData()) {
205 attributes += attributeData->length();
206 ++elementsWithAttributeStorage;
207 for (unsigned i = 0; i < attributeData->length(); ++i) {
208 Attribute* attr = attributeData->attributeItem(i);
210 ++attributesWithAttr;
215 case ATTRIBUTE_NODE: {
223 case CDATA_SECTION_NODE: {
231 case ENTITY_REFERENCE_NODE: {
232 ++entityReferenceNodes;
239 case PROCESSING_INSTRUCTION_NODE: {
243 case DOCUMENT_NODE: {
247 case DOCUMENT_TYPE_NODE: {
251 case DOCUMENT_FRAGMENT_NODE: {
252 if (node->isShadowRoot())
258 case NOTATION_NODE: {
262 case XPATH_NAMESPACE_NODE: {
269 printf("Number of Nodes: %d\n\n", liveNodeSet.size());
270 printf("Number of Nodes with RareData: %zu\n\n", nodesWithRareData);
272 printf("NodeType distribution:\n");
273 printf(" Number of Element nodes: %zu\n", elementNodes);
274 printf(" Number of Attribute nodes: %zu\n", attrNodes);
275 printf(" Number of Text nodes: %zu\n", textNodes);
276 printf(" Number of CDATASection nodes: %zu\n", cdataNodes);
277 printf(" Number of Comment nodes: %zu\n", commentNodes);
278 printf(" Number of EntityReference nodes: %zu\n", entityReferenceNodes);
279 printf(" Number of Entity nodes: %zu\n", entityNodes);
280 printf(" Number of ProcessingInstruction nodes: %zu\n", piNodes);
281 printf(" Number of Document nodes: %zu\n", documentNodes);
282 printf(" Number of DocumentType nodes: %zu\n", docTypeNodes);
283 printf(" Number of DocumentFragment nodes: %zu\n", fragmentNodes);
284 printf(" Number of Notation nodes: %zu\n", notationNodes);
285 printf(" Number of XPathNS nodes: %zu\n", xpathNSNodes);
286 printf(" Number of ShadowRoot nodes: %zu\n", shadowRootNodes);
288 printf("Element tag name distibution:\n");
289 for (HashMap<String, size_t>::iterator it = perTagCount.begin(); it != perTagCount.end(); ++it)
290 printf(" Number of <%s> tags: %zu\n", it->key.utf8().data(), it->value);
292 printf("Attributes:\n");
293 printf(" Number of Attributes (non-Node and Node): %zu [%zu]\n", attributes, sizeof(Attribute));
294 printf(" Number of Attributes with an Attr: %zu\n", attributesWithAttr);
295 printf(" Number of Elements with attribute storage: %zu [%zu]\n", elementsWithAttributeStorage, sizeof(ElementAttributeData));
296 printf(" Number of Elements with RareData: %zu\n", elementsWithRareData);
297 printf(" Number of Elements with NamedNodeMap: %zu [%zu]\n", elementsWithNamedNodeMap, sizeof(NamedNodeMap));
301 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, nodeCounter, ("WebCoreNode"));
302 DEFINE_DEBUG_ONLY_GLOBAL(HashSet<Node*>, ignoreSet, );
305 static bool shouldIgnoreLeaks = false;
308 void Node::startIgnoringLeaks()
311 shouldIgnoreLeaks = true;
315 void Node::stopIgnoringLeaks()
318 shouldIgnoreLeaks = false;
322 Node::StyleChange Node::diff(const RenderStyle* s1, const RenderStyle* s2, Document* doc)
324 StyleChange ch = NoInherit;
325 EDisplay display1 = s1 ? s1->display() : NONE;
326 bool fl1 = s1 && s1->hasPseudoStyle(FIRST_LETTER);
327 EDisplay display2 = s2 ? s2->display() : NONE;
328 bool fl2 = s2 && s2->hasPseudoStyle(FIRST_LETTER);
330 // We just detach if a renderer acquires or loses a column-span, since spanning elements
331 // typically won't contain much content.
332 bool colSpan1 = s1 && s1->columnSpan();
333 bool colSpan2 = s2 && s2->columnSpan();
335 bool specifiesColumns1 = s1 && (!s1->hasAutoColumnCount() || !s1->hasAutoColumnWidth());
336 bool specifiesColumns2 = s2 && (!s2->hasAutoColumnCount() || !s2->hasAutoColumnWidth());
338 if (display1 != display2 || fl1 != fl2 || colSpan1 != colSpan2
339 || (specifiesColumns1 != specifiesColumns2 && doc->settings()->regionBasedColumnsEnabled())
340 || (s1 && s2 && !s1->contentDataEquivalent(s2)))
346 else if (s1->inheritedNotEqual(s2))
348 else if (s1->hasExplicitlyInheritedProperties() || s2->hasExplicitlyInheritedProperties())
351 // If the pseudoStyles have changed, we want any StyleChange that is not NoChange
352 // because setStyle will do the right thing with anything else.
353 if (ch == NoChange && s1->hasAnyPublicPseudoStyles()) {
354 for (PseudoId pseudoId = FIRST_PUBLIC_PSEUDOID; ch == NoChange && pseudoId < FIRST_INTERNAL_PSEUDOID; pseudoId = static_cast<PseudoId>(pseudoId + 1)) {
355 if (s1->hasPseudoStyle(pseudoId)) {
356 RenderStyle* ps2 = s2->getCachedPseudoStyle(pseudoId);
360 RenderStyle* ps1 = s1->getCachedPseudoStyle(pseudoId);
361 ch = ps1 && *ps1 == *ps2 ? NoChange : NoInherit;
367 // When text-combine property has been changed, we need to prepare a separate renderer object.
368 // When text-combine is on, we use RenderCombineText, otherwise RenderText.
369 // https://bugs.webkit.org/show_bug.cgi?id=55069
370 if ((s1 && s2) && (s1->hasTextCombine() != s2->hasTextCombine()))
373 // We need to reattach the node, so that it is moved to the correct RenderFlowThread.
374 if ((s1 && s2) && (s1->flowThread() != s2->flowThread()))
377 // When the region thread has changed, we need to prepare a separate render region object.
378 if ((s1 && s2) && (s1->regionThread() != s2->regionThread()))
384 void Node::trackForDebugging()
387 if (shouldIgnoreLeaks)
390 nodeCounter.increment();
393 #if DUMP_NODE_STATISTICS
394 liveNodeSet.add(this);
401 HashSet<Node*>::iterator it = ignoreSet.find(this);
402 if (it != ignoreSet.end())
403 ignoreSet.remove(it);
405 nodeCounter.decrement();
408 #if DUMP_NODE_STATISTICS
409 liveNodeSet.remove(this);
415 if (hasEventTargetData()) {
416 #if ENABLE(TOUCH_EVENT_TRACKING)
418 m_document->didRemoveEventTargetNode(this);
420 clearEventTargetData();
426 Document* doc = m_document;
427 if (AXObjectCache::accessibilityEnabled() && doc && doc->axObjectCacheExists() && !isContainerNode())
428 doc->axObjectCache()->remove(this);
431 m_previous->setNextSibling(0);
433 m_next->setPreviousSibling(0);
438 InspectorCounters::decrementCounter(InspectorCounters::NodeCounter);
441 void Node::setDocument(Document* document)
443 ASSERT(!inDocument() || m_document == document);
444 if (inDocument() || m_document == document)
447 m_document = document;
450 void Node::setTreeScope(TreeScope* scope)
452 ASSERT(!isShadowRoot());
454 if (!hasRareData() && scope->rootNode()->isDocumentNode())
457 ensureRareData()->setTreeScope(scope);
460 NodeRareData* Node::rareData() const
462 ASSERT(hasRareData());
463 return static_cast<NodeRareData*>(m_data.m_rareData);
466 NodeRareData* Node::ensureRareData()
471 NodeRareData* data = createRareData().leakPtr();
473 data->setRenderer(m_data.m_renderer);
474 m_data.m_rareData = data;
475 setFlag(HasRareDataFlag);
479 PassOwnPtr<NodeRareData> Node::createRareData()
481 return adoptPtr(new NodeRareData(documentInternal()));
484 void Node::clearRareData()
486 ASSERT(hasRareData());
488 #if ENABLE(MUTATION_OBSERVERS)
489 ASSERT(!transientMutationObserverRegistry() || transientMutationObserverRegistry()->isEmpty());
492 RenderObject* renderer = m_data.m_rareData->renderer();
493 delete m_data.m_rareData;
494 m_data.m_renderer = renderer;
495 clearFlag(HasRareDataFlag);
503 HTMLInputElement* Node::toInputElement()
505 // If one of the below ASSERTs trigger, you are calling this function
506 // directly or indirectly from a constructor or destructor of this object.
508 ASSERT(!(isHTMLElement() && hasTagName(inputTag)));
512 short Node::tabIndex() const
514 return hasRareData() ? rareData()->tabIndex() : 0;
517 void Node::setTabIndexExplicitly(short i)
519 ensureRareData()->setTabIndexExplicitly(i);
522 void Node::clearTabIndexExplicitly()
524 ensureRareData()->clearTabIndexExplicitly();
527 String Node::nodeValue() const
532 void Node::setNodeValue(const String& /*nodeValue*/, ExceptionCode& ec)
534 // NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly
535 if (isReadOnlyNode()) {
536 ec = NO_MODIFICATION_ALLOWED_ERR;
540 // By default, setting nodeValue has no effect.
543 PassRefPtr<NodeList> Node::childNodes()
545 return ensureRareData()->ensureNodeLists()->ensureChildNodeList(this);
548 Node *Node::lastDescendant() const
550 Node *n = const_cast<Node *>(this);
551 while (n && n->lastChild())
556 Node* Node::firstDescendant() const
558 Node *n = const_cast<Node *>(this);
559 while (n && n->firstChild())
564 bool Node::insertBefore(PassRefPtr<Node> newChild, Node* refChild, ExceptionCode& ec, bool shouldLazyAttach)
566 if (!isContainerNode()) {
567 ec = HIERARCHY_REQUEST_ERR;
570 return toContainerNode(this)->insertBefore(newChild, refChild, ec, shouldLazyAttach);
573 bool Node::replaceChild(PassRefPtr<Node> newChild, Node* oldChild, ExceptionCode& ec, bool shouldLazyAttach)
575 if (!isContainerNode()) {
576 ec = HIERARCHY_REQUEST_ERR;
579 return toContainerNode(this)->replaceChild(newChild, oldChild, ec, shouldLazyAttach);
582 bool Node::removeChild(Node* oldChild, ExceptionCode& ec)
584 if (!isContainerNode()) {
588 return toContainerNode(this)->removeChild(oldChild, ec);
591 bool Node::appendChild(PassRefPtr<Node> newChild, ExceptionCode& ec, bool shouldLazyAttach)
593 if (!isContainerNode()) {
594 ec = HIERARCHY_REQUEST_ERR;
597 return toContainerNode(this)->appendChild(newChild, ec, shouldLazyAttach);
600 void Node::remove(ExceptionCode& ec)
602 if (ContainerNode* parent = parentNode())
603 parent->removeChild(this, ec);
606 void Node::normalize()
608 // Go through the subtree beneath us, normalizing all nodes. This means that
609 // any two adjacent text nodes are merged and any empty text nodes are removed.
611 RefPtr<Node> node = this;
612 while (Node* firstChild = node->firstChild())
615 NodeType type = node->nodeType();
616 if (type == ELEMENT_NODE)
617 static_cast<Element*>(node.get())->normalizeAttributes();
622 if (type != TEXT_NODE) {
623 node = NodeTraversal::nextPostOrder(node.get());
627 RefPtr<Text> text = toText(node.get());
629 // Remove empty text nodes.
630 if (!text->length()) {
631 // Care must be taken to get the next node before removing the current node.
632 node = NodeTraversal::nextPostOrder(node.get());
639 while (Node* nextSibling = node->nextSibling()) {
640 if (nextSibling->nodeType() != TEXT_NODE)
642 RefPtr<Text> nextText = toText(nextSibling);
644 // Remove empty text nodes.
645 if (!nextText->length()) {
647 nextText->remove(ec);
651 // Both non-empty text nodes. Merge them.
652 unsigned offset = text->length();
654 text->appendData(nextText->data(), ec);
655 document()->textNodesMerged(nextText.get(), offset);
656 nextText->remove(ec);
659 node = NodeTraversal::nextPostOrder(node.get());
663 const AtomicString& Node::virtualPrefix() const
665 // For nodes other than elements and attributes, the prefix is always null
669 void Node::setPrefix(const AtomicString& /*prefix*/, ExceptionCode& ec)
671 // The spec says that for nodes other than elements and attributes, prefix is always null.
672 // It does not say what to do when the user tries to set the prefix on another type of
673 // node, however Mozilla throws a NAMESPACE_ERR exception.
677 const AtomicString& Node::virtualLocalName() const
682 const AtomicString& Node::virtualNamespaceURI() const
687 bool Node::isContentEditable(UserSelectAllTreatment treatment)
689 document()->updateStyleIfNeeded();
690 return rendererIsEditable(Editable, treatment);
693 bool Node::isContentRichlyEditable()
695 document()->updateStyleIfNeeded();
696 return rendererIsEditable(RichlyEditable, UserSelectAllIsAlwaysNonEditable);
701 #if ENABLE(INSPECTOR)
702 if (document() && document()->page())
703 document()->page()->inspectorController()->inspect(this);
707 bool Node::rendererIsEditable(EditableLevel editableLevel, UserSelectAllTreatment treatment) const
709 if (document()->frame() && document()->frame()->page() && document()->frame()->page()->isEditable() && !containingShadowRoot())
712 if (isPseudoElement())
715 // Ideally we'd call ASSERT(!needsStyleRecalc()) here, but
716 // ContainerNode::setFocus() calls setNeedsStyleRecalc(), so the assertion
717 // would fire in the middle of Document::setFocusedNode().
719 for (const Node* node = this; node; node = node->parentNode()) {
720 if ((node->isHTMLElement() || node->isDocumentNode()) && node->renderer()) {
721 #if ENABLE(USERSELECT_ALL)
722 // Elements with user-select: all style are considered atomic
723 // therefore non editable.
724 if (node->renderer()->style()->userSelect() == SELECT_ALL && treatment == UserSelectAllIsAlwaysNonEditable)
727 UNUSED_PARAM(treatment);
729 switch (node->renderer()->style()->userModify()) {
734 case READ_WRITE_PLAINTEXT_ONLY:
735 return editableLevel != RichlyEditable;
737 ASSERT_NOT_REACHED();
745 bool Node::isEditableToAccessibility(EditableLevel editableLevel) const
747 if (rendererIsEditable(editableLevel))
750 // FIXME: Respect editableLevel for ARIA editable elements.
751 if (editableLevel == RichlyEditable)
755 ASSERT(AXObjectCache::accessibilityEnabled());
756 ASSERT(document()->axObjectCacheExists());
758 if (document() && AXObjectCache::accessibilityEnabled() && document()->axObjectCacheExists())
759 return document()->axObjectCache()->rootAXEditableElement(this);
764 bool Node::shouldUseInputMethod()
766 return isContentEditable(UserSelectAllIsAlwaysNonEditable);
769 RenderBox* Node::renderBox() const
771 RenderObject* renderer = this->renderer();
772 return renderer && renderer->isBox() ? toRenderBox(renderer) : 0;
775 RenderBoxModelObject* Node::renderBoxModelObject() const
777 RenderObject* renderer = this->renderer();
778 return renderer && renderer->isBoxModelObject() ? toRenderBoxModelObject(renderer) : 0;
781 LayoutRect Node::boundingBox() const
784 return renderer()->absoluteBoundingBoxRect();
788 LayoutRect Node::renderRect(bool* isReplaced)
790 RenderObject* hitRenderer = this->renderer();
792 RenderObject* renderer = hitRenderer;
793 while (renderer && !renderer->isBody() && !renderer->isRoot()) {
794 if (renderer->isRenderBlock() || renderer->isInlineBlockOrInlineTable() || renderer->isReplaced()) {
795 *isReplaced = renderer->isReplaced();
796 return renderer->absoluteBoundingBoxRect();
798 renderer = renderer->parent();
803 bool Node::hasNonEmptyBoundingBox() const
805 // Before calling absoluteRects, check for the common case where the renderer
806 // is non-empty, since this is a faster check and almost always returns true.
807 RenderBoxModelObject* box = renderBoxModelObject();
810 if (!box->borderBoundingBox().isEmpty())
813 Vector<IntRect> rects;
814 FloatPoint absPos = renderer()->localToAbsolute();
815 renderer()->absoluteRects(rects, flooredLayoutPoint(absPos));
816 size_t n = rects.size();
817 for (size_t i = 0; i < n; ++i)
818 if (!rects[i].isEmpty())
824 inline static ShadowRoot* oldestShadowRootFor(const Node* node)
826 if (!node->isElementNode())
828 if (ElementShadow* shadow = toElement(node)->shadow())
829 return shadow->oldestShadowRoot();
833 inline void Node::setStyleChange(StyleChangeType changeType)
835 m_nodeFlags = (m_nodeFlags & ~StyleChangeMask) | changeType;
838 inline void Node::markAncestorsWithChildNeedsStyleRecalc()
840 for (ContainerNode* p = parentOrHostNode(); p && !p->childNeedsStyleRecalc(); p = p->parentOrHostNode())
841 p->setChildNeedsStyleRecalc();
843 if (document()->childNeedsStyleRecalc())
844 document()->scheduleStyleRecalc();
847 void Node::refEventTarget()
852 void Node::derefEventTarget()
857 void Node::setNeedsStyleRecalc(StyleChangeType changeType)
859 ASSERT(changeType != NoStyleChange);
860 if (!attached()) // changed compared to what?
863 StyleChangeType existingChangeType = styleChangeType();
864 if (changeType > existingChangeType)
865 setStyleChange(changeType);
867 if (existingChangeType == NoStyleChange)
868 markAncestorsWithChildNeedsStyleRecalc();
871 void Node::lazyAttach(ShouldSetAttached shouldSetAttached)
873 for (Node* n = this; n; n = NodeTraversal::next(n, this)) {
874 if (n->hasChildNodes())
875 n->setChildNeedsStyleRecalc();
876 n->setStyleChange(FullStyleChange);
877 if (shouldSetAttached == SetAttached)
880 markAncestorsWithChildNeedsStyleRecalc();
883 bool Node::supportsFocus() const
885 return hasRareData() && rareData()->tabIndexSetExplicitly();
888 bool Node::isFocusable() const
890 if (!inDocument() || !supportsFocus())
893 // Elements in canvas fallback content are not rendered, but they are allowed to be
894 // focusable as long as their canvas is displayed and visible.
895 if (isElementNode() && toElement(this)->isInCanvasSubtree()) {
896 const Element* e = toElement(this);
897 while (e && !e->hasLocalName(canvasTag))
898 e = e->parentElement();
900 return e->renderer() && e->renderer()->style()->visibility() == VISIBLE;
904 ASSERT(!renderer()->needsLayout());
906 // If the node is in a display:none tree it might say it needs style recalc but
907 // the whole document is actually up to date.
908 ASSERT(!document()->childNeedsStyleRecalc());
910 // FIXME: Even if we are not visible, we might have a child that is visible.
911 // Hyatt wants to fix that some day with a "has visible content" flag or the like.
912 if (!renderer() || renderer()->style()->visibility() != VISIBLE)
918 bool Node::isTreeScope() const
920 return treeScope()->rootNode() == this;
923 bool Node::isKeyboardFocusable(KeyboardEvent*) const
925 return isFocusable() && tabIndex() >= 0;
928 bool Node::isMouseFocusable() const
930 return isFocusable();
933 Node* Node::focusDelegate()
938 unsigned Node::nodeIndex() const
940 Node *_tempNode = previousSibling();
942 for ( count=0; _tempNode; count++ )
943 _tempNode = _tempNode->previousSibling();
947 template<unsigned type>
948 bool shouldInvalidateNodeListCachesForAttr(const unsigned nodeListCounts[], const QualifiedName& attrName)
950 if (nodeListCounts[type] && LiveNodeListBase::shouldInvalidateTypeOnAttributeChange(static_cast<NodeListInvalidationType>(type), attrName))
952 return shouldInvalidateNodeListCachesForAttr<type + 1>(nodeListCounts, attrName);
956 bool shouldInvalidateNodeListCachesForAttr<numNodeListInvalidationTypes>(const unsigned[], const QualifiedName&)
961 bool Document::shouldInvalidateNodeListCaches(const QualifiedName* attrName) const
964 return shouldInvalidateNodeListCachesForAttr<DoNotInvalidateOnAttributeChanges + 1>(m_nodeListCounts, *attrName);
966 for (int type = 0; type < numNodeListInvalidationTypes; type++) {
967 if (m_nodeListCounts[type])
974 void Document::invalidateNodeListCaches(const QualifiedName* attrName)
976 HashSet<LiveNodeListBase*>::iterator end = m_listsInvalidatedAtDocument.end();
977 for (HashSet<LiveNodeListBase*>::iterator it = m_listsInvalidatedAtDocument.begin(); it != end; ++it)
978 (*it)->invalidateCache(attrName);
981 void Node::invalidateNodeListCachesInAncestors(const QualifiedName* attrName, Element* attributeOwnerElement)
983 if (hasRareData() && (!attrName || isAttributeNode())) {
984 if (NodeListsNodeData* lists = rareData()->nodeLists())
985 lists->clearChildNodeListCache();
988 // Modifications to attributes that are not associated with an Element can't invalidate NodeList caches.
989 if (attrName && !attributeOwnerElement)
992 if (!document()->shouldInvalidateNodeListCaches(attrName))
995 document()->invalidateNodeListCaches(attrName);
997 for (Node* node = this; node; node = node->parentNode()) {
998 if (!node->hasRareData())
1000 NodeRareData* data = node->rareData();
1001 if (data->nodeLists())
1002 data->nodeLists()->invalidateCaches(attrName);
1006 NodeListsNodeData* Node::nodeLists()
1008 return hasRareData() ? rareData()->nodeLists() : 0;
1011 void Node::checkSetPrefix(const AtomicString& prefix, ExceptionCode& ec)
1013 // Perform error checking as required by spec for setting Node.prefix. Used by
1014 // Element::setPrefix() and Attr::setPrefix()
1016 if (!prefix.isEmpty() && !Document::isValidName(prefix)) {
1017 ec = INVALID_CHARACTER_ERR;
1021 if (isReadOnlyNode()) {
1022 ec = NO_MODIFICATION_ALLOWED_ERR;
1026 // FIXME: Raise NAMESPACE_ERR if prefix is malformed per the Namespaces in XML specification.
1028 const AtomicString& nodeNamespaceURI = namespaceURI();
1029 if ((nodeNamespaceURI.isEmpty() && !prefix.isEmpty())
1030 || (prefix == xmlAtom && nodeNamespaceURI != XMLNames::xmlNamespaceURI)) {
1034 // Attribute-specific checks are in Attr::setPrefix().
1037 bool Node::isDescendantOf(const Node *other) const
1039 // Return true if other is an ancestor of this, otherwise false
1040 if (!other || !other->hasChildNodes() || inDocument() != other->inDocument())
1042 if (other->isDocumentNode())
1043 return document() == other && !isDocumentNode() && inDocument();
1044 for (const ContainerNode* n = parentNode(); n; n = n->parentNode()) {
1051 bool Node::contains(const Node* node) const
1055 return this == node || node->isDescendantOf(this);
1058 bool Node::containsIncludingShadowDOM(Node* node)
1062 for (Node* n = node; n; n = n->parentOrHostNode()) {
1071 ASSERT(!attached());
1072 ASSERT(!renderer() || (renderer()->style() && renderer()->parent()));
1074 // FIXME: This is O(N^2) for the innerHTML case, where all children are replaced at once (and not attached).
1075 // If this node got a renderer it may be the previousRenderer() of sibling text nodes and thus affect the
1076 // result of Text::textRendererIsNeeded() for those nodes.
1078 for (Node* next = nextSibling(); next; next = next->nextSibling()) {
1079 if (next->renderer())
1081 if (!next->attached())
1082 break; // Assume this means none of the following siblings are attached.
1083 if (next->isTextNode())
1084 toText(next)->createTextRendererIfNeeded();
1089 clearNeedsStyleRecalc();
1091 Document* doc = m_document;
1092 if (AXObjectCache::accessibilityEnabled() && doc && doc->axObjectCacheExists())
1093 doc->axObjectCache()->updateCacheAfterNodeIsAttached(this);
1097 static Node* detachingNode;
1099 bool Node::inDetach() const
1101 return detachingNode == this;
1108 ASSERT(!detachingNode);
1109 detachingNode = this;
1113 renderer()->destroyAndCleanupAnonymousWrappers();
1115 for (Node* node = this; node; node = NodeTraversal::next(node, this)) {
1116 RenderObject* renderer = node->renderer();
1117 // RenderFlowThread and the top layer remove elements from the regular tree
1118 // hierarchy. They will be cleaned up when we call detach on them.
1119 #if ENABLE(DIALOG_ELEMENT)
1120 ASSERT(!renderer || renderer->inRenderFlowThread() || (renderer->enclosingLayer()->isInTopLayerSubtree()));
1122 ASSERT(!renderer || renderer->inRenderFlowThread());
1128 ASSERT(!renderer());
1130 Document* doc = document();
1131 if (isUserActionElement()) {
1133 doc->hoveredNodeDetached(this);
1134 if (inActiveChain())
1135 doc->activeChainNodeDetached(this);
1136 doc->userActionElements().didDetach(this);
1139 clearFlag(IsAttachedFlag);
1146 // FIXME: This code is used by editing. Seems like it could move over there and not pollute Node.
1147 Node *Node::previousNodeConsideringAtomicNodes() const
1149 if (previousSibling()) {
1150 Node *n = previousSibling();
1151 while (!isAtomicNode(n) && n->lastChild())
1155 else if (parentNode()) {
1156 return parentNode();
1163 Node *Node::nextNodeConsideringAtomicNodes() const
1165 if (!isAtomicNode(this) && firstChild())
1166 return firstChild();
1168 return nextSibling();
1169 const Node *n = this;
1170 while (n && !n->nextSibling())
1171 n = n->parentNode();
1173 return n->nextSibling();
1177 Node *Node::previousLeafNode() const
1179 Node *node = previousNodeConsideringAtomicNodes();
1181 if (isAtomicNode(node))
1183 node = node->previousNodeConsideringAtomicNodes();
1188 Node *Node::nextLeafNode() const
1190 Node *node = nextNodeConsideringAtomicNodes();
1192 if (isAtomicNode(node))
1194 node = node->nextNodeConsideringAtomicNodes();
1199 ContainerNode* Node::parentNodeForRenderingAndStyle()
1201 return NodeRenderingContext(this).parentNodeForRenderingAndStyle();
1204 RenderStyle* Node::virtualComputedStyle(PseudoId pseudoElementSpecifier)
1206 return parentOrHostNode() ? parentOrHostNode()->computedStyle(pseudoElementSpecifier) : 0;
1209 int Node::maxCharacterOffset() const
1211 ASSERT_NOT_REACHED();
1215 // FIXME: Shouldn't these functions be in the editing code? Code that asks questions about HTML in the core DOM class
1216 // is obviously misplaced.
1217 bool Node::canStartSelection() const
1219 if (rendererIsEditable())
1223 RenderStyle* style = renderer()->style();
1224 // We allow selections to begin within an element that has -webkit-user-select: none set,
1225 // but if the element is draggable then dragging should take priority over selection.
1226 if (style->userDrag() == DRAG_ELEMENT && style->userSelect() == SELECT_NONE)
1229 return parentOrHostNode() ? parentOrHostNode()->canStartSelection() : true;
1232 Element* Node::shadowHost() const
1234 if (ShadowRoot* root = containingShadowRoot())
1235 return root->host();
1239 Node* Node::shadowAncestorNode() const
1241 if (ShadowRoot* root = containingShadowRoot())
1242 return root->host();
1244 return const_cast<Node*>(this);
1247 ShadowRoot* Node::containingShadowRoot() const
1249 Node* root = const_cast<Node*>(this);
1251 if (root->isShadowRoot())
1252 return toShadowRoot(root);
1253 root = root->parentNodeGuaranteedHostFree();
1258 Node* Node::nonBoundaryShadowTreeRootNode()
1260 ASSERT(!isShadowRoot());
1263 if (root->isShadowRoot())
1265 Node* parent = root->parentNodeGuaranteedHostFree();
1266 if (parent && parent->isShadowRoot())
1273 ContainerNode* Node::nonShadowBoundaryParentNode() const
1275 ContainerNode* parent = parentNode();
1276 return parent && !parent->isShadowRoot() ? parent : 0;
1279 Element* Node::parentOrHostElement() const
1281 ContainerNode* parent = parentOrHostNode();
1285 if (parent->isShadowRoot())
1286 return toShadowRoot(parent)->host();
1288 if (!parent->isElementNode())
1291 return toElement(parent);
1294 bool Node::needsShadowTreeWalkerSlow() const
1296 return (isShadowRoot() || (isElementNode() && (isInsertionPoint() || isPseudoElement() || toElement(this)->hasPseudoElements() || toElement(this)->shadow())));
1299 bool Node::isBlockFlow() const
1301 return renderer() && renderer()->isBlockFlow();
1304 Element *Node::enclosingBlockFlowElement() const
1306 Node *n = const_cast<Node *>(this);
1308 return static_cast<Element *>(n);
1311 n = n->parentNode();
1314 if (n->isBlockFlow() || n->hasTagName(bodyTag))
1315 return static_cast<Element *>(n);
1320 bool Node::isRootEditableElement() const
1322 return rendererIsEditable() && isElementNode() && (!parentNode() || !parentNode()->rendererIsEditable()
1323 || !parentNode()->isElementNode() || hasTagName(bodyTag));
1326 Element* Node::rootEditableElement(EditableType editableType) const
1328 if (editableType == HasEditableAXRole)
1329 return const_cast<Element*>(document()->axObjectCache()->rootAXEditableElement(this));
1331 return rootEditableElement();
1334 Element* Node::rootEditableElement() const
1336 Element* result = 0;
1337 for (Node* n = const_cast<Node*>(this); n && n->rendererIsEditable(); n = n->parentNode()) {
1338 if (n->isElementNode())
1339 result = static_cast<Element*>(n);
1340 if (n->hasTagName(bodyTag))
1346 bool Node::inSameContainingBlockFlowElement(Node *n)
1348 return n ? enclosingBlockFlowElement() == n->enclosingBlockFlowElement() : false;
1351 // FIXME: End of obviously misplaced HTML editing functions. Try to move these out of Node.
1353 PassRefPtr<NodeList> Node::getElementsByTagName(const AtomicString& localName)
1355 if (localName.isNull())
1358 if (document()->isHTMLDocument())
1359 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLTagNodeList>(this, HTMLTagNodeListType, localName);
1360 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<TagNodeList>(this, TagNodeListType, localName);
1363 PassRefPtr<NodeList> Node::getElementsByTagNameNS(const AtomicString& namespaceURI, const AtomicString& localName)
1365 if (localName.isNull())
1368 if (namespaceURI == starAtom)
1369 return getElementsByTagName(localName);
1371 return ensureRareData()->ensureNodeLists()->addCacheWithQualifiedName(this, namespaceURI.isEmpty() ? nullAtom : namespaceURI, localName);
1374 PassRefPtr<NodeList> Node::getElementsByName(const String& elementName)
1376 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<NameNodeList>(this, NameNodeListType, elementName);
1379 PassRefPtr<NodeList> Node::getElementsByClassName(const String& classNames)
1381 return ensureRareData()->ensureNodeLists()->addCacheWithName<ClassNodeList>(this, ClassNodeListType, classNames);
1384 PassRefPtr<RadioNodeList> Node::radioNodeList(const AtomicString& name)
1386 ASSERT(hasTagName(formTag) || hasTagName(fieldsetTag));
1387 return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<RadioNodeList>(this, RadioNodeListType, name);
1390 PassRefPtr<Element> Node::querySelector(const AtomicString& selectors, ExceptionCode& ec)
1392 if (selectors.isEmpty()) {
1397 SelectorQuery* selectorQuery = document()->selectorQueryCache()->add(selectors, document(), ec);
1400 return selectorQuery->queryFirst(this);
1403 PassRefPtr<NodeList> Node::querySelectorAll(const AtomicString& selectors, ExceptionCode& ec)
1405 if (selectors.isEmpty()) {
1410 SelectorQuery* selectorQuery = document()->selectorQueryCache()->add(selectors, document(), ec);
1413 return selectorQuery->queryAll(this);
1416 Document *Node::ownerDocument() const
1418 Document *doc = document();
1419 return doc == this ? 0 : doc;
1422 KURL Node::baseURI() const
1424 return parentNode() ? parentNode()->baseURI() : KURL();
1427 bool Node::isEqualNode(Node* other) const
1432 NodeType nodeType = this->nodeType();
1433 if (nodeType != other->nodeType())
1436 if (nodeName() != other->nodeName())
1439 if (localName() != other->localName())
1442 if (namespaceURI() != other->namespaceURI())
1445 if (prefix() != other->prefix())
1448 if (nodeValue() != other->nodeValue())
1451 if (isElementNode() && !toElement(this)->hasEquivalentAttributes(toElement(other)))
1454 Node* child = firstChild();
1455 Node* otherChild = other->firstChild();
1458 if (!child->isEqualNode(otherChild))
1461 child = child->nextSibling();
1462 otherChild = otherChild->nextSibling();
1468 if (nodeType == DOCUMENT_TYPE_NODE) {
1469 const DocumentType* documentTypeThis = static_cast<const DocumentType*>(this);
1470 const DocumentType* documentTypeOther = static_cast<const DocumentType*>(other);
1472 if (documentTypeThis->publicId() != documentTypeOther->publicId())
1475 if (documentTypeThis->systemId() != documentTypeOther->systemId())
1478 if (documentTypeThis->internalSubset() != documentTypeOther->internalSubset())
1481 // FIXME: We don't compare entities or notations because currently both are always empty.
1487 bool Node::isDefaultNamespace(const AtomicString& namespaceURIMaybeEmpty) const
1489 const AtomicString& namespaceURI = namespaceURIMaybeEmpty.isEmpty() ? nullAtom : namespaceURIMaybeEmpty;
1491 switch (nodeType()) {
1492 case ELEMENT_NODE: {
1493 const Element* elem = static_cast<const Element*>(this);
1495 if (elem->prefix().isNull())
1496 return elem->namespaceURI() == namespaceURI;
1498 if (elem->hasAttributes()) {
1499 for (unsigned i = 0; i < elem->attributeCount(); i++) {
1500 const Attribute* attr = elem->attributeItem(i);
1502 if (attr->localName() == xmlnsAtom)
1503 return attr->value() == namespaceURI;
1507 if (Element* ancestor = ancestorElement())
1508 return ancestor->isDefaultNamespace(namespaceURI);
1513 if (Element* de = static_cast<const Document*>(this)->documentElement())
1514 return de->isDefaultNamespace(namespaceURI);
1518 case DOCUMENT_TYPE_NODE:
1519 case DOCUMENT_FRAGMENT_NODE:
1521 case ATTRIBUTE_NODE: {
1522 const Attr* attr = static_cast<const Attr*>(this);
1523 if (attr->ownerElement())
1524 return attr->ownerElement()->isDefaultNamespace(namespaceURI);
1528 if (Element* ancestor = ancestorElement())
1529 return ancestor->isDefaultNamespace(namespaceURI);
1534 String Node::lookupPrefix(const AtomicString &namespaceURI) const
1536 // Implemented according to
1537 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/namespaces-algorithms.html#lookupNamespacePrefixAlgo
1539 if (namespaceURI.isEmpty())
1542 switch (nodeType()) {
1544 return lookupNamespacePrefix(namespaceURI, static_cast<const Element *>(this));
1546 if (Element* de = static_cast<const Document*>(this)->documentElement())
1547 return de->lookupPrefix(namespaceURI);
1551 case DOCUMENT_FRAGMENT_NODE:
1552 case DOCUMENT_TYPE_NODE:
1554 case ATTRIBUTE_NODE: {
1555 const Attr *attr = static_cast<const Attr *>(this);
1556 if (attr->ownerElement())
1557 return attr->ownerElement()->lookupPrefix(namespaceURI);
1561 if (Element* ancestor = ancestorElement())
1562 return ancestor->lookupPrefix(namespaceURI);
1567 String Node::lookupNamespaceURI(const String &prefix) const
1569 // Implemented according to
1570 // http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/namespaces-algorithms.html#lookupNamespaceURIAlgo
1572 if (!prefix.isNull() && prefix.isEmpty())
1575 switch (nodeType()) {
1576 case ELEMENT_NODE: {
1577 const Element *elem = static_cast<const Element *>(this);
1579 if (!elem->namespaceURI().isNull() && elem->prefix() == prefix)
1580 return elem->namespaceURI();
1582 if (elem->hasAttributes()) {
1583 for (unsigned i = 0; i < elem->attributeCount(); i++) {
1584 const Attribute* attr = elem->attributeItem(i);
1586 if (attr->prefix() == xmlnsAtom && attr->localName() == prefix) {
1587 if (!attr->value().isEmpty())
1588 return attr->value();
1591 } else if (attr->localName() == xmlnsAtom && prefix.isNull()) {
1592 if (!attr->value().isEmpty())
1593 return attr->value();
1599 if (Element* ancestor = ancestorElement())
1600 return ancestor->lookupNamespaceURI(prefix);
1604 if (Element* de = static_cast<const Document*>(this)->documentElement())
1605 return de->lookupNamespaceURI(prefix);
1609 case DOCUMENT_TYPE_NODE:
1610 case DOCUMENT_FRAGMENT_NODE:
1612 case ATTRIBUTE_NODE: {
1613 const Attr *attr = static_cast<const Attr *>(this);
1615 if (attr->ownerElement())
1616 return attr->ownerElement()->lookupNamespaceURI(prefix);
1621 if (Element* ancestor = ancestorElement())
1622 return ancestor->lookupNamespaceURI(prefix);
1627 String Node::lookupNamespacePrefix(const AtomicString &_namespaceURI, const Element *originalElement) const
1629 if (_namespaceURI.isNull())
1632 if (originalElement->lookupNamespaceURI(prefix()) == _namespaceURI)
1635 ASSERT(isElementNode());
1636 const Element* thisElement = toElement(this);
1637 if (thisElement->hasAttributes()) {
1638 for (unsigned i = 0; i < thisElement->attributeCount(); i++) {
1639 const Attribute* attr = thisElement->attributeItem(i);
1641 if (attr->prefix() == xmlnsAtom && attr->value() == _namespaceURI
1642 && originalElement->lookupNamespaceURI(attr->localName()) == _namespaceURI)
1643 return attr->localName();
1647 if (Element* ancestor = ancestorElement())
1648 return ancestor->lookupNamespacePrefix(_namespaceURI, originalElement);
1652 static void appendTextContent(const Node* node, bool convertBRsToNewlines, bool& isNullString, StringBuilder& content)
1654 switch (node->nodeType()) {
1655 case Node::TEXT_NODE:
1656 case Node::CDATA_SECTION_NODE:
1657 case Node::COMMENT_NODE:
1658 isNullString = false;
1659 content.append(static_cast<const CharacterData*>(node)->data());
1662 case Node::PROCESSING_INSTRUCTION_NODE:
1663 isNullString = false;
1664 content.append(static_cast<const ProcessingInstruction*>(node)->data());
1667 case Node::ELEMENT_NODE:
1668 if (node->hasTagName(brTag) && convertBRsToNewlines) {
1669 isNullString = false;
1670 content.append('\n');
1674 case Node::ATTRIBUTE_NODE:
1675 case Node::ENTITY_NODE:
1676 case Node::ENTITY_REFERENCE_NODE:
1677 case Node::DOCUMENT_FRAGMENT_NODE:
1678 isNullString = false;
1679 for (Node* child = node->firstChild(); child; child = child->nextSibling()) {
1680 if (child->nodeType() == Node::COMMENT_NODE || child->nodeType() == Node::PROCESSING_INSTRUCTION_NODE)
1682 appendTextContent(child, convertBRsToNewlines, isNullString, content);
1686 case Node::DOCUMENT_NODE:
1687 case Node::DOCUMENT_TYPE_NODE:
1688 case Node::NOTATION_NODE:
1689 case Node::XPATH_NAMESPACE_NODE:
1694 String Node::textContent(bool convertBRsToNewlines) const
1696 StringBuilder content;
1697 bool isNullString = true;
1698 appendTextContent(this, convertBRsToNewlines, isNullString, content);
1699 return isNullString ? String() : content.toString();
1702 void Node::setTextContent(const String& text, ExceptionCode& ec)
1704 switch (nodeType()) {
1706 case CDATA_SECTION_NODE:
1708 case PROCESSING_INSTRUCTION_NODE:
1709 setNodeValue(text, ec);
1712 case ATTRIBUTE_NODE:
1714 case ENTITY_REFERENCE_NODE:
1715 case DOCUMENT_FRAGMENT_NODE: {
1716 RefPtr<ContainerNode> container = toContainerNode(this);
1717 #if ENABLE(MUTATION_OBSERVERS)
1718 ChildListMutationScope mutation(this);
1720 container->removeChildren();
1721 if (!text.isEmpty())
1722 container->appendChild(document()->createTextNode(text), ec);
1726 case DOCUMENT_TYPE_NODE:
1728 case XPATH_NAMESPACE_NODE:
1732 ASSERT_NOT_REACHED();
1735 Element* Node::ancestorElement() const
1737 // In theory, there can be EntityReference nodes between elements, but this is currently not supported.
1738 for (ContainerNode* n = parentNode(); n; n = n->parentNode()) {
1739 if (n->isElementNode())
1740 return static_cast<Element*>(n);
1745 bool Node::offsetInCharacters() const
1750 unsigned short Node::compareDocumentPosition(Node* otherNode)
1752 // It is not clear what should be done if |otherNode| is 0.
1754 return DOCUMENT_POSITION_DISCONNECTED;
1756 if (otherNode == this)
1757 return DOCUMENT_POSITION_EQUIVALENT;
1759 Attr* attr1 = nodeType() == ATTRIBUTE_NODE ? static_cast<Attr*>(this) : 0;
1760 Attr* attr2 = otherNode->nodeType() == ATTRIBUTE_NODE ? static_cast<Attr*>(otherNode) : 0;
1762 Node* start1 = attr1 ? attr1->ownerElement() : this;
1763 Node* start2 = attr2 ? attr2->ownerElement() : otherNode;
1765 // If either of start1 or start2 is null, then we are disconnected, since one of the nodes is
1766 // an orphaned attribute node.
1767 if (!start1 || !start2)
1768 return DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC;
1770 Vector<Node*, 16> chain1;
1771 Vector<Node*, 16> chain2;
1773 chain1.append(attr1);
1775 chain2.append(attr2);
1777 if (attr1 && attr2 && start1 == start2 && start1) {
1778 // We are comparing two attributes on the same node. Crawl our attribute map and see which one we hit first.
1779 Element* owner1 = attr1->ownerElement();
1780 owner1->updatedAttributeData(); // Force update invalid attributes.
1781 unsigned length = owner1->attributeCount();
1782 for (unsigned i = 0; i < length; ++i) {
1783 // If neither of the two determining nodes is a child node and nodeType is the same for both determining nodes, then an
1784 // implementation-dependent order between the determining nodes is returned. This order is stable as long as no nodes of
1785 // the same nodeType are inserted into or removed from the direct container. This would be the case, for example,
1786 // when comparing two attributes of the same element, and inserting or removing additional attributes might change
1787 // the order between existing attributes.
1788 const Attribute* attribute = owner1->attributeItem(i);
1789 if (attr1->qualifiedName() == attribute->name())
1790 return DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | DOCUMENT_POSITION_FOLLOWING;
1791 if (attr2->qualifiedName() == attribute->name())
1792 return DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | DOCUMENT_POSITION_PRECEDING;
1795 ASSERT_NOT_REACHED();
1796 return DOCUMENT_POSITION_DISCONNECTED;
1799 // If one node is in the document and the other is not, we must be disconnected.
1800 // If the nodes have different owning documents, they must be disconnected. Note that we avoid
1801 // comparing Attr nodes here, since they return false from inDocument() all the time (which seems like a bug).
1802 if (start1->inDocument() != start2->inDocument() ||
1803 start1->treeScope() != start2->treeScope())
1804 return DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC;
1806 // We need to find a common ancestor container, and then compare the indices of the two immediate children.
1808 for (current = start1; current; current = current->parentNode())
1809 chain1.append(current);
1810 for (current = start2; current; current = current->parentNode())
1811 chain2.append(current);
1813 // Walk the two chains backwards and look for the first difference.
1814 unsigned index1 = chain1.size();
1815 unsigned index2 = chain2.size();
1816 for (unsigned i = min(index1, index2); i; --i) {
1817 Node* child1 = chain1[--index1];
1818 Node* child2 = chain2[--index2];
1819 if (child1 != child2) {
1820 // If one of the children is an attribute, it wins.
1821 if (child1->nodeType() == ATTRIBUTE_NODE)
1822 return DOCUMENT_POSITION_FOLLOWING;
1823 if (child2->nodeType() == ATTRIBUTE_NODE)
1824 return DOCUMENT_POSITION_PRECEDING;
1826 if (!child2->nextSibling())
1827 return DOCUMENT_POSITION_FOLLOWING;
1828 if (!child1->nextSibling())
1829 return DOCUMENT_POSITION_PRECEDING;
1831 // Otherwise we need to see which node occurs first. Crawl backwards from child2 looking for child1.
1832 for (Node* child = child2->previousSibling(); child; child = child->previousSibling()) {
1833 if (child == child1)
1834 return DOCUMENT_POSITION_FOLLOWING;
1836 return DOCUMENT_POSITION_PRECEDING;
1840 // There was no difference between the two parent chains, i.e., one was a subset of the other. The shorter
1841 // chain is the ancestor.
1842 return index1 < index2 ?
1843 DOCUMENT_POSITION_FOLLOWING | DOCUMENT_POSITION_CONTAINED_BY :
1844 DOCUMENT_POSITION_PRECEDING | DOCUMENT_POSITION_CONTAINS;
1847 FloatPoint Node::convertToPage(const FloatPoint& p) const
1849 // If there is a renderer, just ask it to do the conversion
1851 return renderer()->localToAbsolute(p, UseTransforms);
1853 // Otherwise go up the tree looking for a renderer
1854 Element *parent = ancestorElement();
1856 return parent->convertToPage(p);
1858 // No parent - no conversion needed
1862 FloatPoint Node::convertFromPage(const FloatPoint& p) const
1864 // If there is a renderer, just ask it to do the conversion
1866 return renderer()->absoluteToLocal(p, UseTransforms);
1868 // Otherwise go up the tree looking for a renderer
1869 Element *parent = ancestorElement();
1871 return parent->convertFromPage(p);
1873 // No parent - no conversion needed
1879 static void appendAttributeDesc(const Node* node, StringBuilder& stringBuilder, const QualifiedName& name, const char* attrDesc)
1881 if (!node->isElementNode())
1884 String attr = static_cast<const Element*>(node)->getAttribute(name);
1888 stringBuilder.append(attrDesc);
1889 stringBuilder.append(attr);
1892 void Node::showNode(const char* prefix) const
1897 String value = nodeValue();
1898 value.replaceWithLiteral('\\', "\\\\");
1899 value.replaceWithLiteral('\n', "\\n");
1900 fprintf(stderr, "%s%s\t%p \"%s\"\n", prefix, nodeName().utf8().data(), this, value.utf8().data());
1902 StringBuilder attrs;
1903 appendAttributeDesc(this, attrs, classAttr, " CLASS=");
1904 appendAttributeDesc(this, attrs, styleAttr, " STYLE=");
1905 fprintf(stderr, "%s%s\t%p%s\n", prefix, nodeName().utf8().data(), this, attrs.toString().utf8().data());
1909 void Node::showTreeForThis() const
1911 showTreeAndMark(this, "*");
1914 void Node::showNodePathForThis() const
1916 Vector<const Node*, 16> chain;
1917 const Node* node = this;
1918 while (node->parentOrHostNode()) {
1920 node = node->parentOrHostNode();
1922 for (unsigned index = chain.size(); index > 0; --index) {
1923 const Node* node = chain[index - 1];
1924 if (node->isShadowRoot()) {
1926 for (ShadowRoot* shadowRoot = oldestShadowRootFor(toShadowRoot(node)->host()); shadowRoot && shadowRoot != node; shadowRoot = shadowRoot->youngerShadowRoot())
1928 fprintf(stderr, "/#shadow-root[%d]", count);
1932 switch (node->nodeType()) {
1933 case ELEMENT_NODE: {
1934 fprintf(stderr, "/%s", node->nodeName().utf8().data());
1936 const Element* element = toElement(node);
1937 const AtomicString& idattr = element->getIdAttribute();
1938 bool hasIdAttr = !idattr.isNull() && !idattr.isEmpty();
1939 if (node->previousSibling() || node->nextSibling()) {
1941 for (Node* previous = node->previousSibling(); previous; previous = previous->previousSibling())
1942 if (previous->nodeName() == node->nodeName())
1945 fprintf(stderr, "[@id=\"%s\" and position()=%d]", idattr.string().utf8().data(), count);
1947 fprintf(stderr, "[%d]", count);
1948 } else if (hasIdAttr)
1949 fprintf(stderr, "[@id=\"%s\"]", idattr.string().utf8().data());
1953 fprintf(stderr, "/text()");
1955 case ATTRIBUTE_NODE:
1956 fprintf(stderr, "/@%s", node->nodeName().utf8().data());
1962 fprintf(stderr, "\n");
1965 static void traverseTreeAndMark(const String& baseIndent, const Node* rootNode, const Node* markedNode1, const char* markedLabel1, const Node* markedNode2, const char* markedLabel2)
1967 for (const Node* node = rootNode; node; node = NodeTraversal::next(node)) {
1968 if (node == markedNode1)
1969 fprintf(stderr, "%s", markedLabel1);
1970 if (node == markedNode2)
1971 fprintf(stderr, "%s", markedLabel2);
1973 StringBuilder indent;
1974 indent.append(baseIndent);
1975 for (const Node* tmpNode = node; tmpNode && tmpNode != rootNode; tmpNode = tmpNode->parentOrHostNode())
1976 indent.append('\t');
1977 fprintf(stderr, "%s", indent.toString().utf8().data());
1979 indent.append('\t');
1980 if (node->isShadowRoot()) {
1981 if (ShadowRoot* youngerShadowRoot = toShadowRoot(node)->youngerShadowRoot())
1982 traverseTreeAndMark(indent.toString(), youngerShadowRoot, markedNode1, markedLabel1, markedNode2, markedLabel2);
1983 } else if (ShadowRoot* oldestShadowRoot = oldestShadowRootFor(node))
1984 traverseTreeAndMark(indent.toString(), oldestShadowRoot, markedNode1, markedLabel1, markedNode2, markedLabel2);
1988 void Node::showTreeAndMark(const Node* markedNode1, const char* markedLabel1, const Node* markedNode2, const char* markedLabel2) const
1990 const Node* rootNode;
1991 const Node* node = this;
1992 while (node->parentOrHostNode() && !node->hasTagName(bodyTag))
1993 node = node->parentOrHostNode();
1996 String startingIndent;
1997 traverseTreeAndMark(startingIndent, rootNode, markedNode1, markedLabel1, markedNode2, markedLabel2);
2000 void Node::formatForDebugger(char* buffer, unsigned length) const
2011 strncpy(buffer, result.utf8().data(), length - 1);
2014 static ContainerNode* parentOrHostOrFrameOwner(const Node* node)
2016 ContainerNode* parent = node->parentOrHostNode();
2017 if (!parent && node->document() && node->document()->frame())
2018 parent = node->document()->frame()->ownerElement();
2022 static void showSubTreeAcrossFrame(const Node* node, const Node* markedNode, const String& indent)
2024 if (node == markedNode)
2026 fputs(indent.utf8().data(), stderr);
2028 if (node->isShadowRoot()) {
2029 if (ShadowRoot* youngerShadowRoot = toShadowRoot(node)->youngerShadowRoot())
2030 showSubTreeAcrossFrame(youngerShadowRoot, markedNode, indent + "\t");
2032 if (node->isFrameOwnerElement())
2033 showSubTreeAcrossFrame(static_cast<const HTMLFrameOwnerElement*>(node)->contentDocument(), markedNode, indent + "\t");
2034 if (ShadowRoot* oldestShadowRoot = oldestShadowRootFor(node))
2035 showSubTreeAcrossFrame(oldestShadowRoot, markedNode, indent + "\t");
2037 for (Node* child = node->firstChild(); child; child = child->nextSibling())
2038 showSubTreeAcrossFrame(child, markedNode, indent + "\t");
2041 void Node::showTreeForThisAcrossFrame() const
2043 Node* rootNode = const_cast<Node*>(this);
2044 while (parentOrHostOrFrameOwner(rootNode))
2045 rootNode = parentOrHostOrFrameOwner(rootNode);
2046 showSubTreeAcrossFrame(rootNode, this, "");
2053 void NodeListsNodeData::invalidateCaches(const QualifiedName* attrName)
2055 NodeListAtomicNameCacheMap::const_iterator atomicNameCacheEnd = m_atomicNameCaches.end();
2056 for (NodeListAtomicNameCacheMap::const_iterator it = m_atomicNameCaches.begin(); it != atomicNameCacheEnd; ++it)
2057 it->value->invalidateCache(attrName);
2059 NodeListNameCacheMap::const_iterator nameCacheEnd = m_nameCaches.end();
2060 for (NodeListNameCacheMap::const_iterator it = m_nameCaches.begin(); it != nameCacheEnd; ++it)
2061 it->value->invalidateCache(attrName);
2066 TagNodeListCacheNS::iterator tagCacheEnd = m_tagNodeListCacheNS.end();
2067 for (TagNodeListCacheNS::iterator it = m_tagNodeListCacheNS.begin(); it != tagCacheEnd; ++it)
2068 it->value->invalidateCache();
2071 void Node::getSubresourceURLs(ListHashSet<KURL>& urls) const
2073 addSubresourceAttributeURLs(urls);
2076 Node* Node::enclosingLinkEventParentOrSelf()
2078 for (Node* node = this; node; node = node->parentOrHostNode()) {
2079 // For imagemaps, the enclosing link node is the associated area element not the image itself.
2080 // So we don't let images be the enclosingLinkNode, even though isLink sometimes returns true
2082 if (node->isLink() && !node->hasTagName(imgTag))
2089 const AtomicString& Node::interfaceName() const
2091 return eventNames().interfaceForNode;
2094 ScriptExecutionContext* Node::scriptExecutionContext() const
2099 void Node::didMoveToNewDocument(Document* oldDocument)
2101 TreeScopeAdopter::ensureDidMoveToNewDocumentWasCalled(oldDocument);
2103 // FIXME: Event listener types for this node should be set on the new owner document here.
2105 const EventListenerVector& wheelListeners = getEventListeners(eventNames().mousewheelEvent);
2106 for (size_t i = 0; i < wheelListeners.size(); ++i) {
2107 oldDocument->didRemoveWheelEventHandler();
2108 document()->didAddWheelEventHandler();
2111 Vector<AtomicString> touchEventNames = eventNames().touchEventNames();
2112 for (size_t i = 0; i < touchEventNames.size(); ++i) {
2113 const EventListenerVector& listeners = getEventListeners(touchEventNames[i]);
2114 for (size_t j = 0; j < listeners.size(); ++j) {
2115 oldDocument->didRemoveTouchEventHandler(this);
2116 document()->didAddTouchEventHandler(this);
2120 #if ENABLE(MUTATION_OBSERVERS)
2121 if (Vector<OwnPtr<MutationObserverRegistration> >* registry = mutationObserverRegistry()) {
2122 for (size_t i = 0; i < registry->size(); ++i) {
2123 document()->addMutationObserverTypes(registry->at(i)->mutationTypes());
2127 if (HashSet<MutationObserverRegistration*>* transientRegistry = transientMutationObserverRegistry()) {
2128 for (HashSet<MutationObserverRegistration*>::iterator iter = transientRegistry->begin(); iter != transientRegistry->end(); ++iter) {
2129 document()->addMutationObserverTypes((*iter)->mutationTypes());
2135 static inline bool tryAddEventListener(Node* targetNode, const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
2137 if (!targetNode->EventTarget::addEventListener(eventType, listener, useCapture))
2140 if (Document* document = targetNode->document()) {
2141 document->addListenerTypeIfNeeded(eventType);
2142 if (eventType == eventNames().mousewheelEvent)
2143 document->didAddWheelEventHandler();
2144 else if (eventNames().isTouchEventType(eventType))
2145 document->didAddTouchEventHandler(targetNode);
2151 bool Node::addEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
2153 return tryAddEventListener(this, eventType, listener, useCapture);
2156 static inline bool tryRemoveEventListener(Node* targetNode, const AtomicString& eventType, EventListener* listener, bool useCapture)
2158 if (!targetNode->EventTarget::removeEventListener(eventType, listener, useCapture))
2161 // FIXME: Notify Document that the listener has vanished. We need to keep track of a number of
2162 // listeners for each type, not just a bool - see https://bugs.webkit.org/show_bug.cgi?id=33861
2163 if (Document* document = targetNode->document()) {
2164 if (eventType == eventNames().mousewheelEvent)
2165 document->didRemoveWheelEventHandler();
2166 else if (eventNames().isTouchEventType(eventType))
2167 document->didRemoveTouchEventHandler(targetNode);
2173 bool Node::removeEventListener(const AtomicString& eventType, EventListener* listener, bool useCapture)
2175 return tryRemoveEventListener(this, eventType, listener, useCapture);
2178 typedef HashMap<Node*, OwnPtr<EventTargetData> > EventTargetDataMap;
2180 static EventTargetDataMap& eventTargetDataMap()
2182 DEFINE_STATIC_LOCAL(EventTargetDataMap, map, ());
2186 EventTargetData* Node::eventTargetData()
2188 return hasEventTargetData() ? eventTargetDataMap().get(this) : 0;
2191 EventTargetData* Node::ensureEventTargetData()
2193 if (hasEventTargetData())
2194 return eventTargetDataMap().get(this);
2195 setHasEventTargetData(true);
2196 EventTargetData* data = new EventTargetData;
2197 eventTargetDataMap().set(this, adoptPtr(data));
2201 void Node::clearEventTargetData()
2203 eventTargetDataMap().remove(this);
2206 #if ENABLE(MUTATION_OBSERVERS)
2207 Vector<OwnPtr<MutationObserverRegistration> >* Node::mutationObserverRegistry()
2209 return hasRareData() ? rareData()->mutationObserverRegistry() : 0;
2212 HashSet<MutationObserverRegistration*>* Node::transientMutationObserverRegistry()
2214 return hasRareData() ? rareData()->transientMutationObserverRegistry() : 0;
2217 template<typename Registry>
2218 static inline void collectMatchingObserversForMutation(HashMap<MutationObserver*, MutationRecordDeliveryOptions>& observers, Registry* registry, Node* target, MutationObserver::MutationType type, const QualifiedName* attributeName)
2222 for (typename Registry::iterator iter = registry->begin(); iter != registry->end(); ++iter) {
2223 const MutationObserverRegistration& registration = **iter;
2224 if (registration.shouldReceiveMutationFrom(target, type, attributeName)) {
2225 MutationRecordDeliveryOptions deliveryOptions = registration.deliveryOptions();
2226 HashMap<MutationObserver*, MutationRecordDeliveryOptions>::AddResult result = observers.add(registration.observer(), deliveryOptions);
2227 if (!result.isNewEntry)
2228 result.iterator->value |= deliveryOptions;
2233 void Node::getRegisteredMutationObserversOfType(HashMap<MutationObserver*, MutationRecordDeliveryOptions>& observers, MutationObserver::MutationType type, const QualifiedName* attributeName)
2235 ASSERT((type == MutationObserver::Attributes && attributeName) || !attributeName);
2236 collectMatchingObserversForMutation(observers, mutationObserverRegistry(), this, type, attributeName);
2237 collectMatchingObserversForMutation(observers, transientMutationObserverRegistry(), this, type, attributeName);
2238 for (Node* node = parentNode(); node; node = node->parentNode()) {
2239 collectMatchingObserversForMutation(observers, node->mutationObserverRegistry(), this, type, attributeName);
2240 collectMatchingObserversForMutation(observers, node->transientMutationObserverRegistry(), this, type, attributeName);
2244 void Node::registerMutationObserver(MutationObserver* observer, MutationObserverOptions options, const HashSet<AtomicString>& attributeFilter)
2246 MutationObserverRegistration* registration = 0;
2247 Vector<OwnPtr<MutationObserverRegistration> >* registry = ensureRareData()->ensureMutationObserverRegistry();
2248 for (size_t i = 0; i < registry->size(); ++i) {
2249 if (registry->at(i)->observer() == observer) {
2250 registration = registry->at(i).get();
2251 registration->resetObservation(options, attributeFilter);
2255 if (!registration) {
2256 registry->append(MutationObserverRegistration::create(observer, this, options, attributeFilter));
2257 registration = registry->last().get();
2260 document()->addMutationObserverTypes(registration->mutationTypes());
2263 void Node::unregisterMutationObserver(MutationObserverRegistration* registration)
2265 Vector<OwnPtr<MutationObserverRegistration> >* registry = mutationObserverRegistry();
2270 size_t index = registry->find(registration);
2271 ASSERT(index != notFound);
2272 if (index == notFound)
2275 registry->remove(index);
2278 void Node::registerTransientMutationObserver(MutationObserverRegistration* registration)
2280 ensureRareData()->ensureTransientMutationObserverRegistry()->add(registration);
2283 void Node::unregisterTransientMutationObserver(MutationObserverRegistration* registration)
2285 HashSet<MutationObserverRegistration*>* transientRegistry = transientMutationObserverRegistry();
2286 ASSERT(transientRegistry);
2287 if (!transientRegistry)
2290 ASSERT(transientRegistry->contains(registration));
2291 transientRegistry->remove(registration);
2294 void Node::notifyMutationObserversNodeWillDetach()
2296 if (!document()->hasMutationObservers())
2299 for (Node* node = parentNode(); node; node = node->parentNode()) {
2300 if (Vector<OwnPtr<MutationObserverRegistration> >* registry = node->mutationObserverRegistry()) {
2301 const size_t size = registry->size();
2302 for (size_t i = 0; i < size; ++i)
2303 registry->at(i)->observedSubtreeNodeWillDetach(this);
2306 if (HashSet<MutationObserverRegistration*>* transientRegistry = node->transientMutationObserverRegistry()) {
2307 for (HashSet<MutationObserverRegistration*>::iterator iter = transientRegistry->begin(); iter != transientRegistry->end(); ++iter)
2308 (*iter)->observedSubtreeNodeWillDetach(this);
2312 #endif // ENABLE(MUTATION_OBSERVERS)
2314 void Node::handleLocalEvents(Event* event)
2316 if (!hasEventTargetData())
2319 if (disabled() && event->isMouseEvent())
2322 fireEventListeners(event);
2325 void Node::dispatchScopedEvent(PassRefPtr<Event> event)
2327 dispatchScopedEventDispatchMediator(EventDispatchMediator::create(event));
2330 void Node::dispatchScopedEventDispatchMediator(PassRefPtr<EventDispatchMediator> eventDispatchMediator)
2332 EventDispatcher::dispatchScopedEvent(this, eventDispatchMediator);
2335 bool Node::dispatchEvent(PassRefPtr<Event> event)
2337 if (event->isMouseEvent())
2338 return EventDispatcher::dispatchEvent(this, MouseEventDispatchMediator::create(adoptRef(toMouseEvent(event.leakRef())), MouseEventDispatchMediator::SyntheticMouseEvent));
2339 return EventDispatcher::dispatchEvent(this, EventDispatchMediator::create(event));
2342 void Node::dispatchSubtreeModifiedEvent()
2344 if (isInShadowTree())
2347 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2349 if (!document()->hasListenerType(Document::DOMSUBTREEMODIFIED_LISTENER))
2352 dispatchScopedEvent(MutationEvent::create(eventNames().DOMSubtreeModifiedEvent, true));
2355 void Node::dispatchFocusInEvent(const AtomicString& eventType, PassRefPtr<Node> oldFocusedNode)
2357 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2358 ASSERT(eventType == eventNames().focusinEvent || eventType == eventNames().DOMFocusInEvent);
2359 dispatchScopedEventDispatchMediator(FocusInEventDispatchMediator::create(UIEvent::create(eventType, true, false, document()->defaultView(), 0), oldFocusedNode));
2362 void Node::dispatchFocusOutEvent(const AtomicString& eventType, PassRefPtr<Node> newFocusedNode)
2364 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2365 ASSERT(eventType == eventNames().focusoutEvent || eventType == eventNames().DOMFocusOutEvent);
2366 dispatchScopedEventDispatchMediator(FocusOutEventDispatchMediator::create(UIEvent::create(eventType, true, false, document()->defaultView(), 0), newFocusedNode));
2369 bool Node::dispatchDOMActivateEvent(int detail, PassRefPtr<Event> underlyingEvent)
2371 ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
2372 RefPtr<UIEvent> event = UIEvent::create(eventNames().DOMActivateEvent, true, true, document()->defaultView(), detail);
2373 event->setUnderlyingEvent(underlyingEvent);
2374 dispatchScopedEvent(event);
2375 return event->defaultHandled();
2378 bool Node::dispatchKeyEvent(const PlatformKeyboardEvent& event)
2380 return EventDispatcher::dispatchEvent(this, KeyboardEventDispatchMediator::create(KeyboardEvent::create(event, document()->defaultView())));
2383 bool Node::dispatchMouseEvent(const PlatformMouseEvent& event, const AtomicString& eventType,
2384 int detail, Node* relatedTarget)
2386 return EventDispatcher::dispatchEvent(this, MouseEventDispatchMediator::create(MouseEvent::create(eventType, document()->defaultView(), event, detail, relatedTarget)));
2389 #if ENABLE(GESTURE_EVENTS)
2390 bool Node::dispatchGestureEvent(const PlatformGestureEvent& event)
2392 RefPtr<GestureEvent> gestureEvent = GestureEvent::create(document()->defaultView(), event);
2393 if (!gestureEvent.get())
2395 return EventDispatcher::dispatchEvent(this, GestureEventDispatchMediator::create(gestureEvent));
2399 void Node::dispatchSimulatedClick(Event* underlyingEvent, SimulatedClickMouseEventOptions eventOptions, SimulatedClickVisualOptions visualOptions)
2401 EventDispatcher::dispatchSimulatedClick(this, underlyingEvent, eventOptions, visualOptions);
2404 bool Node::dispatchBeforeLoadEvent(const String& sourceURL)
2406 if (!document()->hasListenerType(Document::BEFORELOAD_LISTENER))
2409 RefPtr<Node> protector(this);
2410 RefPtr<BeforeLoadEvent> beforeLoadEvent = BeforeLoadEvent::create(sourceURL);
2411 dispatchEvent(beforeLoadEvent.get());
2412 return !beforeLoadEvent->defaultPrevented();
2415 bool Node::dispatchWheelEvent(const PlatformWheelEvent& event)
2417 return EventDispatcher::dispatchEvent(this, WheelEventDispatchMediator::create(event, document()->defaultView()));
2420 void Node::dispatchFocusEvent(PassRefPtr<Node> oldFocusedNode)
2422 if (document()->page())
2423 document()->page()->chrome()->client()->elementDidFocus(this);
2425 EventDispatcher::dispatchEvent(this, FocusEventDispatchMediator::create(oldFocusedNode));
2428 void Node::dispatchBlurEvent(PassRefPtr<Node> newFocusedNode)
2430 if (document()->page())
2431 document()->page()->chrome()->client()->elementDidBlur(this);
2433 EventDispatcher::dispatchEvent(this, BlurEventDispatchMediator::create(newFocusedNode));
2436 void Node::dispatchChangeEvent()
2438 dispatchScopedEvent(Event::create(eventNames().changeEvent, true, false));
2441 void Node::dispatchInputEvent()
2443 dispatchScopedEvent(Event::create(eventNames().inputEvent, true, false));
2446 bool Node::disabled() const
2451 void Node::defaultEventHandler(Event* event)
2453 if (event->target() != this)
2455 const AtomicString& eventType = event->type();
2456 if (eventType == eventNames().keydownEvent || eventType == eventNames().keypressEvent) {
2457 if (event->isKeyboardEvent())
2458 if (Frame* frame = document()->frame())
2459 frame->eventHandler()->defaultKeyboardEventHandler(static_cast<KeyboardEvent*>(event));
2460 } else if (eventType == eventNames().clickEvent) {
2461 int detail = event->isUIEvent() ? static_cast<UIEvent*>(event)->detail() : 0;
2462 if (dispatchDOMActivateEvent(detail, event))
2463 event->setDefaultHandled();
2464 #if ENABLE(CONTEXT_MENUS)
2465 } else if (eventType == eventNames().contextmenuEvent) {
2466 if (Frame* frame = document()->frame())
2467 if (Page* page = frame->page())
2468 page->contextMenuController()->handleContextMenuEvent(event);
2470 } else if (eventType == eventNames().textInputEvent) {
2471 if (event->hasInterface(eventNames().interfaceForTextEvent))
2472 if (Frame* frame = document()->frame())
2473 frame->eventHandler()->defaultTextInputEventHandler(static_cast<TextEvent*>(event));
2474 #if ENABLE(PAN_SCROLLING)
2475 } else if (eventType == eventNames().mousedownEvent && event->isMouseEvent()) {
2476 MouseEvent* mouseEvent = static_cast<MouseEvent*>(event);
2477 if (mouseEvent->button() == MiddleButton) {
2478 if (enclosingLinkEventParentOrSelf())
2481 RenderObject* renderer = this->renderer();
2482 while (renderer && (!renderer->isBox() || !toRenderBox(renderer)->canBeScrolledAndHasScrollableArea()))
2483 renderer = renderer->parent();
2486 if (Frame* frame = document()->frame())
2487 frame->eventHandler()->startPanScrolling(renderer);
2491 } else if (eventType == eventNames().mousewheelEvent && event->hasInterface(eventNames().interfaceForWheelEvent)) {
2492 WheelEvent* wheelEvent = static_cast<WheelEvent*>(event);
2494 // If we don't have a renderer, send the wheel event to the first node we find with a renderer.
2495 // This is needed for <option> and <optgroup> elements so that <select>s get a wheel scroll.
2496 Node* startNode = this;
2497 while (startNode && !startNode->renderer())
2498 startNode = startNode->parentOrHostNode();
2500 if (startNode && startNode->renderer())
2501 if (Frame* frame = document()->frame())
2502 frame->eventHandler()->defaultWheelEventHandler(startNode, wheelEvent);
2503 } else if (event->type() == eventNames().webkitEditableContentChangedEvent) {
2504 dispatchInputEvent();
2508 bool Node::willRespondToMouseMoveEvents()
2512 return hasEventListeners(eventNames().mousemoveEvent) || hasEventListeners(eventNames().mouseoverEvent) || hasEventListeners(eventNames().mouseoutEvent);
2515 bool Node::willRespondToMouseClickEvents()
2519 return isContentEditable(UserSelectAllIsAlwaysNonEditable) || hasEventListeners(eventNames().mouseupEvent) || hasEventListeners(eventNames().mousedownEvent) || hasEventListeners(eventNames().clickEvent) || hasEventListeners(eventNames().DOMActivateEvent);
2522 bool Node::willRespondToTouchEvents()
2524 #if ENABLE(TOUCH_EVENTS)
2527 return hasEventListeners(eventNames().touchstartEvent) || hasEventListeners(eventNames().touchmoveEvent) || hasEventListeners(eventNames().touchcancelEvent) || hasEventListeners(eventNames().touchendEvent);
2533 #if ENABLE(MICRODATA)
2534 DOMSettableTokenList* Node::itemProp()
2536 return ensureRareData()->itemProp();
2539 void Node::setItemProp(const String& value)
2541 ensureRareData()->setItemProp(value);
2544 DOMSettableTokenList* Node::itemRef()
2546 return ensureRareData()->itemRef();
2549 void Node::setItemRef(const String& value)
2551 ensureRareData()->setItemRef(value);
2554 DOMSettableTokenList* Node::itemType()
2556 return ensureRareData()->itemType();
2559 void Node::setItemType(const String& value)
2561 ensureRareData()->setItemType(value);
2564 PassRefPtr<PropertyNodeList> Node::propertyNodeList(const String& name)
2566 return ensureRareData()->ensureNodeLists()->addCacheWithName<PropertyNodeList>(this, PropertyNodeListType, name);
2570 // It's important not to inline removedLastRef, because we don't want to inline the code to
2571 // delete a Node at each deref call site.
2572 void Node::removedLastRef()
2574 // An explicit check for Document here is better than a virtual function since it is
2575 // faster for non-Document nodes, and because the call to removedLastRef that is inlined
2576 // at all deref call sites is smaller if it's a non-virtual function.
2577 if (isDocumentNode()) {
2578 static_cast<Document*>(this)->removedLastRef();
2582 m_deletionHasBegun = true;
2587 void Node::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
2589 MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::DOM);
2590 TreeShared<Node, ContainerNode>::reportMemoryUsage(memoryObjectInfo);
2591 ScriptWrappable::reportMemoryUsage(memoryObjectInfo);
2592 info.addMember(m_document);
2593 info.addMember(m_next);
2594 info.addMember(m_previous);
2595 info.addMember(this->renderer());
2597 info.addMember(rareData());
2600 void Node::textRects(Vector<IntRect>& rects) const
2602 RefPtr<Range> range = Range::create(document());
2603 WebCore::ExceptionCode ec = 0;
2604 range->selectNodeContents(const_cast<Node*>(this), ec);
2605 range->textRects(rects);
2608 void Node::registerScopedHTMLStyleChild()
2610 setHasScopedHTMLStyleChild(true);
2613 void Node::unregisterScopedHTMLStyleChild()
2615 ASSERT(hasScopedHTMLStyleChild());
2616 setHasScopedHTMLStyleChild(numberOfScopedHTMLStyleChildren());
2619 size_t Node::numberOfScopedHTMLStyleChildren() const
2622 for (Node* child = firstChild(); child; child = child->nextSibling()) {
2623 if (child->hasTagName(HTMLNames::styleTag) && static_cast<HTMLStyleElement*>(child)->isRegisteredAsScoped())
2630 void Node::setFocus(bool flag)
2632 if (Document* document = this->document())
2633 document->userActionElements().setFocused(this, flag);
2636 void Node::setActive(bool flag, bool)
2638 if (Document* document = this->document())
2639 document->userActionElements().setActive(this, flag);
2642 void Node::setHovered(bool flag)
2644 if (Document* document = this->document())
2645 document->userActionElements().setHovered(this, flag);
2648 bool Node::isUserActionElementActive() const
2650 ASSERT(isUserActionElement());
2651 return document()->userActionElements().isActive(this);
2654 bool Node::isUserActionElementInActiveChain() const
2656 ASSERT(isUserActionElement());
2657 return document()->userActionElements().isInActiveChain(this);
2660 bool Node::isUserActionElementHovered() const
2662 ASSERT(isUserActionElement());
2663 return document()->userActionElements().isHovered(this);
2666 bool Node::isUserActionElementFocused() const
2668 ASSERT(isUserActionElement());
2669 return document()->userActionElements().isFocused(this);
2672 } // namespace WebCore
2676 void showTree(const WebCore::Node* node)
2679 node->showTreeForThis();
2682 void showNodePath(const WebCore::Node* node)
2685 node->showNodePathForThis();