1/*
2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * (C) 1999 Antti Koivisto (koivisto@kde.org)
4 * (C) 2001 Dirk Mueller (mueller@kde.org)
5 * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 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#ifndef Node_h
26#define Node_h
27
28#include "EventTarget.h"
29#include "URLHash.h"
30#include "LayoutRect.h"
31#include "MutationObserver.h"
32#include "RenderStyleConstants.h"
33#include "TreeScope.h"
34#include <wtf/Forward.h>
35#include <wtf/ListHashSet.h>
36#include <wtf/MainThread.h>
37#include <wtf/TypeCasts.h>
38
39// This needs to be here because Document.h also depends on it.
40#define DUMP_NODE_STATISTICS 0
41
42namespace WebCore {
43
44class Attribute;
45class ClassCollection;
46class ContainerNode;
47class DOMTokenList;
48class Document;
49class Element;
50class Event;
51class EventListener;
52class FloatPoint;
53class Frame;
54class HTMLInputElement;
55class HTMLQualifiedName;
56class HTMLSlotElement;
57class IntRect;
58class KeyboardEvent;
59class MathMLQualifiedName;
60class NSResolver;
61class NameNodeList;
62class NamedNodeMap;
63class NodeList;
64class NodeListsNodeData;
65class NodeOrString;
66class NodeRareData;
67class QualifiedName;
68class RadioNodeList;
69class RegisteredEventListener;
70class RenderBox;
71class RenderBoxModelObject;
72class RenderObject;
73class RenderStyle;
74class SVGQualifiedName;
75class ShadowRoot;
76class TagCollection;
77
78#if ENABLE(QT_GESTURE_EVENTS)
79class PlatformGestureEvent;
80#endif
81
82#if ENABLE(INDIE_UI)
83class UIRequestEvent;
84#endif
85
86#if ENABLE(TOUCH_EVENTS) && !PLATFORM(IOS)
87class TouchEvent;
88#endif
89
90typedef int ExceptionCode;
91
92const int nodeStyleChangeShift = 14;
93
94// SyntheticStyleChange means that we need to go through the entire style change logic even though
95// no style property has actually changed. It is used to restructure the tree when, for instance,
96// RenderLayers are created or destroyed due to animation changes.
97enum StyleChangeType {
98 NoStyleChange = 0,
99 InlineStyleChange = 1 << nodeStyleChangeShift,
100 FullStyleChange = 2 << nodeStyleChangeShift,
101 SyntheticStyleChange = 3 << nodeStyleChangeShift,
102 ReconstructRenderTree = 4 << nodeStyleChangeShift,
103};
104
105class NodeRareDataBase {
106public:
107 RenderObject* renderer() const { return m_renderer; }
108 void setRenderer(RenderObject* renderer) { m_renderer = renderer; }
109
110protected:
111 NodeRareDataBase(RenderObject* renderer)
112 : m_renderer(renderer)
113 { }
114
115private:
116 RenderObject* m_renderer;
117};
118
119class Node : public EventTarget {
120 WTF_MAKE_FAST_ALLOCATED;
121
122 friend class Document;
123 friend class TreeScope;
124 friend class TreeScopeAdopter;
125public:
126 enum NodeType {
127 ELEMENT_NODE = 1,
128 ATTRIBUTE_NODE = 2,
129 TEXT_NODE = 3,
130 CDATA_SECTION_NODE = 4,
131 PROCESSING_INSTRUCTION_NODE = 7,
132 COMMENT_NODE = 8,
133 DOCUMENT_NODE = 9,
134 DOCUMENT_TYPE_NODE = 10,
135 DOCUMENT_FRAGMENT_NODE = 11,
136 };
137 enum DeprecatedNodeType {
138 ENTITY_REFERENCE_NODE = 5,
139 ENTITY_NODE = 6,
140 NOTATION_NODE = 12,
141 };
142 enum DocumentPosition {
143 DOCUMENT_POSITION_EQUIVALENT = 0x00,
144 DOCUMENT_POSITION_DISCONNECTED = 0x01,
145 DOCUMENT_POSITION_PRECEDING = 0x02,
146 DOCUMENT_POSITION_FOLLOWING = 0x04,
147 DOCUMENT_POSITION_CONTAINS = 0x08,
148 DOCUMENT_POSITION_CONTAINED_BY = 0x10,
149 DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 0x20,
150 };
151
152 // Only used by ObjC / GObject bindings.
153 static bool isSupportedForBindings(const String& feature, const String& version);
154
155 WEBCORE_EXPORT static void startIgnoringLeaks();
156 WEBCORE_EXPORT static void stopIgnoringLeaks();
157
158 static void dumpStatistics();
159
160 virtual ~Node();
161 void willBeDeletedFrom(Document&);
162
163 // DOM methods & attributes for Node
164
165 bool hasTagName(const HTMLQualifiedName&) const;
166 bool hasTagName(const MathMLQualifiedName&) const;
167 bool hasTagName(const SVGQualifiedName&) const;
168 virtual String nodeName() const = 0;
169 virtual String nodeValue() const;
170 virtual void setNodeValue(const String&, ExceptionCode&);
171 virtual NodeType nodeType() const = 0;
172 ContainerNode* parentNode() const;
173 static ptrdiff_t parentNodeMemoryOffset() { return OBJECT_OFFSETOF(Node, m_parentNode); }
174 Element* parentElement() const;
175 Node* previousSibling() const { return m_previous; }
176 static ptrdiff_t previousSiblingMemoryOffset() { return OBJECT_OFFSETOF(Node, m_previous); }
177 Node* nextSibling() const { return m_next; }
178 static ptrdiff_t nextSiblingMemoryOffset() { return OBJECT_OFFSETOF(Node, m_next); }
179 RefPtr<NodeList> childNodes();
180 Node* firstChild() const;
181 Node* lastChild() const;
182 bool hasAttributes() const;
183 NamedNodeMap* attributes() const;
184 Node* pseudoAwareNextSibling() const;
185 Node* pseudoAwarePreviousSibling() const;
186 Node* pseudoAwareFirstChild() const;
187 Node* pseudoAwareLastChild() const;
188
189 URL baseURI() const;
190
191 void getSubresourceURLs(ListHashSet<URL>&) const;
192
193 // These should all actually return a node, but this is only important for language bindings,
194 // which will already know and hold a ref on the right node to return. Returning bool allows
195 // these methods to be more efficient since they don't need to return a ref
196 WEBCORE_EXPORT bool insertBefore(PassRefPtr<Node> newChild, Node* refChild, ExceptionCode&);
197 bool replaceChild(PassRefPtr<Node> newChild, Node* oldChild, ExceptionCode&);
198 WEBCORE_EXPORT bool removeChild(Node* child, ExceptionCode&);
199 WEBCORE_EXPORT bool appendChild(PassRefPtr<Node> newChild, ExceptionCode&);
200
201 bool hasChildNodes() const { return firstChild(); }
202
203 enum class CloningOperation {
204 OnlySelf,
205 SelfWithTemplateContent,
206 Everything,
207 };
208 virtual Ref<Node> cloneNodeInternal(Document&, CloningOperation) = 0;
209 Ref<Node> cloneNode(bool deep) { return cloneNodeInternal(document(), deep ? CloningOperation::Everything : CloningOperation::OnlySelf); }
210
211 virtual const AtomicString& localName() const;
212 virtual const AtomicString& namespaceURI() const;
213 virtual const AtomicString& prefix() const;
214 virtual void setPrefix(const AtomicString&, ExceptionCode&);
215 void normalize();
216
217 bool isSameNode(Node* other) const { return this == other; }
218 bool isEqualNode(Node*) const;
219 bool isDefaultNamespace(const AtomicString& namespaceURI) const;
220 String lookupPrefix(const AtomicString& namespaceURI) const;
221 String lookupNamespaceURI(const String& prefix) const;
222 String lookupNamespacePrefix(const AtomicString& namespaceURI, const Element* originalElement) const;
223
224 WEBCORE_EXPORT String textContent(bool convertBRsToNewlines = false) const;
225 WEBCORE_EXPORT void setTextContent(const String&, ExceptionCode&);
226
227 Node* lastDescendant() const;
228 Node* firstDescendant() const;
229
230 // From the NonDocumentTypeChildNode - https://dom.spec.whatwg.org/#nondocumenttypechildnode
231 Element* previousElementSibling() const;
232 Element* nextElementSibling() const;
233
234 // From the ChildNode - https://dom.spec.whatwg.org/#childnode
235 void before(Vector<NodeOrString>&&, ExceptionCode&);
236 void after(Vector<NodeOrString>&&, ExceptionCode&);
237 void replaceWith(Vector<NodeOrString>&&, ExceptionCode&);
238 WEBCORE_EXPORT void remove(ExceptionCode&);
239
240 // Other methods (not part of DOM)
241
242 bool isElementNode() const { return getFlag(IsElementFlag); }
243 bool isContainerNode() const { return getFlag(IsContainerFlag); }
244 bool isTextNode() const { return getFlag(IsTextFlag); }
245 bool isHTMLElement() const { return getFlag(IsHTMLFlag); }
246 bool isSVGElement() const { return getFlag(IsSVGFlag); }
247 bool isMathMLElement() const { return getFlag(IsMathMLFlag); }
248
249 bool isPseudoElement() const { return pseudoId() != NOPSEUDO; }
250 bool isBeforePseudoElement() const { return pseudoId() == BEFORE; }
251 bool isAfterPseudoElement() const { return pseudoId() == AFTER; }
252 PseudoId pseudoId() const { return (isElementNode() && hasCustomStyleResolveCallbacks()) ? customPseudoId() : NOPSEUDO; }
253
254 virtual bool isMediaControlElement() const { return false; }
255 virtual bool isMediaControls() const { return false; }
256#if ENABLE(VIDEO_TRACK)
257 virtual bool isWebVTTElement() const { return false; }
258#endif
259 bool isStyledElement() const { return getFlag(IsStyledElementFlag); }
260 virtual bool isAttributeNode() const { return false; }
261 virtual bool isCharacterDataNode() const { return false; }
262 virtual bool isFrameOwnerElement() const { return false; }
263 virtual bool isPluginElement() const { return false; }
264#if ENABLE(SERVICE_CONTROLS)
265 virtual bool isImageControlsRootElement() const { return false; }
266 virtual bool isImageControlsButtonElement() const { return false; }
267#endif
268
269 bool isDocumentNode() const;
270 bool isTreeScope() const;
271 bool isDocumentFragment() const { return getFlag(IsDocumentFragmentFlag); }
272 bool isShadowRoot() const { return isDocumentFragment() && isTreeScope(); }
273
274 bool isNamedFlowContentNode() const { return getFlag(IsNamedFlowContentNodeFlag); }
275 bool hasCustomStyleResolveCallbacks() const { return getFlag(HasCustomStyleResolveCallbacksFlag); }
276
277 bool hasSyntheticAttrChildNodes() const { return getFlag(HasSyntheticAttrChildNodesFlag); }
278 void setHasSyntheticAttrChildNodes(bool flag) { setFlag(flag, HasSyntheticAttrChildNodesFlag); }
279
280 // If this node is in a shadow tree, returns its shadow host. Otherwise, returns null.
281 WEBCORE_EXPORT Element* shadowHost() const;
282 // If this node is in a shadow tree, returns its shadow host. Otherwise, returns this.
283 // Deprecated. Should use shadowHost() and check the return value.
284 WEBCORE_EXPORT Node* deprecatedShadowAncestorNode() const;
285 ShadowRoot* containingShadowRoot() const;
286 ShadowRoot* shadowRoot() const;
287
288#if ENABLE(SHADOW_DOM)
289 HTMLSlotElement* assignedSlot() const;
290#endif
291
292#if ENABLE(CUSTOM_ELEMENTS)
293 bool isCustomElement() const { return getFlag(IsCustomElement); }
294 void setIsCustomElement() { return setFlag(IsCustomElement); }
295#endif
296
297 // Returns null, a child of ShadowRoot, or a legacy shadow root.
298 Node* nonBoundaryShadowTreeRootNode();
299
300 // Node's parent or shadow tree host.
301 ContainerNode* parentOrShadowHostNode() const;
302 ContainerNode* parentInComposedTree() const;
303 Element* parentOrShadowHostElement() const;
304 void setParentNode(ContainerNode*);
305 Node* highestAncestor() const;
306
307 // Use when it's guaranteed to that shadowHost is null.
308 ContainerNode* parentNodeGuaranteedHostFree() const;
309 // Returns the parent node, but null if the parent node is a ShadowRoot.
310 ContainerNode* nonShadowBoundaryParentNode() const;
311
312 bool selfOrAncestorHasDirAutoAttribute() const { return getFlag(SelfOrAncestorHasDirAutoFlag); }
313 void setSelfOrAncestorHasDirAutoAttribute(bool flag) { setFlag(flag, SelfOrAncestorHasDirAutoFlag); }
314
315 // Returns the enclosing event parent Element (or self) that, when clicked, would trigger a navigation.
316 Element* enclosingLinkEventParentOrSelf();
317
318 // These low-level calls give the caller responsibility for maintaining the integrity of the tree.
319 void setPreviousSibling(Node* previous) { m_previous = previous; }
320 void setNextSibling(Node* next) { m_next = next; }
321
322 virtual bool canContainRangeEndPoint() const { return false; }
323
324 bool isRootEditableElement() const;
325 WEBCORE_EXPORT Element* rootEditableElement() const;
326
327 // Called by the parser when this element's close tag is reached,
328 // signaling that all child tags have been parsed and added.
329 // This is needed for <applet> and <object> elements, which can't lay themselves out
330 // until they know all of their nested <param>s. [Radar 3603191, 4040848].
331 // Also used for script elements and some SVG elements for similar purposes,
332 // but making parsing a special case in this respect should be avoided if possible.
333 virtual void finishParsingChildren() { }
334 virtual void beginParsingChildren() { }
335
336 // For <link> and <style> elements.
337 virtual bool sheetLoaded() { return true; }
338 virtual void notifyLoadedSheetAndAllCriticalSubresources(bool /* error loading subresource */) { }
339 virtual void startLoadingDynamicSheet() { ASSERT_NOT_REACHED(); }
340
341 bool isUserActionElement() const { return getFlag(IsUserActionElement); }
342 void setUserActionElement(bool flag) { setFlag(flag, IsUserActionElement); }
343
344 bool inRenderedDocument() const;
345 bool needsStyleRecalc() const { return styleChangeType() != NoStyleChange; }
346 StyleChangeType styleChangeType() const { return static_cast<StyleChangeType>(m_nodeFlags & StyleChangeMask); }
347 bool childNeedsStyleRecalc() const { return getFlag(ChildNeedsStyleRecalcFlag); }
348 bool styleIsAffectedByPreviousSibling() const { return getFlag(StyleIsAffectedByPreviousSibling); }
349 bool isEditingText() const { return getFlag(IsEditingTextFlag); }
350
351 void setChildNeedsStyleRecalc() { setFlag(ChildNeedsStyleRecalcFlag); }
352 void clearChildNeedsStyleRecalc() { m_nodeFlags &= ~(ChildNeedsStyleRecalcFlag | DirectChildNeedsStyleRecalcFlag); }
353
354 WEBCORE_EXPORT void setNeedsStyleRecalc(StyleChangeType = FullStyleChange);
355 void clearNeedsStyleRecalc() { m_nodeFlags &= ~StyleChangeMask; }
356
357 bool isLink() const { return getFlag(IsLinkFlag); }
358 void setIsLink(bool flag) { setFlag(flag, IsLinkFlag); }
359
360 void setIsNamedFlowContentNode() { setFlag(IsNamedFlowContentNodeFlag); }
361 void clearIsNamedFlowContentNode() { clearFlag(IsNamedFlowContentNodeFlag); }
362
363 bool hasEventTargetData() const { return getFlag(HasEventTargetDataFlag); }
364 void setHasEventTargetData(bool flag) { setFlag(flag, HasEventTargetDataFlag); }
365
366 enum UserSelectAllTreatment {
367 UserSelectAllDoesNotAffectEditability,
368 UserSelectAllIsAlwaysNonEditable
369 };
370 WEBCORE_EXPORT bool isContentEditable();
371 bool isContentRichlyEditable();
372
373 WEBCORE_EXPORT void inspect();
374
375 bool hasEditableStyle(UserSelectAllTreatment treatment = UserSelectAllIsAlwaysNonEditable) const
376 {
377 return computeEditability(treatment, ShouldUpdateStyle::DoNotUpdate) != Editability::ReadOnly;
378 }
379 // FIXME: Replace every use of this function by helpers in htmlediting.h
380 bool hasRichlyEditableStyle() const
381 {
382 return computeEditability(UserSelectAllIsAlwaysNonEditable, ShouldUpdateStyle::DoNotUpdate) == Editability::CanEditRichly;
383 }
384
385 enum class Editability { ReadOnly, CanEditPlainText, CanEditRichly };
386 enum class ShouldUpdateStyle { Update, DoNotUpdate };
387 WEBCORE_EXPORT Editability computeEditability(UserSelectAllTreatment, ShouldUpdateStyle) const;
388
389 WEBCORE_EXPORT LayoutRect renderRect(bool* isReplaced);
390 IntRect pixelSnappedRenderRect(bool* isReplaced) { return snappedIntRect(renderRect(isReplaced)); }
391
392 WEBCORE_EXPORT unsigned computeNodeIndex() const;
393
394 // Returns the DOM ownerDocument attribute. This method never returns null, except in the case
395 // of a Document node.
396 WEBCORE_EXPORT Document* ownerDocument() const;
397
398 // Returns the document associated with this node.
399 // A Document node returns itself.
400 Document& document() const
401 {
402 return treeScope().documentScope();
403 }
404
405 TreeScope& treeScope() const
406 {
407 ASSERT(m_treeScope);
408 return *m_treeScope;
409 }
410 static ptrdiff_t treeScopeMemoryOffset() { return OBJECT_OFFSETOF(Node, m_treeScope); }
411
412 // Returns true if this node is associated with a document and is in its associated document's
413 // node tree, false otherwise.
414 bool inDocument() const
415 {
416 return getFlag(InDocumentFlag);
417 }
418 bool isInUserAgentShadowTree() const;
419 bool isInShadowTree() const { return getFlag(IsInShadowTreeFlag); }
420 bool isInTreeScope() const { return getFlag(static_cast<NodeFlags>(InDocumentFlag | IsInShadowTreeFlag)); }
421
422 bool isDocumentTypeNode() const { return nodeType() == DOCUMENT_TYPE_NODE; }
423 virtual bool childTypeAllowed(NodeType) const { return false; }
424 unsigned countChildNodes() const;
425 Node* traverseToChildAt(unsigned) const;
426
427 void checkSetPrefix(const AtomicString& prefix, ExceptionCode&);
428
429 WEBCORE_EXPORT bool isDescendantOf(const Node*) const;
430 bool isDescendantOrShadowDescendantOf(const Node*) const;
431 bool contains(const Node*) const;
432 bool containsIncludingShadowDOM(const Node*) const;
433 bool containsIncludingHostElements(const Node*) const;
434
435 // Used to determine whether range offsets use characters or node indices.
436 virtual bool offsetInCharacters() const;
437 // Number of DOM 16-bit units contained in node. Note that rendered text length can be different - e.g. because of
438 // css-transform:capitalize breaking up precomposed characters and ligatures.
439 virtual int maxCharacterOffset() const;
440
441 // Whether or not a selection can be started in this object
442 virtual bool canStartSelection() const;
443
444 virtual bool shouldSelectOnMouseDown() { return false; }
445
446 // Getting points into and out of screen space
447 FloatPoint convertToPage(const FloatPoint&) const;
448 FloatPoint convertFromPage(const FloatPoint&) const;
449
450 // -----------------------------------------------------------------------------
451 // Integration with rendering tree
452
453 // As renderer() includes a branch you should avoid calling it repeatedly in hot code paths.
454 RenderObject* renderer() const { return hasRareData() ? m_data.m_rareData->renderer() : m_data.m_renderer; };
455 void setRenderer(RenderObject* renderer)
456 {
457 if (hasRareData())
458 m_data.m_rareData->setRenderer(renderer);
459 else
460 m_data.m_renderer = renderer;
461 }
462
463 // Use these two methods with caution.
464 WEBCORE_EXPORT RenderBox* renderBox() const;
465 RenderBoxModelObject* renderBoxModelObject() const;
466
467 // Wrapper for nodes that don't have a renderer, but still cache the style (like HTMLOptionElement).
468 RenderStyle* renderStyle() const;
469
470 virtual RenderStyle* computedStyle(PseudoId pseudoElementSpecifier = NOPSEUDO);
471
472 // -----------------------------------------------------------------------------
473 // Notification of document structure changes (see ContainerNode.h for more notification methods)
474 //
475 // At first, WebKit notifies the node that it has been inserted into the document. This is called during document parsing, and also
476 // when a node is added through the DOM methods insertBefore(), appendChild() or replaceChild(). The call happens _after_ the node has been added to the tree.
477 // This is similar to the DOMNodeInsertedIntoDocument DOM event, but does not require the overhead of event
478 // dispatching.
479 //
480 // WebKit notifies this callback regardless if the subtree of the node is a document tree or a floating subtree.
481 // Implementation can determine the type of subtree by seeing insertionPoint->inDocument().
482 // For a performance reason, notifications are delivered only to ContainerNode subclasses if the insertionPoint is out of document.
483 //
484 // There is another callback named finishedInsertingSubtree(), which is called after all descendants are notified.
485 // Only a few subclasses actually need this. To utilize this, the node should return InsertionShouldCallFinishedInsertingSubtree
486 // from insrtedInto().
487 //
488 enum InsertionNotificationRequest {
489 InsertionDone,
490 InsertionShouldCallFinishedInsertingSubtree
491 };
492
493 virtual InsertionNotificationRequest insertedInto(ContainerNode& insertionPoint);
494 virtual void finishedInsertingSubtree() { }
495
496 // Notifies the node that it is no longer part of the tree.
497 //
498 // This is a dual of insertedInto(), and is similar to the DOMNodeRemovedFromDocument DOM event, but does not require the overhead of event
499 // dispatching, and is called _after_ the node is removed from the tree.
500 //
501 virtual void removedFrom(ContainerNode& insertionPoint);
502
503#if ENABLE(TREE_DEBUGGING)
504 virtual void formatForDebugger(char* buffer, unsigned length) const;
505
506 void showNode(const char* prefix = "") const;
507 void showTreeForThis() const;
508 void showNodePathForThis() const;
509 void showTreeAndMark(const Node* markedNode1, const char* markedLabel1, const Node* markedNode2 = nullptr, const char* markedLabel2 = nullptr) const;
510 void showTreeForThisAcrossFrame() const;
511#endif // ENABLE(TREE_DEBUGGING)
512
513 void invalidateNodeListAndCollectionCachesInAncestors(const QualifiedName* attrName = nullptr, Element* attributeOwnerElement = nullptr);
514 NodeListsNodeData* nodeLists();
515 void clearNodeLists();
516
517 virtual bool willRespondToMouseMoveEvents();
518 virtual bool willRespondToMouseClickEvents();
519 virtual bool willRespondToMouseWheelEvents();
520
521 WEBCORE_EXPORT unsigned short compareDocumentPosition(Node*);
522
523 virtual Node* toNode() override;
524
525 virtual EventTargetInterface eventTargetInterface() const override;
526 virtual ScriptExecutionContext* scriptExecutionContext() const override final; // Implemented in Document.h
527
528 virtual bool addEventListener(const AtomicString& eventType, RefPtr<EventListener>&&, bool useCapture) override;
529 virtual bool removeEventListener(const AtomicString& eventType, EventListener*, bool useCapture) override;
530
531 using EventTarget::dispatchEvent;
532 virtual bool dispatchEvent(Event&) override;
533
534 void dispatchScopedEvent(Event&);
535
536 virtual void handleLocalEvents(Event&);
537
538 void dispatchSubtreeModifiedEvent();
539 bool dispatchDOMActivateEvent(int detail, PassRefPtr<Event> underlyingEvent);
540
541#if ENABLE(QT_GESTURE_EVENTS)
542 bool dispatchGestureEvent(const PlatformGestureEvent&);
543#endif
544#if ENABLE(TOUCH_EVENTS)
545 virtual bool allowsDoubleTapGesture() const { return true; }
546#endif
547
548#if ENABLE(TOUCH_EVENTS) && !PLATFORM(IOS)
549 bool dispatchTouchEvent(TouchEvent&);
550#endif
551#if ENABLE(INDIE_UI)
552 bool dispatchUIRequestEvent(UIRequestEvent&);
553#endif
554
555 bool dispatchBeforeLoadEvent(const String& sourceURL);
556
557 virtual void dispatchInputEvent();
558
559 // Perform the default action for an event.
560 virtual void defaultEventHandler(Event*);
561
562 void ref();
563 void deref();
564 bool hasOneRef() const;
565 int refCount() const;
566
567#ifndef NDEBUG
568 bool m_deletionHasBegun { false };
569 bool m_inRemovedLastRefFunction { false };
570 bool m_adoptionIsRequired { true };
571#endif
572
573 virtual EventTargetData* eventTargetData() override final;
574 virtual EventTargetData& ensureEventTargetData() override final;
575
576 void getRegisteredMutationObserversOfType(HashMap<MutationObserver*, MutationRecordDeliveryOptions>&, MutationObserver::MutationType, const QualifiedName* attributeName);
577 void registerMutationObserver(MutationObserver*, MutationObserverOptions, const HashSet<AtomicString>& attributeFilter);
578 void unregisterMutationObserver(MutationObserverRegistration*);
579 void registerTransientMutationObserver(MutationObserverRegistration*);
580 void unregisterTransientMutationObserver(MutationObserverRegistration*);
581 void notifyMutationObserversNodeWillDetach();
582
583 WEBCORE_EXPORT void textRects(Vector<IntRect>&) const;
584
585 unsigned connectedSubframeCount() const;
586 void incrementConnectedSubframeCount(unsigned amount = 1);
587 void decrementConnectedSubframeCount(unsigned amount = 1);
588 void updateAncestorConnectedSubframeCountForRemoval() const;
589 void updateAncestorConnectedSubframeCountForInsertion() const;
590
591#if ENABLE(CSS_SELECTOR_JIT)
592 static ptrdiff_t nodeFlagsMemoryOffset() { return OBJECT_OFFSETOF(Node, m_nodeFlags); }
593 static ptrdiff_t rareDataMemoryOffset() { return OBJECT_OFFSETOF(Node, m_data.m_rareData); }
594 static int32_t flagIsText() { return IsTextFlag; }
595 static int32_t flagIsElement() { return IsElementFlag; }
596 static int32_t flagIsHTML() { return IsHTMLFlag; }
597 static int32_t flagIsLink() { return IsLinkFlag; }
598 static int32_t flagHasRareData() { return HasRareDataFlag; }
599 static int32_t flagIsParsingChildrenFinished() { return IsParsingChildrenFinishedFlag; }
600 static int32_t flagChildrenAffectedByFirstChildRulesFlag() { return ChildrenAffectedByFirstChildRulesFlag; }
601 static int32_t flagChildrenAffectedByLastChildRulesFlag() { return ChildrenAffectedByLastChildRulesFlag; }
602
603 static int32_t flagAffectsNextSiblingElementStyle() { return AffectsNextSiblingElementStyle; }
604 static int32_t flagStyleIsAffectedByPreviousSibling() { return StyleIsAffectedByPreviousSibling; }
605#endif // ENABLE(CSS_SELECTOR_JIT)
606
607protected:
608 enum NodeFlags {
609 IsTextFlag = 1,
610 IsContainerFlag = 1 << 1,
611 IsElementFlag = 1 << 2,
612 IsStyledElementFlag = 1 << 3,
613 IsHTMLFlag = 1 << 4,
614 IsSVGFlag = 1 << 5,
615 ChildNeedsStyleRecalcFlag = 1 << 7,
616 InDocumentFlag = 1 << 8,
617 IsLinkFlag = 1 << 9,
618 IsUserActionElement = 1 << 10,
619 HasRareDataFlag = 1 << 11,
620 IsDocumentFragmentFlag = 1 << 12,
621
622 // These bits are used by derived classes, pulled up here so they can
623 // be stored in the same memory word as the Node bits above.
624 IsParsingChildrenFinishedFlag = 1 << 13, // Element
625
626 StyleChangeMask = 1 << nodeStyleChangeShift | 1 << (nodeStyleChangeShift + 1) | 1 << (nodeStyleChangeShift + 2),
627 IsEditingTextFlag = 1 << 17,
628 IsNamedFlowContentNodeFlag = 1 << 18,
629 HasSyntheticAttrChildNodesFlag = 1 << 19,
630 HasCustomStyleResolveCallbacksFlag = 1 << 20,
631 HasEventTargetDataFlag = 1 << 21,
632 IsCustomElement = 1 << 22,
633 IsInShadowTreeFlag = 1 << 23,
634 IsMathMLFlag = 1 << 24,
635
636 ChildrenAffectedByFirstChildRulesFlag = 1 << 25,
637 ChildrenAffectedByLastChildRulesFlag = 1 << 26,
638 ChildrenAffectedByHoverRulesFlag = 1 << 27,
639
640 DirectChildNeedsStyleRecalcFlag = 1 << 28,
641 AffectsNextSiblingElementStyle = 1 << 29,
642 StyleIsAffectedByPreviousSibling = 1 << 30,
643
644 SelfOrAncestorHasDirAutoFlag = 1 << 31,
645
646 DefaultNodeFlags = IsParsingChildrenFinishedFlag
647 };
648
649 bool getFlag(NodeFlags mask) const { return m_nodeFlags & mask; }
650 void setFlag(bool f, NodeFlags mask) const { m_nodeFlags = (m_nodeFlags & ~mask) | (-(int32_t)f & mask); }
651 void setFlag(NodeFlags mask) const { m_nodeFlags |= mask; }
652 void clearFlag(NodeFlags mask) const { m_nodeFlags &= ~mask; }
653
654 enum ConstructionType {
655 CreateOther = DefaultNodeFlags,
656 CreateText = DefaultNodeFlags | IsTextFlag,
657 CreateContainer = DefaultNodeFlags | IsContainerFlag,
658 CreateElement = CreateContainer | IsElementFlag,
659 CreatePseudoElement = CreateElement | InDocumentFlag,
660 CreateShadowRoot = CreateContainer | IsDocumentFragmentFlag | IsInShadowTreeFlag,
661 CreateDocumentFragment = CreateContainer | IsDocumentFragmentFlag,
662 CreateStyledElement = CreateElement | IsStyledElementFlag,
663 CreateHTMLElement = CreateStyledElement | IsHTMLFlag,
664 CreateSVGElement = CreateStyledElement | IsSVGFlag | HasCustomStyleResolveCallbacksFlag,
665 CreateDocument = CreateContainer | InDocumentFlag,
666 CreateEditingText = CreateText | IsEditingTextFlag,
667 CreateMathMLElement = CreateStyledElement | IsMathMLFlag
668 };
669 Node(Document&, ConstructionType);
670
671 virtual void didMoveToNewDocument(Document* oldDocument);
672
673 virtual void addSubresourceAttributeURLs(ListHashSet<URL>&) const { }
674
675 bool hasRareData() const { return getFlag(HasRareDataFlag); }
676
677 NodeRareData* rareData() const;
678 NodeRareData& ensureRareData();
679 void clearRareData();
680
681 void clearEventTargetData();
682
683 void setHasCustomStyleResolveCallbacks() { setFlag(true, HasCustomStyleResolveCallbacksFlag); }
684
685 void setTreeScope(TreeScope& scope) { m_treeScope = &scope; }
686
687 void setStyleChange(StyleChangeType changeType) { m_nodeFlags = (m_nodeFlags & ~StyleChangeMask) | changeType; }
688 void updateAncestorsForStyleRecalc();
689
690private:
691 virtual PseudoId customPseudoId() const
692 {
693 ASSERT(hasCustomStyleResolveCallbacks());
694 return NOPSEUDO;
695 }
696
697 WEBCORE_EXPORT void removedLastRef();
698
699 virtual void refEventTarget() override;
700 virtual void derefEventTarget() override;
701
702 Element* ancestorElement() const;
703
704 void trackForDebugging();
705 void materializeRareData();
706
707 Vector<std::unique_ptr<MutationObserverRegistration>>* mutationObserverRegistry();
708 HashSet<MutationObserverRegistration*>* transientMutationObserverRegistry();
709
710 int m_refCount;
711 mutable uint32_t m_nodeFlags;
712
713 ContainerNode* m_parentNode { nullptr };
714 TreeScope* m_treeScope { nullptr };
715 Node* m_previous { nullptr };
716 Node* m_next { nullptr };
717 // When a node has rare data we move the renderer into the rare data.
718 union DataUnion {
719 RenderObject* m_renderer;
720 NodeRareDataBase* m_rareData;
721 } m_data { nullptr };
722
723protected:
724 bool isParsingChildrenFinished() const { return getFlag(IsParsingChildrenFinishedFlag); }
725 void setIsParsingChildrenFinished() { setFlag(IsParsingChildrenFinishedFlag); }
726 void clearIsParsingChildrenFinished() { clearFlag(IsParsingChildrenFinishedFlag); }
727};
728
729#ifndef NDEBUG
730inline void adopted(Node* node)
731{
732 if (!node)
733 return;
734 ASSERT(!node->m_deletionHasBegun);
735 ASSERT(!node->m_inRemovedLastRefFunction);
736 node->m_adoptionIsRequired = false;
737}
738#endif
739
740ALWAYS_INLINE void Node::ref()
741{
742 ASSERT(isMainThread());
743 ASSERT(!m_deletionHasBegun);
744 ASSERT(!m_inRemovedLastRefFunction);
745 ASSERT(!m_adoptionIsRequired);
746 ++m_refCount;
747}
748
749ALWAYS_INLINE void Node::deref()
750{
751 ASSERT(isMainThread());
752 ASSERT(m_refCount >= 0);
753 ASSERT(!m_deletionHasBegun);
754 ASSERT(!m_inRemovedLastRefFunction);
755 ASSERT(!m_adoptionIsRequired);
756 if (--m_refCount <= 0 && !parentNode()) {
757#ifndef NDEBUG
758 m_inRemovedLastRefFunction = true;
759#endif
760 removedLastRef();
761 }
762}
763
764ALWAYS_INLINE bool Node::hasOneRef() const
765{
766 ASSERT(!m_deletionHasBegun);
767 ASSERT(!m_inRemovedLastRefFunction);
768 return m_refCount == 1;
769}
770
771ALWAYS_INLINE int Node::refCount() const
772{
773 return m_refCount;
774}
775
776// Used in Node::addSubresourceAttributeURLs() and in addSubresourceStyleURLs()
777inline void addSubresourceURL(ListHashSet<URL>& urls, const URL& url)
778{
779 if (!url.isNull())
780 urls.add(url);
781}
782
783inline void Node::setParentNode(ContainerNode* parent)
784{
785 ASSERT(isMainThread());
786 m_parentNode = parent;
787}
788
789inline ContainerNode* Node::parentNode() const
790{
791 ASSERT(isMainThreadOrGCThread());
792 return m_parentNode;
793}
794
795inline ContainerNode* Node::parentNodeGuaranteedHostFree() const
796{
797 ASSERT(!isShadowRoot());
798 return parentNode();
799}
800
801} // namespace WebCore
802
803#if ENABLE(TREE_DEBUGGING)
804// Outside the WebCore namespace for ease of invocation from gdb.
805void showTree(const WebCore::Node*);
806void showNodePath(const WebCore::Node*);
807#endif
808
809#endif
810