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