bc1891206b9263f431f8931be5ed5d3b73395b6d
[WebKit-https.git] / Source / WebCore / dom / Node.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
4  *           (C) 2001 Dirk Mueller (mueller@kde.org)
5  * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2014 Apple Inc. All rights reserved.
6  * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
7  * Copyright (C) 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public License
20  * along with this library; see the file COPYING.LIB.  If not, write to
21  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22  * Boston, MA 02110-1301, USA.
23  */
24
25 #include "config.h"
26 #include "Node.h"
27
28 #include "AXObjectCache.h"
29 #include "Attr.h"
30 #include "BeforeLoadEvent.h"
31 #include "ChildListMutationScope.h"
32 #include "ComposedTreeAncestorIterator.h"
33 #include "ContainerNodeAlgorithms.h"
34 #include "ContextMenuController.h"
35 #include "DataTransfer.h"
36 #include "DocumentType.h"
37 #include "ElementIterator.h"
38 #include "ElementRareData.h"
39 #include "ElementTraversal.h"
40 #include "EventDispatcher.h"
41 #include "EventHandler.h"
42 #include "ExceptionCode.h"
43 #include "FrameView.h"
44 #include "HTMLBodyElement.h"
45 #include "HTMLCollection.h"
46 #include "HTMLElement.h"
47 #include "HTMLImageElement.h"
48 #include "HTMLSlotElement.h"
49 #include "HTMLStyleElement.h"
50 #include "InputEvent.h"
51 #include "InspectorController.h"
52 #include "KeyboardEvent.h"
53 #include "Logging.h"
54 #include "MutationEvent.h"
55 #include "NoEventDispatchAssertion.h"
56 #include "NodeRenderStyle.h"
57 #include "ProcessingInstruction.h"
58 #include "ProgressEvent.h"
59 #include "Range.h"
60 #include "RenderBlock.h"
61 #include "RenderBox.h"
62 #include "RenderTextControl.h"
63 #include "RenderView.h"
64 #include "ScopedEventQueue.h"
65 #include "StorageEvent.h"
66 #include "StyleResolver.h"
67 #include "StyleSheetContents.h"
68 #include "TemplateContentDocumentFragment.h"
69 #include "TextEvent.h"
70 #include "TouchEvent.h"
71 #include "WheelEvent.h"
72 #include "XMLNSNames.h"
73 #include "XMLNames.h"
74 #include <wtf/RefCountedLeakCounter.h>
75 #include <wtf/SHA1.h>
76 #include <wtf/Variant.h>
77 #include <wtf/text/CString.h>
78 #include <wtf/text/StringBuilder.h>
79
80 namespace WebCore {
81
82 using namespace HTMLNames;
83
84 #if DUMP_NODE_STATISTICS
85 static HashSet<Node*> liveNodeSet;
86 #endif
87
88 void Node::dumpStatistics()
89 {
90 #if DUMP_NODE_STATISTICS
91     size_t nodesWithRareData = 0;
92
93     size_t elementNodes = 0;
94     size_t attrNodes = 0;
95     size_t textNodes = 0;
96     size_t cdataNodes = 0;
97     size_t commentNodes = 0;
98     size_t entityNodes = 0;
99     size_t piNodes = 0;
100     size_t documentNodes = 0;
101     size_t docTypeNodes = 0;
102     size_t fragmentNodes = 0;
103     size_t shadowRootNodes = 0;
104
105     HashMap<String, size_t> perTagCount;
106
107     size_t attributes = 0;
108     size_t attributesWithAttr = 0;
109     size_t elementsWithAttributeStorage = 0;
110     size_t elementsWithRareData = 0;
111     size_t elementsWithNamedNodeMap = 0;
112
113     for (auto* node : liveNodeSet) {
114         if (node->hasRareData()) {
115             ++nodesWithRareData;
116             if (is<Element>(*node)) {
117                 ++elementsWithRareData;
118                 if (downcast<Element>(*node).hasNamedNodeMap())
119                     ++elementsWithNamedNodeMap;
120             }
121         }
122
123         switch (node->nodeType()) {
124             case ELEMENT_NODE: {
125                 ++elementNodes;
126
127                 // Tag stats
128                 Element& element = downcast<Element>(*node);
129                 HashMap<String, size_t>::AddResult result = perTagCount.add(element.tagName(), 1);
130                 if (!result.isNewEntry)
131                     result.iterator->value++;
132
133                 if (const ElementData* elementData = element.elementData()) {
134                     unsigned length = elementData->length();
135                     attributes += length;
136                     ++elementsWithAttributeStorage;
137                     for (unsigned i = 0; i < length; ++i) {
138                         const Attribute& attr = elementData->attributeAt(i);
139                         if (!attr.isEmpty())
140                             ++attributesWithAttr;
141                     }
142                 }
143                 break;
144             }
145             case ATTRIBUTE_NODE: {
146                 ++attrNodes;
147                 break;
148             }
149             case TEXT_NODE: {
150                 ++textNodes;
151                 break;
152             }
153             case CDATA_SECTION_NODE: {
154                 ++cdataNodes;
155                 break;
156             }
157             case COMMENT_NODE: {
158                 ++commentNodes;
159                 break;
160             }
161             case ENTITY_NODE: {
162                 ++entityNodes;
163                 break;
164             }
165             case PROCESSING_INSTRUCTION_NODE: {
166                 ++piNodes;
167                 break;
168             }
169             case DOCUMENT_NODE: {
170                 ++documentNodes;
171                 break;
172             }
173             case DOCUMENT_TYPE_NODE: {
174                 ++docTypeNodes;
175                 break;
176             }
177             case DOCUMENT_FRAGMENT_NODE: {
178                 if (node->isShadowRoot())
179                     ++shadowRootNodes;
180                 else
181                     ++fragmentNodes;
182                 break;
183             }
184         }
185     }
186
187     printf("Number of Nodes: %d\n\n", liveNodeSet.size());
188     printf("Number of Nodes with RareData: %zu\n\n", nodesWithRareData);
189
190     printf("NodeType distribution:\n");
191     printf("  Number of Element nodes: %zu\n", elementNodes);
192     printf("  Number of Attribute nodes: %zu\n", attrNodes);
193     printf("  Number of Text nodes: %zu\n", textNodes);
194     printf("  Number of CDATASection nodes: %zu\n", cdataNodes);
195     printf("  Number of Comment nodes: %zu\n", commentNodes);
196     printf("  Number of Entity nodes: %zu\n", entityNodes);
197     printf("  Number of ProcessingInstruction nodes: %zu\n", piNodes);
198     printf("  Number of Document nodes: %zu\n", documentNodes);
199     printf("  Number of DocumentType nodes: %zu\n", docTypeNodes);
200     printf("  Number of DocumentFragment nodes: %zu\n", fragmentNodes);
201     printf("  Number of ShadowRoot nodes: %zu\n", shadowRootNodes);
202
203     printf("Element tag name distibution:\n");
204     for (auto& stringSizePair : perTagCount)
205         printf("  Number of <%s> tags: %zu\n", stringSizePair.key.utf8().data(), stringSizePair.value);
206
207     printf("Attributes:\n");
208     printf("  Number of Attributes (non-Node and Node): %zu [%zu]\n", attributes, sizeof(Attribute));
209     printf("  Number of Attributes with an Attr: %zu\n", attributesWithAttr);
210     printf("  Number of Elements with attribute storage: %zu [%zu]\n", elementsWithAttributeStorage, sizeof(ElementData));
211     printf("  Number of Elements with RareData: %zu\n", elementsWithRareData);
212     printf("  Number of Elements with NamedNodeMap: %zu [%zu]\n", elementsWithNamedNodeMap, sizeof(NamedNodeMap));
213 #endif
214 }
215
216 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, nodeCounter, ("WebCoreNode"));
217
218 #ifndef NDEBUG
219 static bool shouldIgnoreLeaks = false;
220
221 static HashSet<Node*>& ignoreSet()
222 {
223     static NeverDestroyed<HashSet<Node*>> ignore;
224
225     return ignore;
226 }
227
228 #endif
229
230 void Node::startIgnoringLeaks()
231 {
232 #ifndef NDEBUG
233     shouldIgnoreLeaks = true;
234 #endif
235 }
236
237 void Node::stopIgnoringLeaks()
238 {
239 #ifndef NDEBUG
240     shouldIgnoreLeaks = false;
241 #endif
242 }
243
244 void Node::trackForDebugging()
245 {
246 #ifndef NDEBUG
247     if (shouldIgnoreLeaks)
248         ignoreSet().add(this);
249     else
250         nodeCounter.increment();
251 #endif
252
253 #if DUMP_NODE_STATISTICS
254     liveNodeSet.add(this);
255 #endif
256 }
257
258 Node::Node(Document& document, ConstructionType type)
259     : m_refCount(1)
260     , m_nodeFlags(type)
261     , m_treeScope(&document)
262 {
263     ASSERT(isMainThread());
264
265     document.incrementReferencingNodeCount();
266
267 #if !defined(NDEBUG) || (defined(DUMP_NODE_STATISTICS) && DUMP_NODE_STATISTICS)
268     trackForDebugging();
269 #endif
270 }
271
272 Node::~Node()
273 {
274     ASSERT(isMainThread());
275     ASSERT(!m_refCount);
276     ASSERT(m_deletionHasBegun);
277     ASSERT(!m_adoptionIsRequired);
278
279 #ifndef NDEBUG
280     if (!ignoreSet().remove(this))
281         nodeCounter.decrement();
282 #endif
283
284 #if DUMP_NODE_STATISTICS
285     liveNodeSet.remove(this);
286 #endif
287
288     ASSERT_WITH_SECURITY_IMPLICATION(!renderer());
289     ASSERT(!parentNode());
290     ASSERT(!m_previous);
291     ASSERT(!m_next);
292
293     if (hasRareData())
294         clearRareData();
295
296     if (!isContainerNode())
297         willBeDeletedFrom(document());
298
299     if (hasEventTargetData())
300         clearEventTargetData();
301
302     document().decrementReferencingNodeCount();
303
304 #if ENABLE(TOUCH_EVENTS) && PLATFORM(IOS) && (!ASSERT_DISABLED || ENABLE(SECURITY_ASSERTIONS))
305     for (auto* document : Document::allDocuments()) {
306         ASSERT_WITH_SECURITY_IMPLICATION(!document->touchEventListenersContain(*this));
307         ASSERT_WITH_SECURITY_IMPLICATION(!document->touchEventHandlersContain(*this));
308         ASSERT_WITH_SECURITY_IMPLICATION(!document->touchEventTargetsContain(*this));
309     }
310 #endif
311 }
312
313 void Node::willBeDeletedFrom(Document& document)
314 {
315     if (hasEventTargetData()) {
316         document.didRemoveWheelEventHandler(*this, EventHandlerRemoval::All);
317 #if ENABLE(TOUCH_EVENTS)
318 #if PLATFORM(IOS)
319         document.removeTouchEventListener(*this, EventHandlerRemoval::All);
320 #endif
321         document.didRemoveTouchEventHandler(*this, EventHandlerRemoval::All);
322 #endif
323     }
324
325 #if ENABLE(TOUCH_EVENTS) && PLATFORM(IOS)
326     document.removeTouchEventHandler(*this, EventHandlerRemoval::All);
327 #endif
328
329     if (AXObjectCache* cache = document.existingAXObjectCache())
330         cache->remove(this);
331 }
332
333 void Node::materializeRareData()
334 {
335     NodeRareData* data;
336     if (is<Element>(*this))
337         data = std::make_unique<ElementRareData>(downcast<RenderElement>(m_data.m_renderer)).release();
338     else
339         data = std::make_unique<NodeRareData>(m_data.m_renderer).release();
340     ASSERT(data);
341
342     m_data.m_rareData = data;
343     setFlag(HasRareDataFlag);
344 }
345
346 void Node::clearRareData()
347 {
348     ASSERT(hasRareData());
349     ASSERT(!transientMutationObserverRegistry() || transientMutationObserverRegistry()->isEmpty());
350
351     RenderObject* renderer = m_data.m_rareData->renderer();
352     if (isElementNode())
353         delete static_cast<ElementRareData*>(m_data.m_rareData);
354     else
355         delete static_cast<NodeRareData*>(m_data.m_rareData);
356     m_data.m_renderer = renderer;
357     clearFlag(HasRareDataFlag);
358 }
359
360 Node* Node::toNode()
361 {
362     return this;
363 }
364
365 String Node::nodeValue() const
366 {
367     return String();
368 }
369
370 ExceptionOr<void> Node::setNodeValue(const String&)
371 {
372     // By default, setting nodeValue has no effect.
373     return { };
374 }
375
376 RefPtr<NodeList> Node::childNodes()
377 {
378     if (is<ContainerNode>(*this))
379         return ensureRareData().ensureNodeLists().ensureChildNodeList(downcast<ContainerNode>(*this));
380     return ensureRareData().ensureNodeLists().ensureEmptyChildNodeList(*this);
381 }
382
383 Node *Node::lastDescendant() const
384 {
385     Node *n = const_cast<Node *>(this);
386     while (n && n->lastChild())
387         n = n->lastChild();
388     return n;
389 }
390
391 Node* Node::firstDescendant() const
392 {
393     Node *n = const_cast<Node *>(this);
394     while (n && n->firstChild())
395         n = n->firstChild();
396     return n;
397 }
398
399 Element* Node::previousElementSibling() const
400 {
401     return ElementTraversal::previousSibling(*this);
402 }
403
404 Element* Node::nextElementSibling() const
405 {
406     return ElementTraversal::nextSibling(*this);
407 }
408
409 ExceptionOr<void> Node::insertBefore(Node& newChild, Node* refChild)
410 {
411     if (!is<ContainerNode>(*this))
412         return Exception { HIERARCHY_REQUEST_ERR };
413     return downcast<ContainerNode>(*this).insertBefore(newChild, refChild);
414 }
415
416 ExceptionOr<void> Node::replaceChild(Node& newChild, Node& oldChild)
417 {
418     if (!is<ContainerNode>(*this))
419         return Exception { HIERARCHY_REQUEST_ERR };
420     return downcast<ContainerNode>(*this).replaceChild(newChild, oldChild);
421 }
422
423 ExceptionOr<void> Node::removeChild(Node& oldChild)
424 {
425     if (!is<ContainerNode>(*this))
426         return Exception { NOT_FOUND_ERR };
427     return downcast<ContainerNode>(*this).removeChild(oldChild);
428 }
429
430 ExceptionOr<void> Node::appendChild(Node& newChild)
431 {
432     if (!is<ContainerNode>(*this))
433         return Exception { HIERARCHY_REQUEST_ERR };
434     return downcast<ContainerNode>(*this).appendChild(newChild);
435 }
436
437 static HashSet<RefPtr<Node>> nodeSetPreTransformedFromNodeOrStringVector(const Vector<NodeOrString>& vector)
438 {
439     HashSet<RefPtr<Node>> nodeSet;
440     for (const auto& variant : vector) {
441         WTF::switchOn(variant,
442             [&] (const RefPtr<Node>& node) { nodeSet.add(const_cast<Node*>(node.get())); },
443             [] (const String&) { }
444         );
445     }
446     return nodeSet;
447 }
448
449 static RefPtr<Node> firstPrecedingSiblingNotInNodeSet(Node& context, const HashSet<RefPtr<Node>>& nodeSet)
450 {
451     for (auto* sibling = context.previousSibling(); sibling; sibling = sibling->previousSibling()) {
452         if (!nodeSet.contains(sibling))
453             return sibling;
454     }
455     return nullptr;
456 }
457
458 static RefPtr<Node> firstFollowingSiblingNotInNodeSet(Node& context, const HashSet<RefPtr<Node>>& nodeSet)
459 {
460     for (auto* sibling = context.nextSibling(); sibling; sibling = sibling->nextSibling()) {
461         if (!nodeSet.contains(sibling))
462             return sibling;
463     }
464     return nullptr;
465 }
466
467 ExceptionOr<RefPtr<Node>> Node::convertNodesOrStringsIntoNode(Vector<NodeOrString>&& nodeOrStringVector)
468 {
469     if (nodeOrStringVector.isEmpty())
470         return nullptr;
471
472     Vector<Ref<Node>> nodes;
473     nodes.reserveInitialCapacity(nodeOrStringVector.size());
474     for (auto& variant : nodeOrStringVector) {
475         WTF::switchOn(variant,
476             [&](RefPtr<Node>& node) { nodes.uncheckedAppend(*node.get()); },
477             [&](String& string) { nodes.uncheckedAppend(Text::create(document(), string)); }
478         );
479     }
480
481     if (nodes.size() == 1)
482         return RefPtr<Node> { WTFMove(nodes.first()) };
483
484     auto nodeToReturn = DocumentFragment::create(document());
485     for (auto& node : nodes) {
486         auto appendResult = nodeToReturn->appendChild(node);
487         if (appendResult.hasException())
488             return appendResult.releaseException();
489     }
490     return RefPtr<Node> { WTFMove(nodeToReturn) };
491 }
492
493 ExceptionOr<void> Node::before(Vector<NodeOrString>&& nodeOrStringVector)
494 {
495     RefPtr<ContainerNode> parent = parentNode();
496     if (!parent)
497         return { };
498
499     auto nodeSet = nodeSetPreTransformedFromNodeOrStringVector(nodeOrStringVector);
500     auto viablePreviousSibling = firstPrecedingSiblingNotInNodeSet(*this, nodeSet);
501
502     auto result = convertNodesOrStringsIntoNode(WTFMove(nodeOrStringVector));
503     if (result.hasException())
504         return result.releaseException();
505     auto node = result.releaseReturnValue();
506     if (!node)
507         return { };
508
509     if (viablePreviousSibling)
510         viablePreviousSibling = viablePreviousSibling->nextSibling();
511     else
512         viablePreviousSibling = parent->firstChild();
513
514     return parent->insertBefore(*node, viablePreviousSibling.get());
515 }
516
517 ExceptionOr<void> Node::after(Vector<NodeOrString>&& nodeOrStringVector)
518 {
519     RefPtr<ContainerNode> parent = parentNode();
520     if (!parent)
521         return { };
522
523     auto nodeSet = nodeSetPreTransformedFromNodeOrStringVector(nodeOrStringVector);
524     auto viableNextSibling = firstFollowingSiblingNotInNodeSet(*this, nodeSet);
525
526     auto result = convertNodesOrStringsIntoNode(WTFMove(nodeOrStringVector));
527     if (result.hasException())
528         return result.releaseException();
529     auto node = result.releaseReturnValue();
530     if (!node)
531         return { };
532
533     return parent->insertBefore(*node, viableNextSibling.get());
534 }
535
536 ExceptionOr<void> Node::replaceWith(Vector<NodeOrString>&& nodeOrStringVector)
537 {
538     RefPtr<ContainerNode> parent = parentNode();
539     if (!parent)
540         return { };
541
542     auto nodeSet = nodeSetPreTransformedFromNodeOrStringVector(nodeOrStringVector);
543     auto viableNextSibling = firstFollowingSiblingNotInNodeSet(*this, nodeSet);
544
545     auto result = convertNodesOrStringsIntoNode(WTFMove(nodeOrStringVector));
546     if (result.hasException())
547         return result.releaseException();
548
549     if (parentNode() == parent) {
550         if (auto node = result.releaseReturnValue())
551             return parent->replaceChild(*node, *this);
552         return parent->removeChild(*this);
553     }
554
555     if (auto node = result.releaseReturnValue())
556         return parent->insertBefore(*node, viableNextSibling.get());
557     return { };
558 }
559
560 ExceptionOr<void> Node::remove()
561 {
562     auto* parent = parentNode();
563     if (!parent)
564         return { };
565     return parent->removeChild(*this);
566 }
567
568 void Node::normalize()
569 {
570     // Go through the subtree beneath us, normalizing all nodes. This means that
571     // any two adjacent text nodes are merged and any empty text nodes are removed.
572
573     RefPtr<Node> node = this;
574     while (Node* firstChild = node->firstChild())
575         node = firstChild;
576     while (node) {
577         NodeType type = node->nodeType();
578         if (type == ELEMENT_NODE)
579             downcast<Element>(*node).normalizeAttributes();
580
581         if (node == this)
582             break;
583
584         if (type != TEXT_NODE) {
585             node = NodeTraversal::nextPostOrder(*node);
586             continue;
587         }
588
589         RefPtr<Text> text = downcast<Text>(node.get());
590
591         // Remove empty text nodes.
592         if (!text->length()) {
593             // Care must be taken to get the next node before removing the current node.
594             node = NodeTraversal::nextPostOrder(*node);
595             text->remove();
596             continue;
597         }
598
599         // Merge text nodes.
600         while (Node* nextSibling = node->nextSibling()) {
601             if (nextSibling->nodeType() != TEXT_NODE)
602                 break;
603             RefPtr<Text> nextText = downcast<Text>(nextSibling);
604
605             // Remove empty text nodes.
606             if (!nextText->length()) {
607                 nextText->remove();
608                 continue;
609             }
610
611             // Both non-empty text nodes. Merge them.
612             unsigned offset = text->length();
613             text->appendData(nextText->data());
614             document().textNodesMerged(nextText.get(), offset);
615             nextText->remove();
616         }
617
618         node = NodeTraversal::nextPostOrder(*node);
619     }
620 }
621
622 ExceptionOr<Ref<Node>> Node::cloneNodeForBindings(bool deep)
623 {
624     if (UNLIKELY(isShadowRoot()))
625         return Exception { NOT_SUPPORTED_ERR };
626     return cloneNode(deep);
627 }
628
629 const AtomicString& Node::prefix() const
630 {
631     // For nodes other than elements and attributes, the prefix is always null
632     return nullAtom;
633 }
634
635 ExceptionOr<void> Node::setPrefix(const AtomicString&)
636 {
637     // The spec says that for nodes other than elements and attributes, prefix is always null.
638     // It does not say what to do when the user tries to set the prefix on another type of
639     // node, however Mozilla throws a NAMESPACE_ERR exception.
640     return Exception { NAMESPACE_ERR };
641 }
642
643 const AtomicString& Node::localName() const
644 {
645     return nullAtom;
646 }
647
648 const AtomicString& Node::namespaceURI() const
649 {
650     return nullAtom;
651 }
652
653 bool Node::isContentEditable()
654 {
655     return computeEditability(UserSelectAllDoesNotAffectEditability, ShouldUpdateStyle::Update) != Editability::ReadOnly;
656 }
657
658 bool Node::isContentRichlyEditable()
659 {
660     return computeEditability(UserSelectAllIsAlwaysNonEditable, ShouldUpdateStyle::Update) == Editability::CanEditRichly;
661 }
662
663 void Node::inspect()
664 {
665     if (document().page())
666         document().page()->inspectorController().inspect(this);
667 }
668
669 static Node::Editability computeEditabilityFromComputedStyle(const Node& startNode, Node::UserSelectAllTreatment treatment)
670 {
671     // Ideally we'd call ASSERT(!needsStyleRecalc()) here, but
672     // ContainerNode::setFocus() calls invalidateStyleForSubtree(), so the assertion
673     // would fire in the middle of Document::setFocusedElement().
674
675     for (const Node* node = &startNode; node; node = node->parentNode()) {
676         auto* style = node->isDocumentNode() ? node->renderStyle() : const_cast<Node*>(node)->computedStyle();
677         if (!style)
678             continue;
679         if (style->display() == NONE)
680             continue;
681 #if ENABLE(USERSELECT_ALL)
682         // Elements with user-select: all style are considered atomic
683         // therefore non editable.
684         if (treatment == Node::UserSelectAllIsAlwaysNonEditable && style->userSelect() == SELECT_ALL)
685             return Node::Editability::ReadOnly;
686 #else
687         UNUSED_PARAM(treatment);
688 #endif
689         switch (style->userModify()) {
690         case READ_ONLY:
691             return Node::Editability::ReadOnly;
692         case READ_WRITE:
693             return Node::Editability::CanEditRichly;
694         case READ_WRITE_PLAINTEXT_ONLY:
695             return Node::Editability::CanEditPlainText;
696         }
697         ASSERT_NOT_REACHED();
698         return Node::Editability::ReadOnly;
699     }
700     return Node::Editability::ReadOnly;
701 }
702
703 Node::Editability Node::computeEditability(UserSelectAllTreatment treatment, ShouldUpdateStyle shouldUpdateStyle) const
704 {
705     if (!document().hasLivingRenderTree() || isPseudoElement())
706         return Editability::ReadOnly;
707
708     if (isInShadowTree())
709         return HTMLElement::editabilityFromContentEditableAttr(*this);
710
711     if (document().frame() && document().frame()->page() && document().frame()->page()->isEditable())
712         return Editability::CanEditRichly;
713
714     if (shouldUpdateStyle == ShouldUpdateStyle::Update && document().needsStyleRecalc()) {
715         if (!document().usesStyleBasedEditability())
716             return HTMLElement::editabilityFromContentEditableAttr(*this);
717         document().updateStyleIfNeeded();
718     }
719     return computeEditabilityFromComputedStyle(*this, treatment);
720 }
721
722 RenderBox* Node::renderBox() const
723 {
724     RenderObject* renderer = this->renderer();
725     return is<RenderBox>(renderer) ? downcast<RenderBox>(renderer) : nullptr;
726 }
727
728 RenderBoxModelObject* Node::renderBoxModelObject() const
729 {
730     RenderObject* renderer = this->renderer();
731     return is<RenderBoxModelObject>(renderer) ? downcast<RenderBoxModelObject>(renderer) : nullptr;
732 }
733     
734 LayoutRect Node::renderRect(bool* isReplaced)
735 {    
736     RenderObject* hitRenderer = this->renderer();
737     ASSERT(hitRenderer);
738     RenderObject* renderer = hitRenderer;
739     while (renderer && !renderer->isBody() && !renderer->isDocumentElementRenderer()) {
740         if (renderer->isRenderBlock() || renderer->isInlineBlockOrInlineTable() || renderer->isReplaced()) {
741             *isReplaced = renderer->isReplaced();
742             return renderer->absoluteBoundingBoxRect();
743         }
744         renderer = renderer->parent();
745     }
746     return LayoutRect();    
747 }
748
749 void Node::refEventTarget()
750 {
751     ref();
752 }
753
754 void Node::derefEventTarget()
755 {
756     deref();
757 }
758
759 void Node::adjustStyleValidity(Style::Validity validity, Style::InvalidationMode mode)
760 {
761     if (validity > styleValidity()) {
762         m_nodeFlags &= ~StyleValidityMask;
763         m_nodeFlags |= static_cast<unsigned>(validity) << StyleValidityShift;
764     }
765     if (mode == Style::InvalidationMode::RecompositeLayer)
766         setFlag(StyleResolutionShouldRecompositeLayerFlag);
767 }
768
769 inline void Node::updateAncestorsForStyleRecalc()
770 {
771     auto composedAncestors = composedTreeAncestors(*this);
772     auto it = composedAncestors.begin();
773     auto end = composedAncestors.end();
774     if (it != end) {
775         it->setDirectChildNeedsStyleRecalc();
776
777         if (it->childrenAffectedByPropertyBasedBackwardPositionalRules())
778             it->adjustStyleValidity(Style::Validity::SubtreeInvalid, Style::InvalidationMode::Normal);
779
780         for (; it != end; ++it) {
781             // Iterator skips over shadow roots.
782             if (auto* shadowRoot = it->shadowRoot())
783                 shadowRoot->setChildNeedsStyleRecalc();
784             if (it->childNeedsStyleRecalc())
785                 break;
786             it->setChildNeedsStyleRecalc();
787         }
788     }
789
790     auto* documentElement = document().documentElement();
791     if (!documentElement)
792         return;
793     if (!documentElement->childNeedsStyleRecalc() && !documentElement->needsStyleRecalc())
794         return;
795     document().setChildNeedsStyleRecalc();
796     document().scheduleStyleRecalc();
797 }
798
799 void Node::invalidateStyle(Style::Validity validity, Style::InvalidationMode mode)
800 {
801     ASSERT(validity != Style::Validity::Valid);
802     if (!inRenderedDocument())
803         return;
804
805     // FIXME: This should eventually be an ASSERT.
806     if (document().inRenderTreeUpdate())
807         return;
808
809     // FIXME: Why the second condition?
810     bool markAncestors = styleValidity() == Style::Validity::Valid || validity == Style::Validity::SubtreeAndRenderersInvalid;
811
812     adjustStyleValidity(validity, mode);
813
814     if (markAncestors)
815         updateAncestorsForStyleRecalc();
816 }
817
818 unsigned Node::computeNodeIndex() const
819 {
820     unsigned count = 0;
821     for (Node* sibling = previousSibling(); sibling; sibling = sibling->previousSibling())
822         ++count;
823     return count;
824 }
825
826 template<unsigned type>
827 bool shouldInvalidateNodeListCachesForAttr(const unsigned nodeListCounts[], const QualifiedName& attrName)
828 {
829     if (nodeListCounts[type] && shouldInvalidateTypeOnAttributeChange(static_cast<NodeListInvalidationType>(type), attrName))
830         return true;
831     return shouldInvalidateNodeListCachesForAttr<type + 1>(nodeListCounts, attrName);
832 }
833
834 template<>
835 bool shouldInvalidateNodeListCachesForAttr<numNodeListInvalidationTypes>(const unsigned[], const QualifiedName&)
836 {
837     return false;
838 }
839
840 inline bool Document::shouldInvalidateNodeListAndCollectionCaches() const
841 {
842     for (int type = 0; type < numNodeListInvalidationTypes; ++type) {
843         if (m_nodeListAndCollectionCounts[type])
844             return true;
845     }
846     return false;
847 }
848
849 inline bool Document::shouldInvalidateNodeListAndCollectionCachesForAttribute(const QualifiedName& attrName) const
850 {
851     return shouldInvalidateNodeListCachesForAttr<DoNotInvalidateOnAttributeChanges + 1>(m_nodeListAndCollectionCounts, attrName);
852 }
853
854 template <typename InvalidationFunction>
855 void Document::invalidateNodeListAndCollectionCaches(InvalidationFunction invalidate)
856 {
857     Vector<LiveNodeList*, 8> lists;
858     copyToVector(m_listsInvalidatedAtDocument, lists);
859     for (auto* list : lists)
860         invalidate(*list);
861
862     Vector<HTMLCollection*, 8> collections;
863     copyToVector(m_collectionsInvalidatedAtDocument, collections);
864     for (auto* collection : collections)
865         invalidate(*collection);
866 }
867
868 void Node::invalidateNodeListAndCollectionCachesInAncestors()
869 {
870     if (hasRareData()) {
871         if (auto* lists = rareData()->nodeLists())
872             lists->clearChildNodeListCache();
873     }
874
875     if (!document().shouldInvalidateNodeListAndCollectionCaches())
876         return;
877
878     document().invalidateNodeListAndCollectionCaches([](auto& list) {
879         list.invalidateCache();
880     });
881
882     for (auto* node = this; node; node = node->parentNode()) {
883         if (!node->hasRareData())
884             continue;
885
886         if (auto* lists = node->rareData()->nodeLists())
887             lists->invalidateCaches();
888     }
889 }
890
891 void Node::invalidateNodeListAndCollectionCachesInAncestorsForAttribute(const QualifiedName& attrName)
892 {
893     ASSERT(is<Element>(*this));
894
895     if (!document().shouldInvalidateNodeListAndCollectionCachesForAttribute(attrName))
896         return;
897
898     document().invalidateNodeListAndCollectionCaches([&attrName](auto& list) {
899         list.invalidateCacheForAttribute(attrName);
900     });
901
902     for (auto* node = this; node; node = node->parentNode()) {
903         if (!node->hasRareData())
904             continue;
905
906         if (auto* lists = node->rareData()->nodeLists())
907             lists->invalidateCachesForAttribute(attrName);
908     }
909 }
910
911 NodeListsNodeData* Node::nodeLists()
912 {
913     return hasRareData() ? rareData()->nodeLists() : nullptr;
914 }
915
916 void Node::clearNodeLists()
917 {
918     rareData()->clearNodeLists();
919 }
920
921 ExceptionOr<void> Node::checkSetPrefix(const AtomicString& prefix)
922 {
923     // Perform error checking as required by spec for setting Node.prefix. Used by
924     // Element::setPrefix() and Attr::setPrefix()
925
926     if (!prefix.isEmpty() && !Document::isValidName(prefix))
927         return Exception { INVALID_CHARACTER_ERR };
928
929     // FIXME: Raise NAMESPACE_ERR if prefix is malformed per the Namespaces in XML specification.
930
931     auto& namespaceURI = this->namespaceURI();
932     if (namespaceURI.isEmpty() && !prefix.isEmpty())
933         return Exception { NAMESPACE_ERR };
934     if (prefix == xmlAtom && namespaceURI != XMLNames::xmlNamespaceURI)
935         return Exception { NAMESPACE_ERR };
936
937     // Attribute-specific checks are in Attr::setPrefix().
938
939     return { };
940 }
941
942 bool Node::isDescendantOf(const Node& other) const
943 {
944     // Return true if other is an ancestor of this, otherwise false
945     if (!other.hasChildNodes() || isConnected() != other.isConnected())
946         return false;
947     if (other.isDocumentNode())
948         return &document() == &other && !isDocumentNode() && isConnected();
949     for (const auto* ancestor = parentNode(); ancestor; ancestor = ancestor->parentNode()) {
950         if (ancestor == &other)
951             return true;
952     }
953     return false;
954 }
955
956 bool Node::isDescendantOrShadowDescendantOf(const Node* other) const
957 {
958     if (!other) 
959         return false;
960     if (isDescendantOf(*other))
961         return true;
962     const Node* shadowAncestorNode = deprecatedShadowAncestorNode();
963     if (!shadowAncestorNode)
964         return false;
965     return shadowAncestorNode == other || shadowAncestorNode->isDescendantOf(*other);
966 }
967
968 bool Node::contains(const Node* node) const
969 {
970     if (!node)
971         return false;
972     return this == node || node->isDescendantOf(*this);
973 }
974
975 bool Node::containsIncludingShadowDOM(const Node* node) const
976 {
977     for (; node; node = node->parentOrShadowHostNode()) {
978         if (node == this)
979             return true;
980     }
981     return false;
982 }
983
984 bool Node::containsIncludingHostElements(const Node* node) const
985 {
986     while (node) {
987         if (node == this)
988             return true;
989         if (node->isDocumentFragment() && static_cast<const DocumentFragment*>(node)->isTemplateContent())
990             node = static_cast<const TemplateContentDocumentFragment*>(node)->host();
991         else
992             node = node->parentOrShadowHostNode();
993     }
994     return false;
995 }
996
997 Node* Node::pseudoAwarePreviousSibling() const
998 {
999     Element* parentOrHost = is<PseudoElement>(*this) ? downcast<PseudoElement>(*this).hostElement() : parentElement();
1000     if (parentOrHost && !previousSibling()) {
1001         if (isAfterPseudoElement() && parentOrHost->lastChild())
1002             return parentOrHost->lastChild();
1003         if (!isBeforePseudoElement())
1004             return parentOrHost->beforePseudoElement();
1005     }
1006     return previousSibling();
1007 }
1008
1009 Node* Node::pseudoAwareNextSibling() const
1010 {
1011     Element* parentOrHost = is<PseudoElement>(*this) ? downcast<PseudoElement>(*this).hostElement() : parentElement();
1012     if (parentOrHost && !nextSibling()) {
1013         if (isBeforePseudoElement() && parentOrHost->firstChild())
1014             return parentOrHost->firstChild();
1015         if (!isAfterPseudoElement())
1016             return parentOrHost->afterPseudoElement();
1017     }
1018     return nextSibling();
1019 }
1020
1021 Node* Node::pseudoAwareFirstChild() const
1022 {
1023     if (is<Element>(*this)) {
1024         const Element& currentElement = downcast<Element>(*this);
1025         Node* first = currentElement.beforePseudoElement();
1026         if (first)
1027             return first;
1028         first = currentElement.firstChild();
1029         if (!first)
1030             first = currentElement.afterPseudoElement();
1031         return first;
1032     }
1033     return firstChild();
1034 }
1035
1036 Node* Node::pseudoAwareLastChild() const
1037 {
1038     if (is<Element>(*this)) {
1039         const Element& currentElement = downcast<Element>(*this);
1040         Node* last = currentElement.afterPseudoElement();
1041         if (last)
1042             return last;
1043         last = currentElement.lastChild();
1044         if (!last)
1045             last = currentElement.beforePseudoElement();
1046         return last;
1047     }
1048     return lastChild();
1049 }
1050
1051 const RenderStyle* Node::computedStyle(PseudoId pseudoElementSpecifier)
1052 {
1053     auto* composedParent = composedTreeAncestors(*this).first();
1054     if (!composedParent)
1055         return nullptr;
1056     return composedParent->computedStyle(pseudoElementSpecifier);
1057 }
1058
1059 int Node::maxCharacterOffset() const
1060 {
1061     ASSERT_NOT_REACHED();
1062     return 0;
1063 }
1064
1065 // FIXME: Shouldn't these functions be in the editing code?  Code that asks questions about HTML in the core DOM class
1066 // is obviously misplaced.
1067 bool Node::canStartSelection() const
1068 {
1069     if (hasEditableStyle())
1070         return true;
1071
1072     if (renderer()) {
1073         const RenderStyle& style = renderer()->style();
1074         // We allow selections to begin within an element that has -webkit-user-select: none set,
1075         // but if the element is draggable then dragging should take priority over selection.
1076         if (style.userDrag() == DRAG_ELEMENT && style.userSelect() == SELECT_NONE)
1077             return false;
1078     }
1079     return parentOrShadowHostNode() ? parentOrShadowHostNode()->canStartSelection() : true;
1080 }
1081
1082 Element* Node::shadowHost() const
1083 {
1084     if (ShadowRoot* root = containingShadowRoot())
1085         return root->host();
1086     return nullptr;
1087 }
1088
1089 Node* Node::deprecatedShadowAncestorNode() const
1090 {
1091     if (ShadowRoot* root = containingShadowRoot())
1092         return root->host();
1093
1094     return const_cast<Node*>(this);
1095 }
1096
1097 ShadowRoot* Node::containingShadowRoot() const
1098 {
1099     ContainerNode& root = treeScope().rootNode();
1100     return is<ShadowRoot>(root) ? downcast<ShadowRoot>(&root) : nullptr;
1101 }
1102
1103 #if !ASSERT_DISABLED
1104 // https://dom.spec.whatwg.org/#concept-closed-shadow-hidden
1105 static bool isClosedShadowHiddenUsingSpecDefinition(const Node& A, const Node& B)
1106 {
1107     return A.isInShadowTree()
1108         && !A.rootNode().containsIncludingShadowDOM(&B)
1109         && (A.containingShadowRoot()->mode() != ShadowRootMode::Open || isClosedShadowHiddenUsingSpecDefinition(*A.shadowHost(), B));
1110 }
1111 #endif
1112
1113 // http://w3c.github.io/webcomponents/spec/shadow/#dfn-unclosed-node
1114 bool Node::isClosedShadowHidden(const Node& otherNode) const
1115 {
1116     // Use Vector instead of HashSet since we expect the number of ancestor tree scopes to be small.
1117     Vector<TreeScope*, 8> ancestorScopesOfThisNode;
1118
1119     for (auto* scope = &treeScope(); scope; scope = scope->parentTreeScope())
1120         ancestorScopesOfThisNode.append(scope);
1121
1122     for (auto* treeScopeThatCanAccessOtherNode = &otherNode.treeScope(); treeScopeThatCanAccessOtherNode; treeScopeThatCanAccessOtherNode = treeScopeThatCanAccessOtherNode->parentTreeScope()) {
1123         for (auto* scope : ancestorScopesOfThisNode) {
1124             if (scope == treeScopeThatCanAccessOtherNode) {
1125                 ASSERT(!isClosedShadowHiddenUsingSpecDefinition(otherNode, *this));
1126                 return false; // treeScopeThatCanAccessOtherNode is a shadow-including inclusive ancestor of this node.
1127             }
1128         }
1129         auto& root = treeScopeThatCanAccessOtherNode->rootNode();
1130         if (is<ShadowRoot>(root) && downcast<ShadowRoot>(root).mode() != ShadowRootMode::Open)
1131             break;
1132     }
1133
1134     ASSERT(isClosedShadowHiddenUsingSpecDefinition(otherNode, *this));
1135     return true;
1136 }
1137
1138 static inline ShadowRoot* parentShadowRoot(const Node& node)
1139 {
1140     if (auto* parent = node.parentElement())
1141         return parent->shadowRoot();
1142     return nullptr;
1143 }
1144
1145 HTMLSlotElement* Node::assignedSlot() const
1146 {
1147     if (auto* shadowRoot = parentShadowRoot(*this))
1148         return shadowRoot->findAssignedSlot(*this);
1149     return nullptr;
1150 }
1151
1152 HTMLSlotElement* Node::assignedSlotForBindings() const
1153 {
1154     auto* shadowRoot = parentShadowRoot(*this);
1155     if (shadowRoot && shadowRoot->mode() == ShadowRootMode::Open)
1156         return shadowRoot->findAssignedSlot(*this);
1157     return nullptr;
1158 }
1159
1160 ContainerNode* Node::parentInComposedTree() const
1161 {
1162     ASSERT(isMainThreadOrGCThread());
1163     if (auto* slot = assignedSlot())
1164         return slot;
1165     if (is<ShadowRoot>(*this))
1166         return downcast<ShadowRoot>(*this).host();
1167     return parentNode();
1168 }
1169
1170 Element* Node::parentElementInComposedTree() const
1171 {
1172     if (auto* slot = assignedSlot())
1173         return slot;
1174     if (auto* parent = parentNode()) {
1175         if (is<ShadowRoot>(*parent))
1176             return downcast<ShadowRoot>(*parent).host();
1177         if (is<Element>(*parent))
1178             return downcast<Element>(parent);
1179     }
1180     return nullptr;
1181 }
1182
1183 bool Node::isInUserAgentShadowTree() const
1184 {
1185     auto* shadowRoot = containingShadowRoot();
1186     return shadowRoot && shadowRoot->mode() == ShadowRootMode::UserAgent;
1187 }
1188
1189 Node* Node::nonBoundaryShadowTreeRootNode()
1190 {
1191     ASSERT(!isShadowRoot());
1192     Node* root = this;
1193     while (root) {
1194         if (root->isShadowRoot())
1195             return root;
1196         Node* parent = root->parentNodeGuaranteedHostFree();
1197         if (parent && parent->isShadowRoot())
1198             return root;
1199         root = parent;
1200     }
1201     return 0;
1202 }
1203
1204 ContainerNode* Node::nonShadowBoundaryParentNode() const
1205 {
1206     ContainerNode* parent = parentNode();
1207     return parent && !parent->isShadowRoot() ? parent : nullptr;
1208 }
1209
1210 Element* Node::parentOrShadowHostElement() const
1211 {
1212     ContainerNode* parent = parentOrShadowHostNode();
1213     if (!parent)
1214         return nullptr;
1215
1216     if (is<ShadowRoot>(*parent))
1217         return downcast<ShadowRoot>(*parent).host();
1218
1219     if (!is<Element>(*parent))
1220         return nullptr;
1221
1222     return downcast<Element>(parent);
1223 }
1224
1225 Node& Node::traverseToRootNode() const
1226 {
1227     Node* node = const_cast<Node*>(this);
1228     Node* highest = node;
1229     for (; node; node = node->parentNode())
1230         highest = node;
1231     return *highest;
1232 }
1233
1234 // https://dom.spec.whatwg.org/#concept-shadow-including-root
1235 Node& Node::shadowIncludingRoot() const
1236 {
1237     auto& root = rootNode();
1238     if (!is<ShadowRoot>(root))
1239         return root;
1240     auto* host = downcast<ShadowRoot>(root).host();
1241     return host ? host->shadowIncludingRoot() : root;
1242 }
1243
1244 Node& Node::getRootNode(const GetRootNodeOptions& options) const
1245 {
1246     return options.composed ? shadowIncludingRoot() : rootNode();
1247 }
1248
1249 Node::InsertionNotificationRequest Node::insertedInto(ContainerNode& insertionPoint)
1250 {
1251     if (insertionPoint.isConnected())
1252         setFlag(IsConnectedFlag);
1253     if (insertionPoint.isInShadowTree())
1254         setFlag(IsInShadowTreeFlag);
1255
1256     invalidateStyle(Style::Validity::SubtreeAndRenderersInvalid);
1257
1258     return InsertionDone;
1259 }
1260
1261 void Node::removedFrom(ContainerNode& insertionPoint)
1262 {
1263     if (insertionPoint.isConnected())
1264         clearFlag(IsConnectedFlag);
1265     if (isInShadowTree() && !treeScope().rootNode().isShadowRoot())
1266         clearFlag(IsInShadowTreeFlag);
1267 }
1268
1269 bool Node::isRootEditableElement() const
1270 {
1271     return hasEditableStyle() && isElementNode() && (!parentNode() || !parentNode()->hasEditableStyle()
1272         || !parentNode()->isElementNode() || hasTagName(bodyTag));
1273 }
1274
1275 Element* Node::rootEditableElement() const
1276 {
1277     Element* result = nullptr;
1278     for (Node* node = const_cast<Node*>(this); node && node->hasEditableStyle(); node = node->parentNode()) {
1279         if (is<Element>(*node))
1280             result = downcast<Element>(node);
1281         if (is<HTMLBodyElement>(*node))
1282             break;
1283     }
1284     return result;
1285 }
1286
1287 // FIXME: End of obviously misplaced HTML editing functions.  Try to move these out of Node.
1288
1289 Document* Node::ownerDocument() const
1290 {
1291     Document* document = &this->document();
1292     return document == this ? nullptr : document;
1293 }
1294
1295 const URL& Node::baseURI() const
1296 {
1297     auto& url = document().baseURL();
1298     return url.isNull() ? blankURL() : url;
1299 }
1300
1301 bool Node::isEqualNode(Node* other) const
1302 {
1303     if (!other)
1304         return false;
1305     
1306     NodeType nodeType = this->nodeType();
1307     if (nodeType != other->nodeType())
1308         return false;
1309     
1310     switch (nodeType) {
1311     case Node::DOCUMENT_TYPE_NODE: {
1312         auto& thisDocType = downcast<DocumentType>(*this);
1313         auto& otherDocType = downcast<DocumentType>(*other);
1314         if (thisDocType.name() != otherDocType.name())
1315             return false;
1316         if (thisDocType.publicId() != otherDocType.publicId())
1317             return false;
1318         if (thisDocType.systemId() != otherDocType.systemId())
1319             return false;
1320         break;
1321         }
1322     case Node::ELEMENT_NODE: {
1323         auto& thisElement = downcast<Element>(*this);
1324         auto& otherElement = downcast<Element>(*other);
1325         if (thisElement.tagQName() != otherElement.tagQName())
1326             return false;
1327         if (!thisElement.hasEquivalentAttributes(&otherElement))
1328             return false;
1329         break;
1330         }
1331     case Node::PROCESSING_INSTRUCTION_NODE: {
1332         auto& thisProcessingInstruction = downcast<ProcessingInstruction>(*this);
1333         auto& otherProcessingInstruction = downcast<ProcessingInstruction>(*other);
1334         if (thisProcessingInstruction.target() != otherProcessingInstruction.target())
1335             return false;
1336         if (thisProcessingInstruction.data() != otherProcessingInstruction.data())
1337             return false;
1338         break;
1339         }
1340     case Node::CDATA_SECTION_NODE:
1341     case Node::TEXT_NODE:
1342     case Node::COMMENT_NODE: {
1343         auto& thisCharacterData = downcast<CharacterData>(*this);
1344         auto& otherCharacterData = downcast<CharacterData>(*other);
1345         if (thisCharacterData.data() != otherCharacterData.data())
1346             return false;
1347         break;
1348         }
1349     case Node::ATTRIBUTE_NODE: {
1350         auto& thisAttribute = downcast<Attr>(*this);
1351         auto& otherAttribute = downcast<Attr>(*other);
1352         if (thisAttribute.qualifiedName() != otherAttribute.qualifiedName())
1353             return false;
1354         if (thisAttribute.value() != otherAttribute.value())
1355             return false;
1356         break;
1357         }
1358     case Node::DOCUMENT_NODE:
1359     case Node::DOCUMENT_FRAGMENT_NODE:
1360         break;
1361     }
1362     
1363     Node* child = firstChild();
1364     Node* otherChild = other->firstChild();
1365     
1366     while (child) {
1367         if (!child->isEqualNode(otherChild))
1368             return false;
1369         
1370         child = child->nextSibling();
1371         otherChild = otherChild->nextSibling();
1372     }
1373     
1374     if (otherChild)
1375         return false;
1376     
1377     return true;
1378 }
1379
1380 // https://dom.spec.whatwg.org/#locate-a-namespace
1381 static const AtomicString& locateDefaultNamespace(const Node& node, const AtomicString& prefix)
1382 {
1383     switch (node.nodeType()) {
1384     case Node::ELEMENT_NODE: {
1385         auto& element = downcast<Element>(node);
1386         auto& namespaceURI = element.namespaceURI();
1387         if (!namespaceURI.isNull() && element.prefix() == prefix)
1388             return namespaceURI;
1389
1390         if (element.hasAttributes()) {
1391             for (auto& attribute : element.attributesIterator()) {
1392                 if (attribute.namespaceURI() != XMLNSNames::xmlnsNamespaceURI)
1393                     continue;
1394
1395                 if ((prefix.isNull() && attribute.prefix().isNull() && attribute.localName() == xmlnsAtom) || (attribute.prefix() == xmlnsAtom && attribute.localName() == prefix)) {
1396                     auto& result = attribute.value();
1397                     return result.isEmpty() ? nullAtom : result;
1398                 }
1399             }
1400         }
1401         auto* parent = node.parentElement();
1402         return parent ? locateDefaultNamespace(*parent, prefix) : nullAtom;
1403     }
1404     case Node::DOCUMENT_NODE:
1405         if (auto* documentElement = downcast<Document>(node).documentElement())
1406             return locateDefaultNamespace(*documentElement, prefix);
1407         return nullAtom;
1408     case Node::DOCUMENT_TYPE_NODE:
1409     case Node::DOCUMENT_FRAGMENT_NODE:
1410         return nullAtom;
1411     case Node::ATTRIBUTE_NODE:
1412         if (auto* ownerElement = downcast<Attr>(node).ownerElement())
1413             return locateDefaultNamespace(*ownerElement, prefix);
1414         return nullAtom;
1415     default:
1416         if (auto* parent = node.parentElement())
1417             return locateDefaultNamespace(*parent, prefix);
1418         return nullAtom;
1419     }
1420 }
1421
1422 // https://dom.spec.whatwg.org/#dom-node-isdefaultnamespace
1423 bool Node::isDefaultNamespace(const AtomicString& potentiallyEmptyNamespace) const
1424 {
1425     const AtomicString& namespaceURI = potentiallyEmptyNamespace.isEmpty() ? nullAtom : potentiallyEmptyNamespace;
1426     return locateDefaultNamespace(*this, nullAtom) == namespaceURI;
1427 }
1428
1429 // https://dom.spec.whatwg.org/#dom-node-lookupnamespaceuri
1430 const AtomicString& Node::lookupNamespaceURI(const AtomicString& potentiallyEmptyPrefix) const
1431 {
1432     const AtomicString& prefix = potentiallyEmptyPrefix.isEmpty() ? nullAtom : potentiallyEmptyPrefix;
1433     return locateDefaultNamespace(*this, prefix);
1434 }
1435
1436 // https://dom.spec.whatwg.org/#locate-a-namespace-prefix
1437 static const AtomicString& locateNamespacePrefix(const Element& element, const AtomicString& namespaceURI)
1438 {
1439     if (element.namespaceURI() == namespaceURI)
1440         return element.prefix();
1441
1442     if (element.hasAttributes()) {
1443         for (auto& attribute : element.attributesIterator()) {
1444             if (attribute.prefix() == xmlnsAtom && attribute.value() == namespaceURI)
1445                 return attribute.localName();
1446         }
1447     }
1448     auto* parent = element.parentElement();
1449     return parent ? locateNamespacePrefix(*parent, namespaceURI) : nullAtom;
1450 }
1451
1452 // https://dom.spec.whatwg.org/#dom-node-lookupprefix
1453 const AtomicString& Node::lookupPrefix(const AtomicString& namespaceURI) const
1454 {
1455     if (namespaceURI.isEmpty())
1456         return nullAtom;
1457     
1458     switch (nodeType()) {
1459     case ELEMENT_NODE:
1460         return locateNamespacePrefix(downcast<Element>(*this), namespaceURI);
1461     case DOCUMENT_NODE:
1462         if (auto* documentElement = downcast<Document>(*this).documentElement())
1463             return locateNamespacePrefix(*documentElement, namespaceURI);
1464         return nullAtom;
1465     case DOCUMENT_FRAGMENT_NODE:
1466     case DOCUMENT_TYPE_NODE:
1467         return nullAtom;
1468     case ATTRIBUTE_NODE:
1469         if (auto* ownerElement = downcast<Attr>(*this).ownerElement())
1470             return locateNamespacePrefix(*ownerElement, namespaceURI);
1471         return nullAtom;
1472     default:
1473         if (auto* parent = parentElement())
1474             return locateNamespacePrefix(*parent, namespaceURI);
1475         return nullAtom;
1476     }
1477 }
1478
1479 static void appendTextContent(const Node* node, bool convertBRsToNewlines, bool& isNullString, StringBuilder& content)
1480 {
1481     switch (node->nodeType()) {
1482     case Node::TEXT_NODE:
1483     case Node::CDATA_SECTION_NODE:
1484     case Node::COMMENT_NODE:
1485         isNullString = false;
1486         content.append(downcast<CharacterData>(*node).data());
1487         break;
1488
1489     case Node::PROCESSING_INSTRUCTION_NODE:
1490         isNullString = false;
1491         content.append(downcast<ProcessingInstruction>(*node).data());
1492         break;
1493     
1494     case Node::ATTRIBUTE_NODE:
1495         isNullString = false;
1496         content.append(downcast<Attr>(*node).value());
1497         break;
1498
1499     case Node::ELEMENT_NODE:
1500         if (node->hasTagName(brTag) && convertBRsToNewlines) {
1501             isNullString = false;
1502             content.append('\n');
1503             break;
1504         }
1505         FALLTHROUGH;
1506     case Node::DOCUMENT_FRAGMENT_NODE:
1507         isNullString = false;
1508         for (Node* child = node->firstChild(); child; child = child->nextSibling()) {
1509             if (child->nodeType() == Node::COMMENT_NODE || child->nodeType() == Node::PROCESSING_INSTRUCTION_NODE)
1510                 continue;
1511             appendTextContent(child, convertBRsToNewlines, isNullString, content);
1512         }
1513         break;
1514
1515     case Node::DOCUMENT_NODE:
1516     case Node::DOCUMENT_TYPE_NODE:
1517         break;
1518     }
1519 }
1520
1521 String Node::textContent(bool convertBRsToNewlines) const
1522 {
1523     StringBuilder content;
1524     bool isNullString = true;
1525     appendTextContent(this, convertBRsToNewlines, isNullString, content);
1526     return isNullString ? String() : content.toString();
1527 }
1528
1529 ExceptionOr<void> Node::setTextContent(const String& text)
1530 {           
1531     switch (nodeType()) {
1532     case ATTRIBUTE_NODE:
1533     case TEXT_NODE:
1534     case CDATA_SECTION_NODE:
1535     case COMMENT_NODE:
1536     case PROCESSING_INSTRUCTION_NODE:
1537         return setNodeValue(text);
1538     case ELEMENT_NODE:
1539     case DOCUMENT_FRAGMENT_NODE: {
1540         auto& container = downcast<ContainerNode>(*this);
1541         if (text.isEmpty())
1542             container.replaceAllChildren(nullptr);
1543         else
1544             container.replaceAllChildren(document().createTextNode(text));
1545         return { };
1546     }
1547     case DOCUMENT_NODE:
1548     case DOCUMENT_TYPE_NODE:
1549         // Do nothing.
1550         return { };
1551     }
1552     ASSERT_NOT_REACHED();
1553     return { };
1554 }
1555
1556 bool Node::offsetInCharacters() const
1557 {
1558     return false;
1559 }
1560
1561 static SHA1::Digest hashPointer(void* pointer)
1562 {
1563     SHA1 sha1;
1564     sha1.addBytes(reinterpret_cast<const uint8_t*>(&pointer), sizeof(pointer));
1565     SHA1::Digest digest;
1566     sha1.computeHash(digest);
1567     return digest;
1568 }
1569
1570 static inline unsigned short compareDetachedElementsPosition(Node& firstNode, Node& secondNode)
1571 {
1572     // If the 2 nodes are not in the same tree, return the result of adding DOCUMENT_POSITION_DISCONNECTED,
1573     // DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC, and either DOCUMENT_POSITION_PRECEDING or
1574     // DOCUMENT_POSITION_FOLLOWING, with the constraint that this is to be consistent. Whether to return
1575     // DOCUMENT_POSITION_PRECEDING or DOCUMENT_POSITION_FOLLOWING is implemented by comparing cryptographic
1576     // hashes of Node pointers.
1577     // See step 3 in https://dom.spec.whatwg.org/#dom-node-comparedocumentposition
1578     SHA1::Digest firstHash = hashPointer(&firstNode);
1579     SHA1::Digest secondHash = hashPointer(&secondNode);
1580
1581     unsigned short direction = memcmp(firstHash.data(), secondHash.data(), SHA1::hashSize) > 0 ? Node::DOCUMENT_POSITION_PRECEDING : Node::DOCUMENT_POSITION_FOLLOWING;
1582
1583     return Node::DOCUMENT_POSITION_DISCONNECTED | Node::DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | direction;
1584 }
1585
1586 unsigned short Node::compareDocumentPosition(Node& otherNode)
1587 {
1588     if (&otherNode == this)
1589         return DOCUMENT_POSITION_EQUIVALENT;
1590     
1591     Attr* attr1 = is<Attr>(*this) ? downcast<Attr>(this) : nullptr;
1592     Attr* attr2 = is<Attr>(otherNode) ? &downcast<Attr>(otherNode) : nullptr;
1593     
1594     Node* start1 = attr1 ? attr1->ownerElement() : this;
1595     Node* start2 = attr2 ? attr2->ownerElement() : &otherNode;
1596     
1597     // If either of start1 or start2 is null, then we are disconnected, since one of the nodes is
1598     // an orphaned attribute node.
1599     if (!start1 || !start2)
1600         return compareDetachedElementsPosition(*this, otherNode);
1601
1602     Vector<Node*, 16> chain1;
1603     Vector<Node*, 16> chain2;
1604     if (attr1)
1605         chain1.append(attr1);
1606     if (attr2)
1607         chain2.append(attr2);
1608     
1609     if (attr1 && attr2 && start1 == start2 && start1) {
1610         // We are comparing two attributes on the same node. Crawl our attribute map and see which one we hit first.
1611         Element* owner1 = attr1->ownerElement();
1612         owner1->synchronizeAllAttributes();
1613         for (const Attribute& attribute : owner1->attributesIterator()) {
1614             // If neither of the two determining nodes is a child node and nodeType is the same for both determining nodes, then an
1615             // implementation-dependent order between the determining nodes is returned. This order is stable as long as no nodes of
1616             // the same nodeType are inserted into or removed from the direct container. This would be the case, for example, 
1617             // when comparing two attributes of the same element, and inserting or removing additional attributes might change 
1618             // the order between existing attributes.
1619             if (attr1->qualifiedName() == attribute.name())
1620                 return DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | DOCUMENT_POSITION_FOLLOWING;
1621             if (attr2->qualifiedName() == attribute.name())
1622                 return DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | DOCUMENT_POSITION_PRECEDING;
1623         }
1624         
1625         ASSERT_NOT_REACHED();
1626         return DOCUMENT_POSITION_DISCONNECTED;
1627     }
1628
1629     // If one node is in the document and the other is not, we must be disconnected.
1630     // If the nodes have different owning documents, they must be disconnected.  Note that we avoid
1631     // comparing Attr nodes here, since they return false from isConnected() all the time (which seems like a bug).
1632     if (start1->isConnected() != start2->isConnected() || &start1->treeScope() != &start2->treeScope())
1633         return compareDetachedElementsPosition(*this, otherNode);
1634
1635     // We need to find a common ancestor container, and then compare the indices of the two immediate children.
1636     Node* current;
1637     for (current = start1; current; current = current->parentNode())
1638         chain1.append(current);
1639     for (current = start2; current; current = current->parentNode())
1640         chain2.append(current);
1641
1642     unsigned index1 = chain1.size();
1643     unsigned index2 = chain2.size();
1644
1645     // If the two elements don't have a common root, they're not in the same tree.
1646     if (chain1[index1 - 1] != chain2[index2 - 1])
1647         return compareDetachedElementsPosition(*this, otherNode);
1648
1649     // Walk the two chains backwards and look for the first difference.
1650     for (unsigned i = std::min(index1, index2); i; --i) {
1651         Node* child1 = chain1[--index1];
1652         Node* child2 = chain2[--index2];
1653         if (child1 != child2) {
1654             // If one of the children is an attribute, it wins.
1655             if (child1->nodeType() == ATTRIBUTE_NODE)
1656                 return DOCUMENT_POSITION_FOLLOWING;
1657             if (child2->nodeType() == ATTRIBUTE_NODE)
1658                 return DOCUMENT_POSITION_PRECEDING;
1659             
1660             if (!child2->nextSibling())
1661                 return DOCUMENT_POSITION_FOLLOWING;
1662             if (!child1->nextSibling())
1663                 return DOCUMENT_POSITION_PRECEDING;
1664
1665             // Otherwise we need to see which node occurs first.  Crawl backwards from child2 looking for child1.
1666             for (Node* child = child2->previousSibling(); child; child = child->previousSibling()) {
1667                 if (child == child1)
1668                     return DOCUMENT_POSITION_FOLLOWING;
1669             }
1670             return DOCUMENT_POSITION_PRECEDING;
1671         }
1672     }
1673     
1674     // There was no difference between the two parent chains, i.e., one was a subset of the other.  The shorter
1675     // chain is the ancestor.
1676     return index1 < index2 ? 
1677                DOCUMENT_POSITION_FOLLOWING | DOCUMENT_POSITION_CONTAINED_BY :
1678                DOCUMENT_POSITION_PRECEDING | DOCUMENT_POSITION_CONTAINS;
1679 }
1680
1681 FloatPoint Node::convertToPage(const FloatPoint& p) const
1682 {
1683     // If there is a renderer, just ask it to do the conversion
1684     if (renderer())
1685         return renderer()->localToAbsolute(p, UseTransforms);
1686     
1687     // Otherwise go up the tree looking for a renderer
1688     if (auto* parent = parentElement())
1689         return parent->convertToPage(p);
1690
1691     // No parent - no conversion needed
1692     return p;
1693 }
1694
1695 FloatPoint Node::convertFromPage(const FloatPoint& p) const
1696 {
1697     // If there is a renderer, just ask it to do the conversion
1698     if (renderer())
1699         return renderer()->absoluteToLocal(p, UseTransforms);
1700
1701     // Otherwise go up the tree looking for a renderer
1702     if (auto* parent = parentElement())
1703         return parent->convertFromPage(p);
1704
1705     // No parent - no conversion needed
1706     return p;
1707 }
1708
1709 #if ENABLE(TREE_DEBUGGING)
1710
1711 static void appendAttributeDesc(const Node* node, StringBuilder& stringBuilder, const QualifiedName& name, const char* attrDesc)
1712 {
1713     if (!is<Element>(*node))
1714         return;
1715
1716     const AtomicString& attr = downcast<Element>(*node).getAttribute(name);
1717     if (attr.isEmpty())
1718         return;
1719
1720     stringBuilder.append(attrDesc);
1721     stringBuilder.append(attr);
1722 }
1723
1724 void Node::showNode(const char* prefix) const
1725 {
1726     if (!prefix)
1727         prefix = "";
1728     if (isTextNode()) {
1729         String value = nodeValue();
1730         value.replaceWithLiteral('\\', "\\\\");
1731         value.replaceWithLiteral('\n', "\\n");
1732         WTFLogAlways("%s%s\t%p \"%s\"\n", prefix, nodeName().utf8().data(), this, value.utf8().data());
1733     } else {
1734         StringBuilder attrs;
1735         appendAttributeDesc(this, attrs, classAttr, " CLASS=");
1736         appendAttributeDesc(this, attrs, styleAttr, " STYLE=");
1737         WTFLogAlways("%s%s\t%p (renderer %p) %s%s%s\n", prefix, nodeName().utf8().data(), this, renderer(), attrs.toString().utf8().data(), needsStyleRecalc() ? " (needs style recalc)" : "", childNeedsStyleRecalc() ? " (child needs style recalc)" : "");
1738     }
1739 }
1740
1741 void Node::showTreeForThis() const
1742 {
1743     showTreeAndMark(this, "*");
1744 }
1745
1746 void Node::showNodePathForThis() const
1747 {
1748     Vector<const Node*, 16> chain;
1749     const Node* node = this;
1750     while (node->parentOrShadowHostNode()) {
1751         chain.append(node);
1752         node = node->parentOrShadowHostNode();
1753     }
1754     for (unsigned index = chain.size(); index > 0; --index) {
1755         const Node* node = chain[index - 1];
1756         if (is<ShadowRoot>(*node)) {
1757             int count = 0;
1758             for (const ShadowRoot* shadowRoot = downcast<ShadowRoot>(node); shadowRoot && shadowRoot != node; shadowRoot = shadowRoot->shadowRoot())
1759                 ++count;
1760             WTFLogAlways("/#shadow-root[%d]", count);
1761             continue;
1762         }
1763
1764         switch (node->nodeType()) {
1765         case ELEMENT_NODE: {
1766             WTFLogAlways("/%s", node->nodeName().utf8().data());
1767
1768             const Element& element = downcast<Element>(*node);
1769             const AtomicString& idattr = element.getIdAttribute();
1770             bool hasIdAttr = !idattr.isNull() && !idattr.isEmpty();
1771             if (node->previousSibling() || node->nextSibling()) {
1772                 int count = 0;
1773                 for (Node* previous = node->previousSibling(); previous; previous = previous->previousSibling())
1774                     if (previous->nodeName() == node->nodeName())
1775                         ++count;
1776                 if (hasIdAttr)
1777                     WTFLogAlways("[@id=\"%s\" and position()=%d]", idattr.string().utf8().data(), count);
1778                 else
1779                     WTFLogAlways("[%d]", count);
1780             } else if (hasIdAttr)
1781                 WTFLogAlways("[@id=\"%s\"]", idattr.string().utf8().data());
1782             break;
1783         }
1784         case TEXT_NODE:
1785             WTFLogAlways("/text()");
1786             break;
1787         case ATTRIBUTE_NODE:
1788             WTFLogAlways("/@%s", node->nodeName().utf8().data());
1789             break;
1790         default:
1791             break;
1792         }
1793     }
1794     WTFLogAlways("\n");
1795 }
1796
1797 static void traverseTreeAndMark(const String& baseIndent, const Node* rootNode, const Node* markedNode1, const char* markedLabel1, const Node* markedNode2, const char* markedLabel2)
1798 {
1799     for (const Node* node = rootNode; node; node = NodeTraversal::next(*node)) {
1800         if (node == markedNode1)
1801             WTFLogAlways("%s", markedLabel1);
1802         if (node == markedNode2)
1803             WTFLogAlways("%s", markedLabel2);
1804
1805         StringBuilder indent;
1806         indent.append(baseIndent);
1807         for (const Node* tmpNode = node; tmpNode && tmpNode != rootNode; tmpNode = tmpNode->parentOrShadowHostNode())
1808             indent.append('\t');
1809         WTFLogAlways("%s", indent.toString().utf8().data());
1810         node->showNode();
1811         indent.append('\t');
1812         if (!node->isShadowRoot()) {
1813             if (ShadowRoot* shadowRoot = node->shadowRoot())
1814                 traverseTreeAndMark(indent.toString(), shadowRoot, markedNode1, markedLabel1, markedNode2, markedLabel2);
1815         }
1816     }
1817 }
1818
1819 void Node::showTreeAndMark(const Node* markedNode1, const char* markedLabel1, const Node* markedNode2, const char* markedLabel2) const
1820 {
1821     const Node* rootNode;
1822     const Node* node = this;
1823     while (node->parentOrShadowHostNode() && !node->hasTagName(bodyTag))
1824         node = node->parentOrShadowHostNode();
1825     rootNode = node;
1826
1827     String startingIndent;
1828     traverseTreeAndMark(startingIndent, rootNode, markedNode1, markedLabel1, markedNode2, markedLabel2);
1829 }
1830
1831 void Node::formatForDebugger(char* buffer, unsigned length) const
1832 {
1833     String result;
1834     String s;
1835
1836     s = nodeName();
1837     if (s.isEmpty())
1838         result = "<none>";
1839     else
1840         result = s;
1841
1842     strncpy(buffer, result.utf8().data(), length - 1);
1843 }
1844
1845 static ContainerNode* parentOrShadowHostOrFrameOwner(const Node* node)
1846 {
1847     ContainerNode* parent = node->parentOrShadowHostNode();
1848     if (!parent && node->document().frame())
1849         parent = node->document().frame()->ownerElement();
1850     return parent;
1851 }
1852
1853 static void showSubTreeAcrossFrame(const Node* node, const Node* markedNode, const String& indent)
1854 {
1855     if (node == markedNode)
1856         fputs("*", stderr);
1857     fputs(indent.utf8().data(), stderr);
1858     node->showNode();
1859     if (!node->isShadowRoot()) {
1860         if (node->isFrameOwnerElement())
1861             showSubTreeAcrossFrame(static_cast<const HTMLFrameOwnerElement*>(node)->contentDocument(), markedNode, indent + "\t");
1862         if (ShadowRoot* shadowRoot = node->shadowRoot())
1863             showSubTreeAcrossFrame(shadowRoot, markedNode, indent + "\t");
1864     }
1865     for (Node* child = node->firstChild(); child; child = child->nextSibling())
1866         showSubTreeAcrossFrame(child, markedNode, indent + "\t");
1867 }
1868
1869 void Node::showTreeForThisAcrossFrame() const
1870 {
1871     Node* rootNode = const_cast<Node*>(this);
1872     while (parentOrShadowHostOrFrameOwner(rootNode))
1873         rootNode = parentOrShadowHostOrFrameOwner(rootNode);
1874     showSubTreeAcrossFrame(rootNode, this, "");
1875 }
1876
1877 #endif // ENABLE(TREE_DEBUGGING)
1878
1879 // --------
1880
1881 void NodeListsNodeData::invalidateCaches()
1882 {
1883     for (auto& atomicName : m_atomicNameCaches)
1884         atomicName.value->invalidateCache();
1885
1886     for (auto& collection : m_cachedCollections)
1887         collection.value->invalidateCache();
1888
1889     for (auto& tagCollection : m_tagCollectionNSCache)
1890         tagCollection.value->invalidateCache();
1891 }
1892
1893 void NodeListsNodeData::invalidateCachesForAttribute(const QualifiedName& attrName)
1894 {
1895     for (auto& atomicName : m_atomicNameCaches)
1896         atomicName.value->invalidateCacheForAttribute(attrName);
1897
1898     for (auto& collection : m_cachedCollections)
1899         collection.value->invalidateCacheForAttribute(attrName);
1900 }
1901
1902 void Node::getSubresourceURLs(ListHashSet<URL>& urls) const
1903 {
1904     addSubresourceAttributeURLs(urls);
1905 }
1906
1907 Element* Node::enclosingLinkEventParentOrSelf()
1908 {
1909     for (Node* node = this; node; node = node->parentInComposedTree()) {
1910         // For imagemaps, the enclosing link element is the associated area element not the image itself.
1911         // So we don't let images be the enclosing link element, even though isLink sometimes returns
1912         // true for them.
1913         if (node->isLink() && !is<HTMLImageElement>(*node))
1914             return downcast<Element>(node);
1915     }
1916
1917     return nullptr;
1918 }
1919
1920 EventTargetInterface Node::eventTargetInterface() const
1921 {
1922     return NodeEventTargetInterfaceType;
1923 }
1924
1925 #if !ASSERT_DISABLED || ENABLE(SECURITY_ASSERTIONS)
1926 class DidMoveToNewDocumentAssertionScope {
1927 public:
1928     DidMoveToNewDocumentAssertionScope(Node& node, Document& oldDocument, Document& newDocument)
1929         : m_node(node)
1930         , m_oldDocument(oldDocument)
1931         , m_newDocument(newDocument)
1932         , m_previousScope(s_scope)
1933     {
1934         s_scope = this;
1935     }
1936
1937     ~DidMoveToNewDocumentAssertionScope()
1938     {
1939         ASSERT_WITH_SECURITY_IMPLICATION(m_called);
1940         s_scope = m_previousScope;
1941     }
1942
1943     static void didRecieveCall(Node& node, Document& oldDocument, Document& newDocument)
1944     {
1945         ASSERT_WITH_SECURITY_IMPLICATION(s_scope);
1946         ASSERT_WITH_SECURITY_IMPLICATION(!s_scope->m_called);
1947         ASSERT_WITH_SECURITY_IMPLICATION(&s_scope->m_node == &node);
1948         ASSERT_WITH_SECURITY_IMPLICATION(&s_scope->m_oldDocument == &oldDocument);
1949         ASSERT_WITH_SECURITY_IMPLICATION(&s_scope->m_newDocument == &newDocument);
1950         s_scope->m_called = true;
1951     }
1952
1953 private:
1954     Node& m_node;
1955     Document& m_oldDocument;
1956     Document& m_newDocument;
1957     bool m_called { false };
1958     DidMoveToNewDocumentAssertionScope* m_previousScope;
1959
1960     static DidMoveToNewDocumentAssertionScope* s_scope;
1961 };
1962
1963 DidMoveToNewDocumentAssertionScope* DidMoveToNewDocumentAssertionScope::s_scope = nullptr;
1964
1965 #else
1966 class DidMoveToNewDocumentAssertionScope {
1967 public:
1968     DidMoveToNewDocumentAssertionScope(Node&, Document&, Document&) { }
1969     static void didRecieveCall(Node&, Document&, Document&) { }
1970 };
1971 #endif
1972
1973 static ALWAYS_INLINE void moveNodeToNewDocument(Node& node, Document& oldDocument, Document& newDocument)
1974 {
1975     ASSERT(!node.isConnected() || &oldDocument != &newDocument);
1976     DidMoveToNewDocumentAssertionScope scope(node, oldDocument, newDocument);
1977     node.didMoveToNewDocument(oldDocument, newDocument);
1978     ASSERT_WITH_SECURITY_IMPLICATION(&node.document() == &newDocument);
1979 }
1980
1981 template <typename MoveNodeFunction, typename MoveShadowRootFunction>
1982 static void traverseSubtreeToUpdateTreeScope(Node& root, MoveNodeFunction moveNode, MoveShadowRootFunction moveShadowRoot)
1983 {
1984     for (Node* node = &root; node; node = NodeTraversal::next(*node, &root)) {
1985         moveNode(*node);
1986
1987         if (!is<Element>(*node))
1988             continue;
1989         Element& element = downcast<Element>(*node);
1990
1991         if (element.hasSyntheticAttrChildNodes()) {
1992             for (auto& attr : element.attrNodeList())
1993                 moveNode(*attr);
1994         }
1995
1996         if (auto* shadow = element.shadowRoot())
1997             moveShadowRoot(*shadow);
1998     }
1999 }
2000
2001 static void moveShadowTreeToNewDocument(ShadowRoot& shadowRoot, Document& oldDocument, Document& newDocument)
2002 {
2003     traverseSubtreeToUpdateTreeScope(shadowRoot, [&oldDocument, &newDocument](Node& node) {
2004         moveNodeToNewDocument(node, oldDocument, newDocument);
2005     }, [&oldDocument, &newDocument](ShadowRoot& innerShadowRoot) {
2006         ASSERT_WITH_SECURITY_IMPLICATION(&innerShadowRoot.document() == &oldDocument);
2007         moveShadowTreeToNewDocument(innerShadowRoot, oldDocument, newDocument);
2008     });
2009 }
2010
2011 void Node::moveTreeToNewScope(Node& root, TreeScope& oldScope, TreeScope& newScope)
2012 {
2013     ASSERT(&oldScope != &newScope);
2014     ASSERT_WITH_SECURITY_IMPLICATION(&root.treeScope() == &oldScope);
2015
2016     Document& oldDocument = oldScope.documentScope();
2017     Document& newDocument = newScope.documentScope();
2018     if (&oldDocument != &newDocument) {
2019         oldDocument.incrementReferencingNodeCount();
2020         traverseSubtreeToUpdateTreeScope(root, [&](Node& node) {
2021             ASSERT(!node.isTreeScope());
2022             ASSERT_WITH_SECURITY_IMPLICATION(&node.treeScope() == &oldScope);
2023             ASSERT_WITH_SECURITY_IMPLICATION(&node.document() == &oldDocument);
2024             node.setTreeScope(newScope);
2025             moveNodeToNewDocument(node, oldDocument, newDocument);
2026         }, [&](ShadowRoot& shadowRoot) {
2027             ASSERT_WITH_SECURITY_IMPLICATION(&shadowRoot.document() == &oldDocument);
2028             shadowRoot.setParentTreeScope(newScope);
2029             moveShadowTreeToNewDocument(shadowRoot, oldDocument, newDocument);
2030         });
2031         oldDocument.decrementReferencingNodeCount();
2032     } else {
2033         traverseSubtreeToUpdateTreeScope(root, [&](Node& node) {
2034             ASSERT(!node.isTreeScope());
2035             ASSERT_WITH_SECURITY_IMPLICATION(&node.treeScope() == &oldScope);
2036             node.setTreeScope(newScope);
2037             if (!node.hasRareData())
2038                 return;
2039             if (auto* nodeLists = node.rareData()->nodeLists())
2040                 nodeLists->adoptTreeScope();
2041         }, [&newScope](ShadowRoot& shadowRoot) {
2042             shadowRoot.setParentTreeScope(newScope);
2043         });
2044     }
2045 }
2046
2047 void Node::didMoveToNewDocument(Document& oldDocument, Document& newDocument)
2048 {
2049     ASSERT_WITH_SECURITY_IMPLICATION(&document() == &newDocument);
2050     DidMoveToNewDocumentAssertionScope::didRecieveCall(*this, oldDocument, newDocument);
2051
2052     newDocument.incrementReferencingNodeCount();
2053     oldDocument.decrementReferencingNodeCount();
2054
2055     if (hasRareData()) {
2056         if (auto* nodeLists = rareData()->nodeLists())
2057             nodeLists->adoptDocument(oldDocument, newDocument);
2058     }
2059
2060     oldDocument.moveNodeIteratorsToNewDocument(*this, newDocument);
2061
2062     if (auto* eventTargetData = this->eventTargetData()) {
2063         if (!eventTargetData->eventListenerMap.isEmpty()) {
2064             for (auto& type : eventTargetData->eventListenerMap.eventTypes())
2065                 newDocument.addListenerTypeIfNeeded(type);
2066         }
2067     }
2068
2069     if (AXObjectCache::accessibilityEnabled()) {
2070         if (auto* cache = oldDocument.existingAXObjectCache())
2071             cache->remove(this);
2072     }
2073
2074     unsigned numWheelEventHandlers = eventListeners(eventNames().mousewheelEvent).size() + eventListeners(eventNames().wheelEvent).size();
2075     for (unsigned i = 0; i < numWheelEventHandlers; ++i) {
2076         oldDocument.didRemoveWheelEventHandler(*this);
2077         newDocument.didAddWheelEventHandler(*this);
2078     }
2079
2080     unsigned numTouchEventListeners = 0;
2081     for (auto& name : eventNames().touchEventNames())
2082         numTouchEventListeners += eventListeners(name).size();
2083
2084     for (unsigned i = 0; i < numTouchEventListeners; ++i) {
2085         oldDocument.didRemoveTouchEventHandler(*this);
2086         newDocument.didAddTouchEventHandler(*this);
2087
2088 #if ENABLE(TOUCH_EVENTS) && PLATFORM(IOS)
2089         oldDocument.removeTouchEventListener(*this);
2090         newDocument.addTouchEventListener(*this);
2091 #endif
2092     }
2093
2094 #if ENABLE(TOUCH_EVENTS) && ENABLE(IOS_GESTURE_EVENTS)
2095     unsigned numGestureEventListeners = 0;
2096     for (auto& name : eventNames().gestureEventNames())
2097         numGestureEventListeners += eventListeners(name).size();
2098
2099     for (unsigned i = 0; i < numGestureEventListeners; ++i) {
2100         oldDocument.removeTouchEventHandler(*this);
2101         newDocument.addTouchEventHandler(*this);
2102     }
2103 #endif
2104
2105     if (auto* registry = mutationObserverRegistry()) {
2106         for (auto& registration : *registry)
2107             newDocument.addMutationObserverTypes(registration->mutationTypes());
2108     }
2109
2110     if (auto* transientRegistry = transientMutationObserverRegistry()) {
2111         for (auto& registration : *transientRegistry)
2112             newDocument.addMutationObserverTypes(registration->mutationTypes());
2113     }
2114
2115 #if !ASSERT_DISABLED || ENABLE(SECURITY_ASSERTIONS)
2116 #if ENABLE(TOUCH_EVENTS) && PLATFORM(IOS)
2117     ASSERT_WITH_SECURITY_IMPLICATION(!oldDocument.touchEventListenersContain(*this));
2118     ASSERT_WITH_SECURITY_IMPLICATION(!oldDocument.touchEventHandlersContain(*this));
2119 #endif
2120 #if ENABLE(TOUCH_EVENTS) && ENABLE(IOS_GESTURE_EVENTS)
2121     ASSERT_WITH_SECURITY_IMPLICATION(!oldDocument.touchEventTargetsContain(*this));
2122 #endif
2123 #endif
2124 }
2125
2126 static inline bool tryAddEventListener(Node* targetNode, const AtomicString& eventType, Ref<EventListener>&& listener, const EventTarget::AddEventListenerOptions& options)
2127 {
2128     if (!targetNode->EventTarget::addEventListener(eventType, listener.copyRef(), options))
2129         return false;
2130
2131     targetNode->document().addListenerTypeIfNeeded(eventType);
2132     if (eventNames().isWheelEventType(eventType))
2133         targetNode->document().didAddWheelEventHandler(*targetNode);
2134     else if (eventNames().isTouchEventType(eventType))
2135         targetNode->document().didAddTouchEventHandler(*targetNode);
2136
2137 #if PLATFORM(IOS)
2138     if (targetNode == &targetNode->document() && eventType == eventNames().scrollEvent)
2139         targetNode->document().domWindow()->incrementScrollEventListenersCount();
2140
2141     // FIXME: Would it be sufficient to special-case this code for <body> and <frameset>?
2142     //
2143     // This code was added to address <rdar://problem/5846492> Onorientationchange event not working for document.body.
2144     // Forward this call to addEventListener() to the window since these are window-only events.
2145     if (eventType == eventNames().orientationchangeEvent || eventType == eventNames().resizeEvent)
2146         targetNode->document().domWindow()->addEventListener(eventType, WTFMove(listener), options);
2147
2148 #if ENABLE(TOUCH_EVENTS)
2149     if (eventNames().isTouchEventType(eventType))
2150         targetNode->document().addTouchEventListener(*targetNode);
2151 #endif
2152 #endif // PLATFORM(IOS)
2153
2154 #if ENABLE(IOS_GESTURE_EVENTS) && ENABLE(TOUCH_EVENTS)
2155     if (eventNames().isGestureEventType(eventType))
2156         targetNode->document().addTouchEventHandler(*targetNode);
2157 #endif
2158
2159     return true;
2160 }
2161
2162 bool Node::addEventListener(const AtomicString& eventType, Ref<EventListener>&& listener, const AddEventListenerOptions& options)
2163 {
2164     return tryAddEventListener(this, eventType, WTFMove(listener), options);
2165 }
2166
2167 static inline bool tryRemoveEventListener(Node* targetNode, const AtomicString& eventType, EventListener& listener, const EventTarget::ListenerOptions& options)
2168 {
2169     if (!targetNode->EventTarget::removeEventListener(eventType, listener, options))
2170         return false;
2171
2172     // FIXME: Notify Document that the listener has vanished. We need to keep track of a number of
2173     // listeners for each type, not just a bool - see https://bugs.webkit.org/show_bug.cgi?id=33861
2174     if (eventNames().isWheelEventType(eventType))
2175         targetNode->document().didRemoveWheelEventHandler(*targetNode);
2176     else if (eventNames().isTouchEventType(eventType))
2177         targetNode->document().didRemoveTouchEventHandler(*targetNode);
2178
2179 #if PLATFORM(IOS)
2180     if (targetNode == &targetNode->document() && eventType == eventNames().scrollEvent)
2181         targetNode->document().domWindow()->decrementScrollEventListenersCount();
2182
2183     // FIXME: Would it be sufficient to special-case this code for <body> and <frameset>? See <rdar://problem/15647823>.
2184     // This code was added to address <rdar://problem/5846492> Onorientationchange event not working for document.body.
2185     // Forward this call to removeEventListener() to the window since these are window-only events.
2186     if (eventType == eventNames().orientationchangeEvent || eventType == eventNames().resizeEvent)
2187         targetNode->document().domWindow()->removeEventListener(eventType, listener, options);
2188
2189 #if ENABLE(TOUCH_EVENTS)
2190     if (eventNames().isTouchEventType(eventType))
2191         targetNode->document().removeTouchEventListener(*targetNode);
2192 #endif
2193 #endif // PLATFORM(IOS)
2194
2195 #if ENABLE(IOS_GESTURE_EVENTS) && ENABLE(TOUCH_EVENTS)
2196     if (eventNames().isGestureEventType(eventType))
2197         targetNode->document().removeTouchEventHandler(*targetNode);
2198 #endif
2199
2200     return true;
2201 }
2202
2203 bool Node::removeEventListener(const AtomicString& eventType, EventListener& listener, const ListenerOptions& options)
2204 {
2205     return tryRemoveEventListener(this, eventType, listener, options);
2206 }
2207
2208 typedef HashMap<Node*, std::unique_ptr<EventTargetData>> EventTargetDataMap;
2209
2210 static EventTargetDataMap& eventTargetDataMap()
2211 {
2212     static NeverDestroyed<EventTargetDataMap> map;
2213
2214     return map;
2215 }
2216
2217 static StaticLock s_eventTargetDataMapLock;
2218
2219 EventTargetData* Node::eventTargetData()
2220 {
2221     return hasEventTargetData() ? eventTargetDataMap().get(this) : nullptr;
2222 }
2223
2224 EventTargetData* Node::eventTargetDataConcurrently()
2225 {
2226     auto locker = holdLock(s_eventTargetDataMapLock);
2227     return hasEventTargetData() ? eventTargetDataMap().get(this) : nullptr;
2228 }
2229
2230 EventTargetData& Node::ensureEventTargetData()
2231 {
2232     if (hasEventTargetData())
2233         return *eventTargetDataMap().get(this);
2234
2235     auto locker = holdLock(s_eventTargetDataMapLock);
2236     setHasEventTargetData(true);
2237     return *eventTargetDataMap().add(this, std::make_unique<EventTargetData>()).iterator->value;
2238 }
2239
2240 void Node::clearEventTargetData()
2241 {
2242     auto locker = holdLock(s_eventTargetDataMapLock);
2243     eventTargetDataMap().remove(this);
2244 }
2245
2246 Vector<std::unique_ptr<MutationObserverRegistration>>* Node::mutationObserverRegistry()
2247 {
2248     if (!hasRareData())
2249         return nullptr;
2250     auto* data = rareData()->mutationObserverData();
2251     if (!data)
2252         return nullptr;
2253     return &data->registry;
2254 }
2255
2256 HashSet<MutationObserverRegistration*>* Node::transientMutationObserverRegistry()
2257 {
2258     if (!hasRareData())
2259         return nullptr;
2260     auto* data = rareData()->mutationObserverData();
2261     if (!data)
2262         return nullptr;
2263     return &data->transientRegistry;
2264 }
2265
2266 template<typename Registry> static inline void collectMatchingObserversForMutation(HashMap<MutationObserver*, MutationRecordDeliveryOptions>& observers, Registry* registry, Node& target, MutationObserver::MutationType type, const QualifiedName* attributeName)
2267 {
2268     if (!registry)
2269         return;
2270
2271     for (auto& registration : *registry) {
2272         if (registration->shouldReceiveMutationFrom(target, type, attributeName)) {
2273             auto deliveryOptions = registration->deliveryOptions();
2274             auto result = observers.add(&registration->observer(), deliveryOptions);
2275             if (!result.isNewEntry)
2276                 result.iterator->value |= deliveryOptions;
2277         }
2278     }
2279 }
2280
2281 HashMap<MutationObserver*, MutationRecordDeliveryOptions> Node::registeredMutationObservers(MutationObserver::MutationType type, const QualifiedName* attributeName)
2282 {
2283     HashMap<MutationObserver*, MutationRecordDeliveryOptions> result;
2284     ASSERT((type == MutationObserver::Attributes && attributeName) || !attributeName);
2285     collectMatchingObserversForMutation(result, mutationObserverRegistry(), *this, type, attributeName);
2286     collectMatchingObserversForMutation(result, transientMutationObserverRegistry(), *this, type, attributeName);
2287     for (Node* node = parentNode(); node; node = node->parentNode()) {
2288         collectMatchingObserversForMutation(result, node->mutationObserverRegistry(), *this, type, attributeName);
2289         collectMatchingObserversForMutation(result, node->transientMutationObserverRegistry(), *this, type, attributeName);
2290     }
2291     return result;
2292 }
2293
2294 void Node::registerMutationObserver(MutationObserver& observer, MutationObserverOptions options, const HashSet<AtomicString>& attributeFilter)
2295 {
2296     MutationObserverRegistration* registration = nullptr;
2297     auto& registry = ensureRareData().ensureMutationObserverData().registry;
2298
2299     for (auto& candidateRegistration : registry) {
2300         if (&candidateRegistration->observer() == &observer) {
2301             registration = candidateRegistration.get();
2302             registration->resetObservation(options, attributeFilter);
2303         }
2304     }
2305
2306     if (!registration) {
2307         registry.append(std::make_unique<MutationObserverRegistration>(observer, *this, options, attributeFilter));
2308         registration = registry.last().get();
2309     }
2310
2311     document().addMutationObserverTypes(registration->mutationTypes());
2312 }
2313
2314 void Node::unregisterMutationObserver(MutationObserverRegistration& registration)
2315 {
2316     auto* registry = mutationObserverRegistry();
2317     ASSERT(registry);
2318     if (!registry)
2319         return;
2320
2321     registry->removeFirstMatching([&registration] (auto& current) {
2322         return current.get() == &registration;
2323     });
2324 }
2325
2326 void Node::registerTransientMutationObserver(MutationObserverRegistration& registration)
2327 {
2328     ensureRareData().ensureMutationObserverData().transientRegistry.add(&registration);
2329 }
2330
2331 void Node::unregisterTransientMutationObserver(MutationObserverRegistration& registration)
2332 {
2333     auto* transientRegistry = transientMutationObserverRegistry();
2334     ASSERT(transientRegistry);
2335     if (!transientRegistry)
2336         return;
2337
2338     ASSERT(transientRegistry->contains(&registration));
2339     transientRegistry->remove(&registration);
2340 }
2341
2342 void Node::notifyMutationObserversNodeWillDetach()
2343 {
2344     if (!document().hasMutationObservers())
2345         return;
2346
2347     for (Node* node = parentNode(); node; node = node->parentNode()) {
2348         if (auto* registry = node->mutationObserverRegistry()) {
2349             for (auto& registration : *registry)
2350                 registration->observedSubtreeNodeWillDetach(*this);
2351         }
2352         if (auto* transientRegistry = node->transientMutationObserverRegistry()) {
2353             for (auto* registration : *transientRegistry)
2354                 registration->observedSubtreeNodeWillDetach(*this);
2355         }
2356     }
2357 }
2358
2359 void Node::handleLocalEvents(Event& event)
2360 {
2361     if (!hasEventTargetData())
2362         return;
2363
2364     // FIXME: Should we deliver wheel events to disabled form controls or not?
2365     if (is<Element>(*this) && downcast<Element>(*this).isDisabledFormControl() && event.isMouseEvent() && !event.isWheelEvent())
2366         return;
2367
2368     fireEventListeners(event);
2369 }
2370
2371 void Node::dispatchScopedEvent(Event& event)
2372 {
2373     EventDispatcher::dispatchScopedEvent(*this, event);
2374 }
2375
2376 bool Node::dispatchEvent(Event& event)
2377 {
2378 #if ENABLE(TOUCH_EVENTS) && !PLATFORM(IOS)
2379     if (is<TouchEvent>(event))
2380         return dispatchTouchEvent(downcast<TouchEvent>(event));
2381 #endif
2382     return EventDispatcher::dispatchEvent(*this, event);
2383 }
2384
2385 void Node::dispatchSubtreeModifiedEvent()
2386 {
2387     if (isInShadowTree())
2388         return;
2389
2390     ASSERT_WITH_SECURITY_IMPLICATION(NoEventDispatchAssertion::isEventDispatchAllowedInSubtree(*this));
2391
2392     if (!document().hasListenerType(Document::DOMSUBTREEMODIFIED_LISTENER))
2393         return;
2394     const AtomicString& subtreeModifiedEventName = eventNames().DOMSubtreeModifiedEvent;
2395     if (!parentNode() && !hasEventListeners(subtreeModifiedEventName))
2396         return;
2397
2398     dispatchScopedEvent(MutationEvent::create(subtreeModifiedEventName, true));
2399 }
2400
2401 bool Node::dispatchDOMActivateEvent(int detail, Event& underlyingEvent)
2402 {
2403     ASSERT_WITH_SECURITY_IMPLICATION(NoEventDispatchAssertion::isEventAllowedInMainThread());
2404     Ref<UIEvent> event = UIEvent::create(eventNames().DOMActivateEvent, true, true, document().defaultView(), detail);
2405     event->setUnderlyingEvent(&underlyingEvent);
2406     dispatchScopedEvent(event);
2407     return event->defaultHandled();
2408 }
2409
2410 #if ENABLE(TOUCH_EVENTS) && !PLATFORM(IOS)
2411 bool Node::dispatchTouchEvent(TouchEvent& event)
2412 {
2413     return EventDispatcher::dispatchEvent(*this, event);
2414 }
2415 #endif
2416
2417 bool Node::dispatchBeforeLoadEvent(const String& sourceURL)
2418 {
2419     if (!document().hasListenerType(Document::BEFORELOAD_LISTENER))
2420         return true;
2421
2422     Ref<Node> protectedThis(*this);
2423     Ref<BeforeLoadEvent> beforeLoadEvent = BeforeLoadEvent::create(sourceURL);
2424     dispatchEvent(beforeLoadEvent);
2425     return !beforeLoadEvent->defaultPrevented();
2426 }
2427
2428 void Node::dispatchInputEvent()
2429 {
2430     dispatchScopedEvent(Event::create(eventNames().inputEvent, true, false));
2431 }
2432
2433 void Node::defaultEventHandler(Event& event)
2434 {
2435     if (event.target() != this)
2436         return;
2437     const AtomicString& eventType = event.type();
2438     if (eventType == eventNames().keydownEvent || eventType == eventNames().keypressEvent) {
2439         if (is<KeyboardEvent>(event)) {
2440             if (Frame* frame = document().frame())
2441                 frame->eventHandler().defaultKeyboardEventHandler(downcast<KeyboardEvent>(event));
2442         }
2443     } else if (eventType == eventNames().clickEvent) {
2444         int detail = is<UIEvent>(event) ? downcast<UIEvent>(event).detail() : 0;
2445         if (dispatchDOMActivateEvent(detail, event))
2446             event.setDefaultHandled();
2447 #if ENABLE(CONTEXT_MENUS)
2448     } else if (eventType == eventNames().contextmenuEvent) {
2449         if (Frame* frame = document().frame())
2450             if (Page* page = frame->page())
2451                 page->contextMenuController().handleContextMenuEvent(event);
2452 #endif
2453     } else if (eventType == eventNames().textInputEvent) {
2454         if (is<TextEvent>(event)) {
2455             if (Frame* frame = document().frame())
2456                 frame->eventHandler().defaultTextInputEventHandler(downcast<TextEvent>(event));
2457         }
2458 #if ENABLE(PAN_SCROLLING)
2459     } else if (eventType == eventNames().mousedownEvent && is<MouseEvent>(event)) {
2460         if (downcast<MouseEvent>(event).button() == MiddleButton) {
2461             if (enclosingLinkEventParentOrSelf())
2462                 return;
2463
2464             RenderObject* renderer = this->renderer();
2465             while (renderer && (!is<RenderBox>(*renderer) || !downcast<RenderBox>(*renderer).canBeScrolledAndHasScrollableArea()))
2466                 renderer = renderer->parent();
2467
2468             if (renderer) {
2469                 if (Frame* frame = document().frame())
2470                     frame->eventHandler().startPanScrolling(downcast<RenderBox>(*renderer));
2471             }
2472         }
2473 #endif
2474     } else if (eventNames().isWheelEventType(eventType) && is<WheelEvent>(event)) {
2475         // If we don't have a renderer, send the wheel event to the first node we find with a renderer.
2476         // This is needed for <option> and <optgroup> elements so that <select>s get a wheel scroll.
2477         Node* startNode = this;
2478         while (startNode && !startNode->renderer())
2479             startNode = startNode->parentOrShadowHostNode();
2480         
2481         if (startNode && startNode->renderer())
2482             if (Frame* frame = document().frame())
2483                 frame->eventHandler().defaultWheelEventHandler(startNode, downcast<WheelEvent>(event));
2484 #if ENABLE(TOUCH_EVENTS) && PLATFORM(IOS)
2485     } else if (is<TouchEvent>(event) && eventNames().isTouchEventType(eventType)) {
2486         RenderObject* renderer = this->renderer();
2487         while (renderer && (!is<RenderBox>(*renderer) || !downcast<RenderBox>(*renderer).canBeScrolledAndHasScrollableArea()))
2488             renderer = renderer->parent();
2489
2490         if (renderer && renderer->node()) {
2491             if (Frame* frame = document().frame())
2492                 frame->eventHandler().defaultTouchEventHandler(*renderer->node(), downcast<TouchEvent>(event));
2493         }
2494 #endif
2495     }
2496 }
2497
2498 bool Node::willRespondToMouseMoveEvents()
2499 {
2500     // FIXME: Why is the iOS code path different from the non-iOS code path?
2501 #if !PLATFORM(IOS)
2502     if (!is<Element>(*this))
2503         return false;
2504     if (downcast<Element>(*this).isDisabledFormControl())
2505         return false;
2506 #endif
2507     return hasEventListeners(eventNames().mousemoveEvent) || hasEventListeners(eventNames().mouseoverEvent) || hasEventListeners(eventNames().mouseoutEvent);
2508 }
2509
2510 bool Node::willRespondToMouseClickEvents()
2511 {
2512     // FIXME: Why is the iOS code path different from the non-iOS code path?
2513 #if PLATFORM(IOS)
2514     return isContentEditable() || hasEventListeners(eventNames().mouseupEvent) || hasEventListeners(eventNames().mousedownEvent) || hasEventListeners(eventNames().clickEvent);
2515 #else
2516     if (!is<Element>(*this))
2517         return false;
2518     if (downcast<Element>(*this).isDisabledFormControl())
2519         return false;
2520     return computeEditability(UserSelectAllIsAlwaysNonEditable, ShouldUpdateStyle::Update) != Editability::ReadOnly
2521         || hasEventListeners(eventNames().mouseupEvent) || hasEventListeners(eventNames().mousedownEvent) || hasEventListeners(eventNames().clickEvent) || hasEventListeners(eventNames().DOMActivateEvent);
2522 #endif
2523 }
2524
2525 bool Node::willRespondToMouseWheelEvents()
2526 {
2527     return hasEventListeners(eventNames().mousewheelEvent);
2528 }
2529
2530 // It's important not to inline removedLastRef, because we don't want to inline the code to
2531 // delete a Node at each deref call site.
2532 void Node::removedLastRef()
2533 {
2534     // An explicit check for Document here is better than a virtual function since it is
2535     // faster for non-Document nodes, and because the call to removedLastRef that is inlined
2536     // at all deref call sites is smaller if it's a non-virtual function.
2537     if (is<Document>(*this)) {
2538         downcast<Document>(*this).removedLastRef();
2539         return;
2540     }
2541
2542 #ifndef NDEBUG
2543     m_deletionHasBegun = true;
2544 #endif
2545     delete this;
2546 }
2547
2548 void Node::textRects(Vector<IntRect>& rects) const
2549 {
2550     auto range = Range::create(document());
2551     range->selectNodeContents(const_cast<Node&>(*this));
2552     range->absoluteTextRects(rects);
2553 }
2554
2555 unsigned Node::connectedSubframeCount() const
2556 {
2557     return hasRareData() ? rareData()->connectedSubframeCount() : 0;
2558 }
2559
2560 void Node::incrementConnectedSubframeCount(unsigned amount)
2561 {
2562     ASSERT(isContainerNode());
2563     ensureRareData().incrementConnectedSubframeCount(amount);
2564 }
2565
2566 void Node::decrementConnectedSubframeCount(unsigned amount)
2567 {
2568     rareData()->decrementConnectedSubframeCount(amount);
2569 }
2570
2571 void Node::updateAncestorConnectedSubframeCountForRemoval() const
2572 {
2573     unsigned count = connectedSubframeCount();
2574
2575     if (!count)
2576         return;
2577
2578     for (Node* node = parentOrShadowHostNode(); node; node = node->parentOrShadowHostNode())
2579         node->decrementConnectedSubframeCount(count);
2580 }
2581
2582 void Node::updateAncestorConnectedSubframeCountForInsertion() const
2583 {
2584     unsigned count = connectedSubframeCount();
2585
2586     if (!count)
2587         return;
2588
2589     for (Node* node = parentOrShadowHostNode(); node; node = node->parentOrShadowHostNode())
2590         node->incrementConnectedSubframeCount(count);
2591 }
2592
2593 bool Node::inRenderedDocument() const
2594 {
2595     return isConnected() && document().hasLivingRenderTree();
2596 }
2597
2598 void* Node::opaqueRootSlow() const
2599 {
2600     const Node* node = this;
2601     for (;;) {
2602         const Node* nextNode = node->parentOrShadowHostNode();
2603         if (!nextNode)
2604             break;
2605         node = nextNode;
2606     }
2607     return const_cast<void*>(static_cast<const void*>(node));
2608 }
2609
2610 } // namespace WebCore
2611
2612 #if ENABLE(TREE_DEBUGGING)
2613
2614 void showTree(const WebCore::Node* node)
2615 {
2616     if (node)
2617         node->showTreeForThis();
2618 }
2619
2620 void showNodePath(const WebCore::Node* node)
2621 {
2622     if (node)
2623         node->showNodePathForThis();
2624 }
2625
2626 #endif // ENABLE(TREE_DEBUGGING)