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, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
7 *
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Library General Public
10 * License as published by the Free Software Foundation; either
11 * version 2 of the License, or (at your option) any later version.
12 *
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Library General Public License for more details.
17 *
18 * You should have received a copy of the GNU Library General Public License
19 * along with this library; see the file COPYING.LIB. If not, write to
20 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21 * Boston, MA 02110-1301, USA.
22 *
23 */
24
25#pragma once
26
27#include "EventTarget.h"
28#include "ExceptionOr.h"
29#include "LayoutRect.h"
30#include "MutationObserver.h"
31#include "RenderStyleConstants.h"
32#include "StyleValidity.h"
33#include "TreeScope.h"
34#include <wtf/Forward.h>
35#include <wtf/IsoMalloc.h>
36#include <wtf/ListHashSet.h>
37#include <wtf/MainThread.h>
38#include <wtf/URLHash.h>
39
40// This needs to be here because Document.h also depends on it.
41#define DUMP_NODE_STATISTICS 0
42
43namespace WebCore {
44
45class ContainerNode;
46class Document;
47class Element;
48class FloatPoint;
49class HTMLQualifiedName;
50class HTMLSlotElement;
51class MathMLQualifiedName;
52class NamedNodeMap;
53class NodeList;
54class NodeListsNodeData;
55class NodeRareData;
56class QualifiedName;
57class RenderBox;
58class RenderBoxModelObject;
59class RenderObject;
60class RenderStyle;
61class SVGQualifiedName;
62class ShadowRoot;
63class TouchEvent;
64
65using NodeOrString = Variant<RefPtr<Node>, String>;
66
67class NodeRareDataBase {
68public:
69 RenderObject* renderer() const { return m_renderer; }
70 void setRenderer(RenderObject* renderer) { m_renderer = renderer; }
71
72protected:
73 NodeRareDataBase(RenderObject* renderer)
74 : m_renderer(renderer)
75 { }
76
77private:
78 RenderObject* m_renderer;
79};
80
81class Node : public EventTarget {
82 WTF_MAKE_ISO_ALLOCATED(Node);
83
84 friend class Document;
85 friend class TreeScope;
86public:
87 enum NodeType {
88 ELEMENT_NODE = 1,
89 ATTRIBUTE_NODE = 2,
90 TEXT_NODE = 3,
91 CDATA_SECTION_NODE = 4,
92 PROCESSING_INSTRUCTION_NODE = 7,
93 COMMENT_NODE = 8,
94 DOCUMENT_NODE = 9,
95 DOCUMENT_TYPE_NODE = 10,
96 DOCUMENT_FRAGMENT_NODE = 11,
97 };
98 enum DeprecatedNodeType {
99 ENTITY_REFERENCE_NODE = 5,
100 ENTITY_NODE = 6,
101 NOTATION_NODE = 12,
102 };
103 enum DocumentPosition {
104 DOCUMENT_POSITION_EQUIVALENT = 0x00,
105 DOCUMENT_POSITION_DISCONNECTED = 0x01,
106 DOCUMENT_POSITION_PRECEDING = 0x02,
107 DOCUMENT_POSITION_FOLLOWING = 0x04,
108 DOCUMENT_POSITION_CONTAINS = 0x08,
109 DOCUMENT_POSITION_CONTAINED_BY = 0x10,
110 DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 0x20,
111 };
112
113 WEBCORE_EXPORT static void startIgnoringLeaks();
114 WEBCORE_EXPORT static void stopIgnoringLeaks();
115
116 static void dumpStatistics();
117
118 virtual ~Node();
119 void willBeDeletedFrom(Document&);
120
121 // DOM methods & attributes for Node
122
123 bool hasTagName(const HTMLQualifiedName&) const;
124 bool hasTagName(const MathMLQualifiedName&) const;
125 bool hasTagName(const SVGQualifiedName&) const;
126 virtual String nodeName() const = 0;
127 virtual String nodeValue() const;
128 virtual ExceptionOr<void> setNodeValue(const String&);
129 virtual NodeType nodeType() const = 0;
130 virtual size_t approximateMemoryCost() const { return sizeof(*this); }
131 ContainerNode* parentNode() const;
132 static ptrdiff_t parentNodeMemoryOffset() { return OBJECT_OFFSETOF(Node, m_parentNode); }
133 Element* parentElement() const;
134 Node* previousSibling() const { return m_previous; }
135 static ptrdiff_t previousSiblingMemoryOffset() { return OBJECT_OFFSETOF(Node, m_previous); }
136 Node* nextSibling() const { return m_next; }
137 static ptrdiff_t nextSiblingMemoryOffset() { return OBJECT_OFFSETOF(Node, m_next); }
138 WEBCORE_EXPORT RefPtr<NodeList> childNodes();
139 Node* firstChild() const;
140 Node* lastChild() const;
141 bool hasAttributes() const;
142 NamedNodeMap* attributes() const;
143 Node* pseudoAwareNextSibling() const;
144 Node* pseudoAwarePreviousSibling() const;
145 Node* pseudoAwareFirstChild() const;
146 Node* pseudoAwareLastChild() const;
147
148 WEBCORE_EXPORT const URL& baseURI() const;
149
150 void getSubresourceURLs(ListHashSet<URL>&) const;
151
152 WEBCORE_EXPORT ExceptionOr<void> insertBefore(Node& newChild, Node* refChild);
153 WEBCORE_EXPORT ExceptionOr<void> replaceChild(Node& newChild, Node& oldChild);
154 WEBCORE_EXPORT ExceptionOr<void> removeChild(Node& child);
155 WEBCORE_EXPORT ExceptionOr<void> appendChild(Node& newChild);
156
157 bool hasChildNodes() const { return firstChild(); }
158
159 enum class CloningOperation {
160 OnlySelf,
161 SelfWithTemplateContent,
162 Everything,
163 };
164 virtual Ref<Node> cloneNodeInternal(Document&, CloningOperation) = 0;
165 Ref<Node> cloneNode(bool deep) { return cloneNodeInternal(document(), deep ? CloningOperation::Everything : CloningOperation::OnlySelf); }
166 WEBCORE_EXPORT ExceptionOr<Ref<Node>> cloneNodeForBindings(bool deep);
167
168 virtual const AtomicString& localName() const;
169 virtual const AtomicString& namespaceURI() const;
170 virtual const AtomicString& prefix() const;
171 virtual ExceptionOr<void> setPrefix(const AtomicString&);
172 WEBCORE_EXPORT void normalize();
173
174 bool isSameNode(Node* other) const { return this == other; }
175 WEBCORE_EXPORT bool isEqualNode(Node*) const;
176 WEBCORE_EXPORT bool isDefaultNamespace(const AtomicString& namespaceURI) const;
177 WEBCORE_EXPORT const AtomicString& lookupPrefix(const AtomicString& namespaceURI) const;
178 WEBCORE_EXPORT const AtomicString& lookupNamespaceURI(const AtomicString& prefix) const;
179
180 WEBCORE_EXPORT String textContent(bool convertBRsToNewlines = false) const;
181 WEBCORE_EXPORT ExceptionOr<void> setTextContent(const String&);
182
183 Node* lastDescendant() const;
184 Node* firstDescendant() const;
185
186 // From the NonDocumentTypeChildNode - https://dom.spec.whatwg.org/#nondocumenttypechildnode
187 WEBCORE_EXPORT Element* previousElementSibling() const;
188 WEBCORE_EXPORT Element* nextElementSibling() const;
189
190 // From the ChildNode - https://dom.spec.whatwg.org/#childnode
191 ExceptionOr<void> before(Vector<NodeOrString>&&);
192 ExceptionOr<void> after(Vector<NodeOrString>&&);
193 ExceptionOr<void> replaceWith(Vector<NodeOrString>&&);
194 WEBCORE_EXPORT ExceptionOr<void> remove();
195
196 // Other methods (not part of DOM)
197
198 bool isElementNode() const { return getFlag(IsElementFlag); }
199 bool isContainerNode() const { return getFlag(IsContainerFlag); }
200 bool isTextNode() const { return getFlag(IsTextFlag); }
201 bool isHTMLElement() const { return getFlag(IsHTMLFlag); }
202 bool isSVGElement() const { return getFlag(IsSVGFlag); }
203 bool isMathMLElement() const { return getFlag(IsMathMLFlag); }
204
205 bool isPseudoElement() const { return pseudoId() != PseudoId::None; }
206 bool isBeforePseudoElement() const { return pseudoId() == PseudoId::Before; }
207 bool isAfterPseudoElement() const { return pseudoId() == PseudoId::After; }
208 PseudoId pseudoId() const { return (isElementNode() && hasCustomStyleResolveCallbacks()) ? customPseudoId() : PseudoId::None; }
209
210 virtual bool isMediaControlElement() const { return false; }
211 virtual bool isMediaControls() const { return false; }
212#if ENABLE(VIDEO_TRACK)
213 virtual bool isWebVTTElement() const { return false; }
214#endif
215 bool isStyledElement() const { return getFlag(IsHTMLFlag) || getFlag(IsSVGFlag) || getFlag(IsMathMLFlag); }
216 virtual bool isAttributeNode() const { return false; }
217 virtual bool isCharacterDataNode() const { return false; }
218 virtual bool isFrameOwnerElement() const { return false; }
219 virtual bool isPluginElement() const { return false; }
220#if ENABLE(SERVICE_CONTROLS)
221 virtual bool isImageControlsRootElement() const { return false; }
222 virtual bool isImageControlsButtonElement() const { return false; }
223#endif
224
225 bool isDocumentNode() const { return getFlag(IsDocumentNodeFlag); }
226 bool isTreeScope() const { return getFlag(IsDocumentNodeFlag) || getFlag(IsShadowRootFlag); }
227 bool isDocumentFragment() const { return getFlag(IsContainerFlag) && !(getFlag(IsElementFlag) || getFlag(IsDocumentNodeFlag)); }
228 bool isShadowRoot() const { return getFlag(IsShadowRootFlag); }
229
230 bool hasCustomStyleResolveCallbacks() const { return getFlag(HasCustomStyleResolveCallbacksFlag); }
231
232 bool hasSyntheticAttrChildNodes() const { return getFlag(HasSyntheticAttrChildNodesFlag); }
233 void setHasSyntheticAttrChildNodes(bool flag) { setFlag(flag, HasSyntheticAttrChildNodesFlag); }
234
235 // If this node is in a shadow tree, returns its shadow host. Otherwise, returns null.
236 WEBCORE_EXPORT Element* shadowHost() const;
237 ShadowRoot* containingShadowRoot() const;
238 ShadowRoot* shadowRoot() const;
239 bool isClosedShadowHidden(const Node&) const;
240
241 HTMLSlotElement* assignedSlot() const;
242 HTMLSlotElement* assignedSlotForBindings() const;
243
244 bool isUndefinedCustomElement() const { return isElementNode() && getFlag(IsEditingTextOrUndefinedCustomElementFlag); }
245 bool isCustomElementUpgradeCandidate() const { return getFlag(IsCustomElement) && getFlag(IsEditingTextOrUndefinedCustomElementFlag); }
246 bool isDefinedCustomElement() const { return getFlag(IsCustomElement) && !getFlag(IsEditingTextOrUndefinedCustomElementFlag); }
247 bool isFailedCustomElement() const { return isElementNode() && !getFlag(IsCustomElement) && getFlag(IsEditingTextOrUndefinedCustomElementFlag); }
248
249 // Returns null, a child of ShadowRoot, or a legacy shadow root.
250 Node* nonBoundaryShadowTreeRootNode();
251
252 // Node's parent or shadow tree host.
253 ContainerNode* parentOrShadowHostNode() const;
254 ContainerNode* parentInComposedTree() const;
255 Element* parentElementInComposedTree() const;
256 Element* parentOrShadowHostElement() const;
257 void setParentNode(ContainerNode*);
258 Node& rootNode() const;
259 Node& traverseToRootNode() const;
260 Node& shadowIncludingRoot() const;
261
262 struct GetRootNodeOptions {
263 bool composed;
264 };
265 Node& getRootNode(const GetRootNodeOptions&) const;
266
267 void* opaqueRoot() const;
268
269 // Use when it's guaranteed to that shadowHost is null.
270 ContainerNode* parentNodeGuaranteedHostFree() const;
271 // Returns the parent node, but null if the parent node is a ShadowRoot.
272 ContainerNode* nonShadowBoundaryParentNode() const;
273
274 bool selfOrAncestorHasDirAutoAttribute() const { return getFlag(SelfOrAncestorHasDirAutoFlag); }
275 void setSelfOrAncestorHasDirAutoAttribute(bool flag) { setFlag(flag, SelfOrAncestorHasDirAutoFlag); }
276
277 // Returns the enclosing event parent Element (or self) that, when clicked, would trigger a navigation.
278 Element* enclosingLinkEventParentOrSelf();
279
280 // These low-level calls give the caller responsibility for maintaining the integrity of the tree.
281 void setPreviousSibling(Node* previous) { m_previous = previous; }
282 void setNextSibling(Node* next) { m_next = next; }
283
284 virtual bool canContainRangeEndPoint() const { return false; }
285
286 WEBCORE_EXPORT bool isRootEditableElement() const;
287 WEBCORE_EXPORT Element* rootEditableElement() const;
288
289 // Called by the parser when this element's close tag is reached,
290 // signaling that all child tags have been parsed and added.
291 // This is needed for <applet> and <object> elements, which can't lay themselves out
292 // until they know all of their nested <param>s. [Radar 3603191, 4040848].
293 // Also used for script elements and some SVG elements for similar purposes,
294 // but making parsing a special case in this respect should be avoided if possible.
295 virtual void finishParsingChildren() { }
296 virtual void beginParsingChildren() { }
297
298 // For <link> and <style> elements.
299 virtual bool sheetLoaded() { return true; }
300 virtual void notifyLoadedSheetAndAllCriticalSubresources(bool /* error loading subresource */) { }
301 virtual void startLoadingDynamicSheet() { ASSERT_NOT_REACHED(); }
302
303 bool isUserActionElement() const { return getFlag(IsUserActionElement); }
304 void setUserActionElement(bool flag) { setFlag(flag, IsUserActionElement); }
305
306 bool inRenderedDocument() const;
307 bool needsStyleRecalc() const { return styleValidity() != Style::Validity::Valid; }
308 Style::Validity styleValidity() const;
309 bool styleResolutionShouldRecompositeLayer() const;
310 bool childNeedsStyleRecalc() const { return getFlag(ChildNeedsStyleRecalcFlag); }
311 bool styleIsAffectedByPreviousSibling() const { return getFlag(StyleIsAffectedByPreviousSibling); }
312 bool isEditingText() const { return getFlag(IsTextFlag) && getFlag(IsEditingTextOrUndefinedCustomElementFlag); }
313
314 void setChildNeedsStyleRecalc() { setFlag(ChildNeedsStyleRecalcFlag); }
315 void clearChildNeedsStyleRecalc() { m_nodeFlags &= ~(ChildNeedsStyleRecalcFlag | DirectChildNeedsStyleRecalcFlag); }
316
317 void setHasValidStyle();
318
319 bool isLink() const { return getFlag(IsLinkFlag); }
320 void setIsLink(bool flag) { setFlag(flag, IsLinkFlag); }
321
322 bool hasEventTargetData() const { return getFlag(HasEventTargetDataFlag); }
323 void setHasEventTargetData(bool flag) { setFlag(flag, HasEventTargetDataFlag); }
324
325 enum UserSelectAllTreatment {
326 UserSelectAllDoesNotAffectEditability,
327 UserSelectAllIsAlwaysNonEditable
328 };
329 WEBCORE_EXPORT bool isContentEditable();
330 bool isContentRichlyEditable();
331
332 WEBCORE_EXPORT void inspect();
333
334 bool hasEditableStyle(UserSelectAllTreatment treatment = UserSelectAllIsAlwaysNonEditable) const
335 {
336 return computeEditability(treatment, ShouldUpdateStyle::DoNotUpdate) != Editability::ReadOnly;
337 }
338 // FIXME: Replace every use of this function by helpers in Editing.h
339 bool hasRichlyEditableStyle() const
340 {
341 return computeEditability(UserSelectAllIsAlwaysNonEditable, ShouldUpdateStyle::DoNotUpdate) == Editability::CanEditRichly;
342 }
343
344 enum class Editability { ReadOnly, CanEditPlainText, CanEditRichly };
345 enum class ShouldUpdateStyle { Update, DoNotUpdate };
346 WEBCORE_EXPORT Editability computeEditability(UserSelectAllTreatment, ShouldUpdateStyle) const;
347
348 WEBCORE_EXPORT LayoutRect renderRect(bool* isReplaced);
349 IntRect pixelSnappedRenderRect(bool* isReplaced) { return snappedIntRect(renderRect(isReplaced)); }
350
351 WEBCORE_EXPORT unsigned computeNodeIndex() const;
352
353 // Returns the DOM ownerDocument attribute. This method never returns null, except in the case
354 // of a Document node.
355 WEBCORE_EXPORT Document* ownerDocument() const;
356
357 // Returns the document associated with this node.
358 // A Document node returns itself.
359 Document& document() const
360 {
361 return treeScope().documentScope();
362 }
363
364 TreeScope& treeScope() const
365 {
366 ASSERT(m_treeScope);
367 return *m_treeScope;
368 }
369 void setTreeScopeRecursively(TreeScope&);
370 static ptrdiff_t treeScopeMemoryOffset() { return OBJECT_OFFSETOF(Node, m_treeScope); }
371
372 // Returns true if this node is associated with a document and is in its associated document's
373 // node tree, false otherwise (https://dom.spec.whatwg.org/#connected).
374 bool isConnected() const
375 {
376 return getFlag(IsConnectedFlag);
377 }
378 bool isInUserAgentShadowTree() const;
379 bool isInShadowTree() const { return getFlag(IsInShadowTreeFlag); }
380 bool isInTreeScope() const { return getFlag(static_cast<NodeFlags>(IsConnectedFlag | IsInShadowTreeFlag)); }
381
382 bool isDocumentTypeNode() const { return nodeType() == DOCUMENT_TYPE_NODE; }
383 virtual bool childTypeAllowed(NodeType) const { return false; }
384 unsigned countChildNodes() const;
385 Node* traverseToChildAt(unsigned) const;
386
387 ExceptionOr<void> checkSetPrefix(const AtomicString& prefix);
388
389 WEBCORE_EXPORT bool isDescendantOf(const Node&) const;
390 bool isDescendantOf(const Node* other) const { return other && isDescendantOf(*other); }
391
392 bool isDescendantOrShadowDescendantOf(const Node*) const;
393 WEBCORE_EXPORT bool contains(const Node*) const;
394 bool containsIncludingShadowDOM(const Node*) const;
395
396 // Number of DOM 16-bit units contained in node. Note that rendered text length can be different - e.g. because of
397 // css-transform:capitalize breaking up precomposed characters and ligatures.
398 virtual int maxCharacterOffset() const;
399
400 // Whether or not a selection can be started in this object
401 virtual bool canStartSelection() const;
402
403 virtual bool shouldSelectOnMouseDown() { return false; }
404
405 // Getting points into and out of screen space
406 FloatPoint convertToPage(const FloatPoint&) const;
407 FloatPoint convertFromPage(const FloatPoint&) const;
408
409 // -----------------------------------------------------------------------------
410 // Integration with rendering tree
411
412 // As renderer() includes a branch you should avoid calling it repeatedly in hot code paths.
413 RenderObject* renderer() const { return hasRareData() ? m_data.m_rareData->renderer() : m_data.m_renderer; };
414 void setRenderer(RenderObject* renderer)
415 {
416 if (hasRareData())
417 m_data.m_rareData->setRenderer(renderer);
418 else
419 m_data.m_renderer = renderer;
420 }
421
422 // Use these two methods with caution.
423 WEBCORE_EXPORT RenderBox* renderBox() const;
424 RenderBoxModelObject* renderBoxModelObject() const;
425
426 // Wrapper for nodes that don't have a renderer, but still cache the style (like HTMLOptionElement).
427 const RenderStyle* renderStyle() const;
428
429 virtual const RenderStyle* computedStyle(PseudoId pseudoElementSpecifier = PseudoId::None);
430
431 enum class InsertedIntoAncestorResult {
432 Done,
433 NeedsPostInsertionCallback,
434 };
435
436 struct InsertionType {
437 bool connectedToDocument { false };
438 bool treeScopeChanged { false };
439 };
440 // Called *after* this node or its ancestor is inserted into a new parent (may or may not be a part of document) by scripts or parser.
441 // insertedInto **MUST NOT** invoke scripts. Return NeedsPostInsertionCallback and implement didFinishInsertingNode instead to run scripts.
442 virtual InsertedIntoAncestorResult insertedIntoAncestor(InsertionType, ContainerNode& parentOfInsertedTree);
443 virtual void didFinishInsertingNode() { }
444
445 struct RemovalType {
446 bool disconnectedFromDocument { false };
447 bool treeScopeChanged { false };
448 };
449 virtual void removedFromAncestor(RemovalType, ContainerNode& oldParentOfRemovedTree);
450
451#if ENABLE(TREE_DEBUGGING)
452 virtual void formatForDebugger(char* buffer, unsigned length) const;
453
454 void showNode(const char* prefix = "") const;
455 void showTreeForThis() const;
456 void showNodePathForThis() const;
457 void showTreeAndMark(const Node* markedNode1, const char* markedLabel1, const Node* markedNode2 = nullptr, const char* markedLabel2 = nullptr) const;
458 void showTreeForThisAcrossFrame() const;
459#endif // ENABLE(TREE_DEBUGGING)
460
461 void invalidateNodeListAndCollectionCachesInAncestors();
462 void invalidateNodeListAndCollectionCachesInAncestorsForAttribute(const QualifiedName& attrName);
463 NodeListsNodeData* nodeLists();
464 void clearNodeLists();
465
466 virtual bool willRespondToMouseMoveEvents();
467 virtual bool willRespondToMouseClickEvents();
468 virtual bool willRespondToMouseWheelEvents();
469
470 WEBCORE_EXPORT unsigned short compareDocumentPosition(Node&);
471
472 EventTargetInterface eventTargetInterface() const override;
473 ScriptExecutionContext* scriptExecutionContext() const final; // Implemented in Document.h
474
475 bool addEventListener(const AtomicString& eventType, Ref<EventListener>&&, const AddEventListenerOptions&) override;
476 bool removeEventListener(const AtomicString& eventType, EventListener&, const ListenerOptions&) override;
477
478 using EventTarget::dispatchEvent;
479 void dispatchEvent(Event&) override;
480
481 void dispatchScopedEvent(Event&);
482
483 virtual void handleLocalEvents(Event&, EventInvokePhase);
484
485 void dispatchSubtreeModifiedEvent();
486 void dispatchDOMActivateEvent(Event& underlyingClickEvent);
487
488#if ENABLE(TOUCH_EVENTS)
489 virtual bool allowsDoubleTapGesture() const { return true; }
490#endif
491
492 bool dispatchBeforeLoadEvent(const String& sourceURL);
493
494 WEBCORE_EXPORT void dispatchInputEvent();
495
496 // Perform the default action for an event.
497 virtual void defaultEventHandler(Event&);
498
499 void ref();
500 void deref();
501 bool hasOneRef() const;
502 unsigned refCount() const;
503
504#ifndef NDEBUG
505 bool m_deletionHasBegun { false };
506 bool m_inRemovedLastRefFunction { false };
507 bool m_adoptionIsRequired { true };
508#endif
509
510 EventTargetData* eventTargetData() final;
511 EventTargetData* eventTargetDataConcurrently() final;
512 EventTargetData& ensureEventTargetData() final;
513
514 HashMap<Ref<MutationObserver>, MutationRecordDeliveryOptions> registeredMutationObservers(MutationObserver::MutationType, const QualifiedName* attributeName);
515 void registerMutationObserver(MutationObserver&, MutationObserverOptions, const HashSet<AtomicString>& attributeFilter);
516 void unregisterMutationObserver(MutationObserverRegistration&);
517 void registerTransientMutationObserver(MutationObserverRegistration&);
518 void unregisterTransientMutationObserver(MutationObserverRegistration&);
519 void notifyMutationObserversNodeWillDetach();
520
521 WEBCORE_EXPORT void textRects(Vector<IntRect>&) const;
522
523 unsigned connectedSubframeCount() const;
524 void incrementConnectedSubframeCount(unsigned amount = 1);
525 void decrementConnectedSubframeCount(unsigned amount = 1);
526 void updateAncestorConnectedSubframeCountForRemoval() const;
527 void updateAncestorConnectedSubframeCountForInsertion() const;
528
529#if ENABLE(JIT)
530 static ptrdiff_t nodeFlagsMemoryOffset() { return OBJECT_OFFSETOF(Node, m_nodeFlags); }
531 static ptrdiff_t rareDataMemoryOffset() { return OBJECT_OFFSETOF(Node, m_data.m_rareData); }
532 static int32_t flagIsText() { return IsTextFlag; }
533 static int32_t flagIsContainer() { return IsContainerFlag; }
534 static int32_t flagIsElement() { return IsElementFlag; }
535 static int32_t flagIsShadowRoot() { return IsShadowRootFlag; }
536 static int32_t flagIsHTML() { return IsHTMLFlag; }
537 static int32_t flagIsLink() { return IsLinkFlag; }
538 static int32_t flagHasFocusWithin() { return HasFocusWithin; }
539 static int32_t flagHasRareData() { return HasRareDataFlag; }
540 static int32_t flagIsParsingChildrenFinished() { return IsParsingChildrenFinishedFlag; }
541 static int32_t flagChildrenAffectedByFirstChildRulesFlag() { return ChildrenAffectedByFirstChildRulesFlag; }
542 static int32_t flagChildrenAffectedByLastChildRulesFlag() { return ChildrenAffectedByLastChildRulesFlag; }
543
544 static int32_t flagAffectsNextSiblingElementStyle() { return AffectsNextSiblingElementStyle; }
545 static int32_t flagStyleIsAffectedByPreviousSibling() { return StyleIsAffectedByPreviousSibling; }
546#endif // ENABLE(JIT)
547
548protected:
549 enum NodeFlags {
550 IsTextFlag = 1,
551 IsContainerFlag = 1 << 1,
552 IsElementFlag = 1 << 2,
553 IsHTMLFlag = 1 << 3,
554 IsSVGFlag = 1 << 4,
555 IsMathMLFlag = 1 << 5,
556 IsDocumentNodeFlag = 1 << 6,
557 IsShadowRootFlag = 1 << 7,
558 IsConnectedFlag = 1 << 8,
559 IsInShadowTreeFlag = 1 << 9,
560 HasRareDataFlag = 1 << 10,
561 HasEventTargetDataFlag = 1 << 11,
562
563 // These bits are used by derived classes, pulled up here so they can
564 // be stored in the same memory word as the Node bits above.
565 ChildNeedsStyleRecalcFlag = 1 << 12, // ContainerNode
566 DirectChildNeedsStyleRecalcFlag = 1 << 13,
567
568 IsEditingTextOrUndefinedCustomElementFlag = 1 << 14, // Text and Element
569 IsCustomElement = 1 << 15, // Element
570 HasFocusWithin = 1 << 16,
571 IsLinkFlag = 1 << 17,
572 IsUserActionElement = 1 << 18,
573 IsParsingChildrenFinishedFlag = 1 << 19,
574 HasSyntheticAttrChildNodesFlag = 1 << 20,
575 SelfOrAncestorHasDirAutoFlag = 1 << 21,
576
577 // The following flags are used in style invalidation.
578 StyleValidityShift = 22,
579 StyleValidityMask = 3 << StyleValidityShift,
580 StyleResolutionShouldRecompositeLayerFlag = 1 << 24,
581
582 ChildrenAffectedByFirstChildRulesFlag = 1 << 25,
583 ChildrenAffectedByLastChildRulesFlag = 1 << 26,
584 ChildrenAffectedByHoverRulesFlag = 1 << 27,
585
586 AffectsNextSiblingElementStyle = 1 << 28,
587 StyleIsAffectedByPreviousSibling = 1 << 29,
588 DescendantsAffectedByPreviousSiblingFlag = 1 << 30,
589
590 HasCustomStyleResolveCallbacksFlag = 1 << 31,
591
592 DefaultNodeFlags = IsParsingChildrenFinishedFlag
593 };
594
595 bool getFlag(NodeFlags mask) const { return m_nodeFlags & mask; }
596 void setFlag(bool f, NodeFlags mask) const { m_nodeFlags = (m_nodeFlags & ~mask) | (-(int32_t)f & mask); }
597 void setFlag(NodeFlags mask) const { m_nodeFlags |= mask; }
598 void clearFlag(NodeFlags mask) const { m_nodeFlags &= ~mask; }
599
600 bool isParsingChildrenFinished() const { return getFlag(IsParsingChildrenFinishedFlag); }
601 void setIsParsingChildrenFinished() { setFlag(IsParsingChildrenFinishedFlag); }
602 void clearIsParsingChildrenFinished() { clearFlag(IsParsingChildrenFinishedFlag); }
603
604 enum ConstructionType {
605 CreateOther = DefaultNodeFlags,
606 CreateText = DefaultNodeFlags | IsTextFlag,
607 CreateContainer = DefaultNodeFlags | IsContainerFlag,
608 CreateElement = CreateContainer | IsElementFlag,
609 CreatePseudoElement = CreateElement | IsConnectedFlag,
610 CreateShadowRoot = CreateContainer | IsShadowRootFlag | IsInShadowTreeFlag,
611 CreateDocumentFragment = CreateContainer,
612 CreateHTMLElement = CreateElement | IsHTMLFlag,
613 CreateSVGElement = CreateElement | IsSVGFlag | HasCustomStyleResolveCallbacksFlag,
614 CreateMathMLElement = CreateElement | IsMathMLFlag,
615 CreateDocument = CreateContainer | IsDocumentNodeFlag | IsConnectedFlag,
616 CreateEditingText = CreateText | IsEditingTextOrUndefinedCustomElementFlag,
617 };
618 Node(Document&, ConstructionType);
619
620 static constexpr uint32_t s_refCountIncrement = 2;
621 static constexpr uint32_t s_refCountMask = ~static_cast<uint32_t>(1);
622
623 virtual void addSubresourceAttributeURLs(ListHashSet<URL>&) const { }
624
625 bool hasRareData() const { return getFlag(HasRareDataFlag); }
626
627 NodeRareData* rareData() const;
628 NodeRareData& ensureRareData();
629 void clearRareData();
630
631 void clearEventTargetData();
632
633 void setHasCustomStyleResolveCallbacks() { setFlag(true, HasCustomStyleResolveCallbacksFlag); }
634
635 void setTreeScope(TreeScope& scope) { m_treeScope = &scope; }
636
637 void invalidateStyle(Style::Validity, Style::InvalidationMode = Style::InvalidationMode::Normal);
638 void updateAncestorsForStyleRecalc();
639
640 ExceptionOr<RefPtr<Node>> convertNodesOrStringsIntoNode(Vector<NodeOrString>&&);
641
642private:
643 virtual PseudoId customPseudoId() const
644 {
645 ASSERT(hasCustomStyleResolveCallbacks());
646 return PseudoId::None;
647 }
648
649 WEBCORE_EXPORT void removedLastRef();
650
651 void refEventTarget() final;
652 void derefEventTarget() final;
653 bool isNode() const final;
654
655 void trackForDebugging();
656 void materializeRareData();
657
658 Vector<std::unique_ptr<MutationObserverRegistration>>* mutationObserverRegistry();
659 HashSet<MutationObserverRegistration*>* transientMutationObserverRegistry();
660
661 void adjustStyleValidity(Style::Validity, Style::InvalidationMode);
662
663 void* opaqueRootSlow() const;
664
665 static void moveShadowTreeToNewDocument(ShadowRoot&, Document& oldDocument, Document& newDocument);
666 static void moveTreeToNewScope(Node&, TreeScope& oldScope, TreeScope& newScope);
667 void moveNodeToNewDocument(Document& oldDocument, Document& newDocument);
668
669 uint32_t m_refCountAndParentBit { s_refCountIncrement };
670 mutable uint32_t m_nodeFlags;
671
672 ContainerNode* m_parentNode { nullptr };
673 TreeScope* m_treeScope { nullptr };
674 Node* m_previous { nullptr };
675 Node* m_next { nullptr };
676 // When a node has rare data we move the renderer into the rare data.
677 union DataUnion {
678 RenderObject* m_renderer;
679 NodeRareDataBase* m_rareData;
680 } m_data { nullptr };
681};
682
683#ifndef NDEBUG
684inline void adopted(Node* node)
685{
686 if (!node)
687 return;
688 ASSERT(!node->m_deletionHasBegun);
689 ASSERT(!node->m_inRemovedLastRefFunction);
690 node->m_adoptionIsRequired = false;
691}
692#endif
693
694ALWAYS_INLINE void Node::ref()
695{
696 ASSERT(isMainThread());
697 ASSERT(!m_deletionHasBegun);
698 ASSERT(!m_inRemovedLastRefFunction);
699 ASSERT(!m_adoptionIsRequired);
700 m_refCountAndParentBit += s_refCountIncrement;
701}
702
703ALWAYS_INLINE void Node::deref()
704{
705 ASSERT(isMainThread());
706 ASSERT(refCount());
707 ASSERT(!m_deletionHasBegun);
708 ASSERT(!m_inRemovedLastRefFunction);
709 ASSERT(!m_adoptionIsRequired);
710 auto updatedRefCount = m_refCountAndParentBit - s_refCountIncrement;
711 if (!updatedRefCount) {
712 // Don't update m_refCountAndParentBit to avoid double destruction through use of Ref<T>/RefPtr<T>.
713 // (This is a security mitigation in case of programmer error. It will ASSERT in debug builds.)
714#ifndef NDEBUG
715 m_inRemovedLastRefFunction = true;
716#endif
717 removedLastRef();
718 return;
719 }
720 m_refCountAndParentBit = updatedRefCount;
721}
722
723ALWAYS_INLINE bool Node::hasOneRef() const
724{
725 ASSERT(!m_deletionHasBegun);
726 ASSERT(!m_inRemovedLastRefFunction);
727 return refCount() == 1;
728}
729
730ALWAYS_INLINE unsigned Node::refCount() const
731{
732 return m_refCountAndParentBit / s_refCountIncrement;
733}
734
735// Used in Node::addSubresourceAttributeURLs() and in addSubresourceStyleURLs()
736inline void addSubresourceURL(ListHashSet<URL>& urls, const URL& url)
737{
738 if (!url.isNull())
739 urls.add(url);
740}
741
742inline void Node::setParentNode(ContainerNode* parent)
743{
744 ASSERT(isMainThread());
745 m_parentNode = parent;
746 m_refCountAndParentBit = (m_refCountAndParentBit & s_refCountMask) | !!parent;
747}
748
749inline ContainerNode* Node::parentNode() const
750{
751 ASSERT(isMainThreadOrGCThread());
752 return m_parentNode;
753}
754
755inline void* Node::opaqueRoot() const
756{
757 // FIXME: Possible race?
758 // https://bugs.webkit.org/show_bug.cgi?id=165713
759 if (isConnected())
760 return &document();
761 return opaqueRootSlow();
762}
763
764inline ContainerNode* Node::parentNodeGuaranteedHostFree() const
765{
766 ASSERT(!isShadowRoot());
767 return parentNode();
768}
769
770inline Style::Validity Node::styleValidity() const
771{
772 return static_cast<Style::Validity>((m_nodeFlags & StyleValidityMask) >> StyleValidityShift);
773}
774
775inline bool Node::styleResolutionShouldRecompositeLayer() const
776{
777 return getFlag(StyleResolutionShouldRecompositeLayerFlag);
778}
779
780inline void Node::setHasValidStyle()
781{
782 m_nodeFlags &= ~StyleValidityMask;
783 clearFlag(StyleResolutionShouldRecompositeLayerFlag);
784}
785
786inline void Node::setTreeScopeRecursively(TreeScope& newTreeScope)
787{
788 ASSERT(!isDocumentNode());
789 ASSERT(!m_deletionHasBegun);
790 if (m_treeScope != &newTreeScope)
791 moveTreeToNewScope(*this, *m_treeScope, newTreeScope);
792}
793
794} // namespace WebCore
795
796#if ENABLE(TREE_DEBUGGING)
797// Outside the WebCore namespace for ease of invocation from the debugger.
798void showTree(const WebCore::Node*);
799void showNodePath(const WebCore::Node*);
800#endif
801
802SPECIALIZE_TYPE_TRAITS_BEGIN(WebCore::Node)
803 static bool isType(const WebCore::EventTarget& target) { return target.isNode(); }
804SPECIALIZE_TYPE_TRAITS_END()
805