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-2011, 2014 Apple Inc. All rights reserved.
6 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
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.
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.
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.
28 #include "bindings/core/v8/ExceptionStatePlaceholder.h"
29 #include "core/dom/MutationObserver.h"
30 #include "core/dom/SimulatedClickOptions.h"
31 #include "core/dom/TreeScope.h"
32 #include "core/dom/TreeShared.h"
33 #include "core/editing/EditingBoundary.h"
34 #include "core/events/EventTarget.h"
35 #include "core/inspector/InspectorCounters.h"
36 #include "core/rendering/style/RenderStyleConstants.h"
37 #include "platform/geometry/LayoutRect.h"
38 #include "platform/heap/Handle.h"
39 #include "platform/weborigin/KURLHash.h"
40 #include "wtf/Forward.h"
42 // This needs to be here because Document.h also depends on it.
43 #define DUMP_NODE_STATISTICS 0
48 class ClassCollection;
50 class DOMSettableTokenList;
54 class EventDispatchMediator;
59 class HTMLInputElement;
60 class HTMLQualifiedName;
66 class NodeEventContext;
68 class NodeListsNodeData;
70 class PlatformGestureEvent;
71 class PlatformKeyboardEvent;
72 class PlatformMouseEvent;
73 class PlatformWheelEvent;
76 class RegisteredEventListener;
78 class RenderBoxModelObject;
81 class SVGQualifiedName;
83 template <typename NodeType> class StaticNodeTypeList;
84 typedef StaticNodeTypeList<Node> StaticNodeList;
90 const int nodeStyleChangeShift = 19;
92 enum StyleChangeType {
94 LocalStyleChange = 1 << nodeStyleChangeShift,
95 SubtreeStyleChange = 2 << nodeStyleChangeShift,
96 NeedsReattachStyleChange = 3 << nodeStyleChangeShift,
99 class NodeRareDataBase {
101 RenderObject* renderer() const { return m_renderer; }
102 void setRenderer(RenderObject* renderer) { m_renderer = renderer; }
105 NodeRareDataBase(RenderObject* renderer)
106 : m_renderer(renderer)
110 // Oilpan: This member is traced in NodeRareData.
111 // FIXME: Can we add traceAfterDispatch and finalizeGarbageCollectedObject
112 // to NodeRareDataBase, and make m_renderer Member<>?
113 RenderObject* m_renderer;
117 #define NODE_BASE_CLASSES public GarbageCollectedFinalized<Node>, public EventTarget
119 // TreeShared should be the last to pack TreeShared::m_refCount and
120 // Node::m_nodeFlags on 64bit platforms.
121 #define NODE_BASE_CLASSES public EventTarget, public TreeShared<Node>
124 class Node : NODE_BASE_CLASSES {
125 friend class Document;
126 friend class TreeScope;
127 friend class TreeScopeAdopter;
129 DEFINE_EVENT_TARGET_REFCOUNTING_WILL_BE_REMOVED(TreeShared<Node>);
130 WILL_BE_USING_GARBAGE_COLLECTED_MIXIN(Node);
136 CDATA_SECTION_NODE = 4,
137 PROCESSING_INSTRUCTION_NODE = 7,
140 DOCUMENT_TYPE_NODE = 10,
141 DOCUMENT_FRAGMENT_NODE = 11,
144 // Entity, EntityReference, Notation, and XPathNamespace nodes are impossible to create in Blink.
145 // But for compatibility reasons we want these enum values exist in JS, and this enum makes the bindings
146 // generation not complain about ENTITY_REFERENCE_NODE being missing from the implementation
147 // while not requiring all switch(NodeType) blocks to include this deprecated constant.
148 enum DeprecatedNodeType {
149 ENTITY_REFERENCE_NODE = 5,
152 XPATH_NAMESPACE_NODE = 13,
155 enum DocumentPosition {
156 DOCUMENT_POSITION_EQUIVALENT = 0x00,
157 DOCUMENT_POSITION_DISCONNECTED = 0x01,
158 DOCUMENT_POSITION_PRECEDING = 0x02,
159 DOCUMENT_POSITION_FOLLOWING = 0x04,
160 DOCUMENT_POSITION_CONTAINS = 0x08,
161 DOCUMENT_POSITION_CONTAINED_BY = 0x10,
162 DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 0x20,
166 // All Nodes are placed in their own heap partition for security.
167 // See http://crbug.com/246860 for detail.
168 void* operator new(size_t);
169 void operator delete(void*);
172 static void dumpStatistics();
176 // DOM methods & attributes for Node
178 bool hasTagName(const HTMLQualifiedName&) const;
179 bool hasTagName(const SVGQualifiedName&) const;
180 virtual String nodeName() const = 0;
181 virtual String nodeValue() const;
182 virtual void setNodeValue(const String&);
183 virtual NodeType nodeType() const = 0;
184 ContainerNode* parentNode() const;
185 Element* parentElement() const;
186 ContainerNode* parentElementOrShadowRoot() const;
187 ContainerNode* parentElementOrDocumentFragment() const;
188 Node* previousSibling() const { return m_previous; }
189 Node* nextSibling() const { return m_next; }
190 PassRefPtrWillBeRawPtr<NodeList> childNodes();
191 Node* firstChild() const;
192 Node* lastChild() const;
194 void remove(ExceptionState&);
196 Node* pseudoAwareNextSibling() const;
197 Node* pseudoAwarePreviousSibling() const;
198 Node* pseudoAwareFirstChild() const;
199 Node* pseudoAwareLastChild() const;
201 virtual KURL baseURI() const;
203 // These should all actually return a node, but this is only important for language bindings,
204 // which will already know and hold a ref on the right node to return.
205 PassRefPtrWillBeRawPtr<Node> insertBefore(PassRefPtrWillBeRawPtr<Node> newChild, Node* refChild, ExceptionState& = ASSERT_NO_EXCEPTION);
206 PassRefPtrWillBeRawPtr<Node> replaceChild(PassRefPtrWillBeRawPtr<Node> newChild, PassRefPtrWillBeRawPtr<Node> oldChild, ExceptionState& = ASSERT_NO_EXCEPTION);
207 PassRefPtrWillBeRawPtr<Node> removeChild(PassRefPtrWillBeRawPtr<Node> child, ExceptionState& = ASSERT_NO_EXCEPTION);
208 PassRefPtrWillBeRawPtr<Node> appendChild(PassRefPtrWillBeRawPtr<Node> newChild, ExceptionState& = ASSERT_NO_EXCEPTION);
210 bool hasChildren() const { return firstChild(); }
211 virtual PassRefPtrWillBeRawPtr<Node> cloneNode(bool deep = false) = 0;
212 virtual const AtomicString& localName() const;
213 virtual const AtomicString& namespaceURI() const;
216 bool isSameNode(Node* other) const { return this == other; }
217 bool isEqualNode(Node*) const;
218 bool isDefaultNamespace(const AtomicString& namespaceURI) const;
219 const AtomicString& lookupPrefix(const AtomicString& namespaceURI) const;
220 const AtomicString& lookupNamespaceURI(const String& prefix) const;
222 String textContent(bool convertBRsToNewlines = false) const;
223 void setTextContent(const String&);
225 // Other methods (not part of DOM)
227 bool isElementNode() const { return getFlag(IsElementFlag); }
228 bool isContainerNode() const { return getFlag(IsContainerFlag); }
229 bool isTextNode() const { return getFlag(IsTextFlag); }
230 bool isHTMLElement() const { return getFlag(IsHTMLFlag); }
231 bool isSVGElement() const { return getFlag(IsSVGFlag); }
233 bool isPseudoElement() const { return pseudoId() != NOPSEUDO; }
234 bool isBeforePseudoElement() const { return pseudoId() == BEFORE; }
235 bool isAfterPseudoElement() const { return pseudoId() == AFTER; }
236 virtual PseudoId pseudoId() const { return NOPSEUDO; }
238 bool isCustomElement() const { return getFlag(CustomElementFlag); }
239 enum CustomElementState {
240 NotCustomElement = 0,
241 WaitingForUpgrade = 1 << 0,
244 CustomElementState customElementState() const
246 return isCustomElement()
247 ? (getFlag(CustomElementUpgradedFlag) ? Upgraded : WaitingForUpgrade)
250 void setCustomElementState(CustomElementState newState);
252 virtual bool isMediaControlElement() const { return false; }
253 virtual bool isMediaControls() const { return false; }
254 virtual bool isVTTElement() const { return false; }
255 virtual bool isAttributeNode() const { return false; }
256 virtual bool isCharacterDataNode() const { return false; }
257 virtual bool isFrameOwnerElement() const { return false; }
259 // StyledElements allow inline style (style="border: 1px"), presentational attributes (ex. color),
260 // class names (ex. class="foo bar") and other non-basic styling features. They and also control
261 // if this element can participate in style sharing.
263 // FIXME: The only things that ever go through StyleResolver that aren't StyledElements are
264 // PseudoElements and VTTElements. It's possible we can just eliminate all the checks
265 // since those elements will never have class names, inline style, or other things that
266 // this apparently guards against.
267 bool isStyledElement() const { return isHTMLElement() || isSVGElement(); }
269 bool isDocumentNode() const;
270 bool isTreeScope() const;
271 bool isDocumentFragment() const { return getFlag(IsDocumentFragmentFlag); }
272 bool isShadowRoot() const { return isDocumentFragment() && isTreeScope(); }
273 bool isInsertionPoint() const { return getFlag(IsInsertionPointFlag); }
275 bool hasCustomStyleCallbacks() const { return getFlag(HasCustomStyleCallbacksFlag); }
277 bool hasSyntheticAttrChildNodes() const { return getFlag(HasSyntheticAttrChildNodesFlag); }
278 void setHasSyntheticAttrChildNodes(bool flag) { setFlag(flag, HasSyntheticAttrChildNodesFlag); }
280 // If this node is in a shadow tree, returns its shadow host. Otherwise, returns 0.
281 Element* shadowHost() const;
282 ShadowRoot* containingShadowRoot() const;
283 ShadowRoot* youngestShadowRoot() const;
285 // Returns 0, a child of ShadowRoot, or a legacy shadow root.
286 Node* nonBoundaryShadowTreeRootNode();
288 // Node's parent, shadow tree host.
289 ContainerNode* parentOrShadowHostNode() const;
290 Element* parentOrShadowHostElement() const;
291 void setParentOrShadowHostNode(ContainerNode*);
293 // Knows about all kinds of hosts.
294 ContainerNode* parentOrShadowHostOrTemplateHostNode() const;
296 // Returns the parent node, but 0 if the parent node is a ShadowRoot.
297 ContainerNode* nonShadowBoundaryParentNode() const;
299 bool selfOrAncestorHasDirAutoAttribute() const { return getFlag(SelfOrAncestorHasDirAutoFlag); }
300 void setSelfOrAncestorHasDirAutoAttribute(bool flag) { setFlag(flag, SelfOrAncestorHasDirAutoFlag); }
302 // Returns the enclosing event parent Element (or self) that, when clicked, would trigger a navigation.
303 Element* enclosingLinkEventParentOrSelf();
305 // These low-level calls give the caller responsibility for maintaining the integrity of the tree.
306 void setPreviousSibling(Node* previous) { m_previous = previous; }
307 void setNextSibling(Node* next) { m_next = next; }
309 virtual bool canContainRangeEndPoint() const { return false; }
311 // FIXME: These two functions belong in editing -- "atomic node" is an editing concept.
312 Node* previousNodeConsideringAtomicNodes() const;
313 Node* nextNodeConsideringAtomicNodes() const;
315 // Returns the next leaf node or 0 if there are no more.
316 // Delivers leaf nodes as if the whole DOM tree were a linear chain of its leaf nodes.
317 // Uses an editing-specific concept of what a leaf node is, and should probably be moved
318 // out of the Node class into an editing-specific source file.
319 Node* nextLeafNode() const;
321 // Returns the previous leaf node or 0 if there are no more.
322 // Delivers leaf nodes as if the whole DOM tree were a linear chain of its leaf nodes.
323 // Uses an editing-specific concept of what a leaf node is, and should probably be moved
324 // out of the Node class into an editing-specific source file.
325 Node* previousLeafNode() const;
327 bool isRootEditableElement() const;
328 Element* rootEditableElement() const;
329 Element* rootEditableElement(EditableType) const;
331 // For <link> and <style> elements.
332 virtual bool sheetLoaded() { return true; }
333 virtual void notifyLoadedSheetAndAllCriticalSubresources(bool /* error loading subresource */) { }
334 virtual void startLoadingDynamicSheet() { ASSERT_NOT_REACHED(); }
336 bool hasName() const { return !isTextNode() && getFlag(HasNameOrIsEditingTextFlag); }
338 bool isUserActionElement() const { return getFlag(IsUserActionElementFlag); }
339 void setUserActionElement(bool flag) { setFlag(flag, IsUserActionElementFlag); }
341 bool active() const { return isUserActionElement() && isUserActionElementActive(); }
342 bool inActiveChain() const { return isUserActionElement() && isUserActionElementInActiveChain(); }
343 bool hovered() const { return isUserActionElement() && isUserActionElementHovered(); }
344 bool focused() const { return isUserActionElement() && isUserActionElementFocused(); }
346 bool needsAttach() const { return styleChangeType() == NeedsReattachStyleChange; }
347 bool needsStyleRecalc() const { return styleChangeType() != NoStyleChange; }
348 StyleChangeType styleChangeType() const { return static_cast<StyleChangeType>(m_nodeFlags & StyleChangeMask); }
349 bool childNeedsStyleRecalc() const { return getFlag(ChildNeedsStyleRecalcFlag); }
350 bool isLink() const { return getFlag(IsLinkFlag); }
351 bool isEditingText() const { return isTextNode() && getFlag(HasNameOrIsEditingTextFlag); }
353 void setHasName(bool f) { ASSERT(!isTextNode()); setFlag(f, HasNameOrIsEditingTextFlag); }
354 void setChildNeedsStyleRecalc() { setFlag(ChildNeedsStyleRecalcFlag); }
355 void clearChildNeedsStyleRecalc() { clearFlag(ChildNeedsStyleRecalcFlag); }
357 void setNeedsStyleRecalc(StyleChangeType);
358 void clearNeedsStyleRecalc();
360 bool childNeedsDistributionRecalc() const { return getFlag(ChildNeedsDistributionRecalcFlag); }
361 void setChildNeedsDistributionRecalc() { setFlag(ChildNeedsDistributionRecalcFlag); }
362 void clearChildNeedsDistributionRecalc() { clearFlag(ChildNeedsDistributionRecalcFlag); }
363 void markAncestorsWithChildNeedsDistributionRecalc();
365 bool childNeedsStyleInvalidation() const { return getFlag(ChildNeedsStyleInvalidationFlag); }
366 void setChildNeedsStyleInvalidation() { setFlag(ChildNeedsStyleInvalidationFlag); }
367 void clearChildNeedsStyleInvalidation() { clearFlag(ChildNeedsStyleInvalidationFlag); }
368 void markAncestorsWithChildNeedsStyleInvalidation();
369 bool needsStyleInvalidation() const { return getFlag(NeedsStyleInvalidationFlag); }
370 void clearNeedsStyleInvalidation() { clearFlag(NeedsStyleInvalidationFlag); }
371 void setNeedsStyleInvalidation();
373 void recalcDistribution();
375 bool svgFilterNeedsLayerUpdate() const { return getFlag(SVGFilterNeedsLayerUpdateFlag); }
376 void setSVGFilterNeedsLayerUpdate() { setFlag(SVGFilterNeedsLayerUpdateFlag); }
377 void clearSVGFilterNeedsLayerUpdate() { clearFlag(SVGFilterNeedsLayerUpdateFlag); }
379 void setIsLink(bool f);
381 bool hasEventTargetData() const { return getFlag(HasEventTargetDataFlag); }
382 void setHasEventTargetData(bool flag) { setFlag(flag, HasEventTargetDataFlag); }
384 bool isV8CollectableDuringMinorGC() const { return getFlag(V8CollectableDuringMinorGCFlag); }
385 void markV8CollectableDuringMinorGC() { setFlag(true, V8CollectableDuringMinorGCFlag); }
386 void clearV8CollectableDuringMinorGC() { setFlag(false, V8CollectableDuringMinorGCFlag); }
388 virtual void setFocus(bool flag);
389 virtual void setActive(bool flag = true);
390 virtual void setHovered(bool flag = true);
392 virtual short tabIndex() const;
394 virtual Node* focusDelegate();
395 // This is called only when the node is focused.
396 virtual bool shouldHaveFocusAppearance() const;
398 // Whether the node is inert. This can't be in Element because text nodes
399 // must be recognized as inert to prevent text selection.
400 bool isInert() const;
402 enum UserSelectAllTreatment {
403 UserSelectAllDoesNotAffectEditability,
404 UserSelectAllIsAlwaysNonEditable
406 bool isContentEditable(UserSelectAllTreatment = UserSelectAllDoesNotAffectEditability);
407 bool isContentRichlyEditable();
409 bool hasEditableStyle(EditableType editableType = ContentIsEditable, UserSelectAllTreatment treatment = UserSelectAllIsAlwaysNonEditable) const
411 switch (editableType) {
412 case ContentIsEditable:
413 return hasEditableStyle(Editable, treatment);
414 case HasEditableAXRole:
415 return isEditableToAccessibility(Editable);
417 ASSERT_NOT_REACHED();
421 bool rendererIsRichlyEditable(EditableType editableType = ContentIsEditable) const
423 switch (editableType) {
424 case ContentIsEditable:
425 return hasEditableStyle(RichlyEditable, UserSelectAllIsAlwaysNonEditable);
426 case HasEditableAXRole:
427 return isEditableToAccessibility(RichlyEditable);
429 ASSERT_NOT_REACHED();
433 virtual LayoutRect boundingBox() const;
434 IntRect pixelSnappedBoundingBox() const { return pixelSnappedIntRect(boundingBox()); }
436 // Returns true if the node has a non-empty bounding box in layout.
437 // This does not 100% guarantee the user can see it, but is pretty close.
438 // Note: This method only works properly after layout has occurred.
439 bool hasNonEmptyBoundingBox() const;
441 unsigned nodeIndex() const;
443 // Returns the DOM ownerDocument attribute. This method never returns NULL, except in the case
444 // of a Document node.
445 Document* ownerDocument() const;
447 // Returns the document associated with this node. A Document node returns itself.
448 Document& document() const
450 return treeScope().document();
453 TreeScope& treeScope() const
459 bool inActiveDocument() const;
461 // Returns true if this node is associated with a document and is in its associated document's
462 // node tree, false otherwise.
463 bool inDocument() const
465 return getFlag(InDocumentFlag);
467 bool isInShadowTree() const { return getFlag(IsInShadowTreeFlag); }
468 bool isInTreeScope() const { return getFlag(static_cast<NodeFlags>(InDocumentFlag | IsInShadowTreeFlag)); }
470 bool isDocumentTypeNode() const { return nodeType() == DOCUMENT_TYPE_NODE; }
471 virtual bool childTypeAllowed(NodeType) const { return false; }
472 unsigned countChildren() const;
474 bool isDescendantOf(const Node*) const;
475 bool contains(const Node*) const;
476 bool containsIncludingShadowDOM(const Node*) const;
477 bool containsIncludingHostElements(const Node&) const;
478 Node* commonAncestor(const Node&, Node* (*parent)(const Node&));
480 // Used to determine whether range offsets use characters or node indices.
481 virtual bool offsetInCharacters() const;
482 // Number of DOM 16-bit units contained in node. Note that rendered text length can be different - e.g. because of
483 // css-transform:capitalize breaking up precomposed characters and ligatures.
484 virtual int maxCharacterOffset() const;
486 // Whether or not a selection can be started in this object
487 virtual bool canStartSelection() const;
489 // Getting points into and out of screen space
490 FloatPoint convertToPage(const FloatPoint&) const;
491 FloatPoint convertFromPage(const FloatPoint&) const;
493 // -----------------------------------------------------------------------------
494 // Integration with rendering tree
496 // As renderer() includes a branch you should avoid calling it repeatedly in hot code paths.
497 // Note that if a Node has a renderer, it's parentNode is guaranteed to have one as well.
498 RenderObject* renderer() const { return hasRareData() ? m_data.m_rareData->renderer() : m_data.m_renderer; };
499 void setRenderer(RenderObject* renderer)
502 m_data.m_rareData->setRenderer(renderer);
504 m_data.m_renderer = renderer;
507 // Use these two methods with caution.
508 RenderBox* renderBox() const;
509 RenderBoxModelObject* renderBoxModelObject() const;
511 struct AttachContext {
512 RenderStyle* resolvedStyle;
513 bool performingReattach;
515 AttachContext() : resolvedStyle(0), performingReattach(false) { }
518 // Attaches this node to the rendering tree. This calculates the style to be applied to the node and creates an
519 // appropriate RenderObject which will be inserted into the tree (except when the style has display: none). This
520 // makes the node visible in the FrameView.
521 virtual void attach(const AttachContext& = AttachContext());
523 // Detaches the node from the rendering tree, making it invisible in the rendered view. This method will remove
524 // the node's rendering object from the rendering tree and delete it.
525 virtual void detach(const AttachContext& = AttachContext());
528 bool inDetach() const;
531 void reattach(const AttachContext& = AttachContext());
532 void lazyReattachIfAttached();
534 // Returns true if recalcStyle should be called on the object, if there is such a method (on Document and Element).
535 bool shouldCallRecalcStyle(StyleRecalcChange);
537 // Wrapper for nodes that don't have a renderer, but still cache the style (like HTMLOptionElement).
538 RenderStyle* renderStyle() const;
539 RenderStyle* parentRenderStyle() const;
541 RenderStyle* computedStyle(PseudoId pseudoElementSpecifier = NOPSEUDO) { return virtualComputedStyle(pseudoElementSpecifier); }
543 // -----------------------------------------------------------------------------
544 // Notification of document structure changes (see ContainerNode.h for more notification methods)
546 // At first, WebKit notifies the node that it has been inserted into the document. This is called during document parsing, and also
547 // 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.
548 // This is similar to the DOMNodeInsertedIntoDocument DOM event, but does not require the overhead of event
551 // WebKit notifies this callback regardless if the subtree of the node is a document tree or a floating subtree.
552 // Implementation can determine the type of subtree by seeing insertionPoint->inDocument().
553 // For a performance reason, notifications are delivered only to ContainerNode subclasses if the insertionPoint is out of document.
555 // There are another callback named didNotifySubtreeInsertionsToDocument(), which is called after all the descendant is notified,
556 // if this node was inserted into the document tree. Only a few subclasses actually need this. To utilize this, the node should
557 // return InsertionShouldCallDidNotifySubtreeInsertions from insertedInto().
559 enum InsertionNotificationRequest {
561 InsertionShouldCallDidNotifySubtreeInsertions
564 virtual InsertionNotificationRequest insertedInto(ContainerNode* insertionPoint);
565 virtual void didNotifySubtreeInsertionsToDocument() { }
567 // Notifies the node that it is no longer part of the tree.
569 // This is a dual of insertedInto(), and is similar to the DOMNodeRemovedFromDocument DOM event, but does not require the overhead of event
570 // dispatching, and is called _after_ the node is removed from the tree.
572 virtual void removedFrom(ContainerNode* insertionPoint);
574 String debugName() const;
577 virtual void formatForDebugger(char* buffer, unsigned length) const;
579 void showNode(const char* prefix = "") const;
580 void showTreeForThis() const;
581 void showNodePathForThis() const;
582 void showTreeAndMark(const Node* markedNode1, const char* markedLabel1, const Node* markedNode2 = 0, const char* markedLabel2 = 0) const;
583 void showTreeForThisAcrossFrame() const;
586 NodeListsNodeData* nodeLists();
587 void clearNodeLists();
589 virtual bool willRespondToMouseMoveEvents();
590 virtual bool willRespondToMouseClickEvents();
591 virtual bool willRespondToTouchEvents();
593 enum ShadowTreesTreatment {
594 TreatShadowTreesAsDisconnected,
595 TreatShadowTreesAsComposed
598 unsigned short compareDocumentPosition(const Node*, ShadowTreesTreatment = TreatShadowTreesAsDisconnected) const;
600 virtual Node* toNode() OVERRIDE FINAL;
602 virtual const AtomicString& interfaceName() const OVERRIDE;
603 virtual ExecutionContext* executionContext() const OVERRIDE FINAL;
605 virtual bool addEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, bool useCapture = false) OVERRIDE;
606 virtual bool removeEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, bool useCapture = false) OVERRIDE;
607 virtual void removeAllEventListeners() OVERRIDE;
608 void removeAllEventListenersRecursively();
610 // Handlers to do/undo actions on the target node before an event is dispatched to it and after the event
611 // has been dispatched. The data pointer is handed back by the preDispatch and passed to postDispatch.
612 virtual void* preDispatchEventHandler(Event*) { return 0; }
613 virtual void postDispatchEventHandler(Event*, void* /*dataFromPreDispatch*/) { }
615 using EventTarget::dispatchEvent;
616 virtual bool dispatchEvent(PassRefPtrWillBeRawPtr<Event>) OVERRIDE;
618 void dispatchScopedEvent(PassRefPtrWillBeRawPtr<Event>);
619 void dispatchScopedEventDispatchMediator(PassRefPtrWillBeRawPtr<EventDispatchMediator>);
621 virtual void handleLocalEvents(Event*);
623 void dispatchSubtreeModifiedEvent();
624 bool dispatchDOMActivateEvent(int detail, PassRefPtrWillBeRawPtr<Event> underlyingEvent);
626 bool dispatchKeyEvent(const PlatformKeyboardEvent&);
627 bool dispatchWheelEvent(const PlatformWheelEvent&);
628 bool dispatchMouseEvent(const PlatformMouseEvent&, const AtomicString& eventType, int clickCount = 0, Node* relatedTarget = 0);
629 bool dispatchGestureEvent(const PlatformGestureEvent&);
630 bool dispatchTouchEvent(PassRefPtrWillBeRawPtr<TouchEvent>);
632 void dispatchSimulatedClick(Event* underlyingEvent, SimulatedClickMouseEventOptions = SendNoEvents);
634 void dispatchInputEvent();
636 // Perform the default action for an event.
637 virtual void defaultEventHandler(Event*);
638 virtual void willCallDefaultEventHandler(const Event&);
640 virtual EventTargetData* eventTargetData() OVERRIDE;
641 virtual EventTargetData& ensureEventTargetData() OVERRIDE;
643 void getRegisteredMutationObserversOfType(WillBeHeapHashMap<RawPtrWillBeMember<MutationObserver>, MutationRecordDeliveryOptions>&, MutationObserver::MutationType, const QualifiedName* attributeName);
644 void registerMutationObserver(MutationObserver&, MutationObserverOptions, const HashSet<AtomicString>& attributeFilter);
645 void unregisterMutationObserver(MutationObserverRegistration*);
646 void registerTransientMutationObserver(MutationObserverRegistration*);
647 void unregisterTransientMutationObserver(MutationObserverRegistration*);
648 void notifyMutationObserversNodeWillDetach();
650 unsigned connectedSubframeCount() const;
651 void incrementConnectedSubframeCount(unsigned amount = 1);
652 void decrementConnectedSubframeCount(unsigned amount = 1);
653 void updateAncestorConnectedSubframeCountForRemoval() const;
654 void updateAncestorConnectedSubframeCountForInsertion() const;
656 PassRefPtrWillBeRawPtr<StaticNodeList> getDestinationInsertionPoints();
658 void setAlreadySpellChecked(bool flag) { setFlag(flag, AlreadySpellCheckedFlag); }
659 bool isAlreadySpellChecked() { return getFlag(AlreadySpellCheckedFlag); }
661 bool isFinishedParsingChildren() const { return getFlag(IsFinishedParsingChildrenFlag); }
663 virtual void trace(Visitor*) OVERRIDE;
665 unsigned lengthOfContents() const;
671 // Node type flags. These never change once created.
673 IsContainerFlag = 1 << 2,
674 IsElementFlag = 1 << 3,
677 IsDocumentFragmentFlag = 1 << 6,
678 IsInsertionPointFlag = 1 << 7,
680 // Changes based on if the element should be treated like a link,
681 // ex. When setting the href attribute on an <a>.
684 // Changes based on :hover, :active and :focus state.
685 IsUserActionElementFlag = 1 << 9,
687 // Tree state flags. These change when the element is added/removed
689 InDocumentFlag = 1 << 10,
690 IsInShadowTreeFlag = 1 << 11,
692 // Set by the parser when the children are done parsing.
693 IsFinishedParsingChildrenFlag = 1 << 12,
695 // Flags related to recalcStyle.
696 SVGFilterNeedsLayerUpdateFlag = 1 << 13,
697 HasCustomStyleCallbacksFlag = 1 << 14,
698 ChildNeedsStyleInvalidationFlag = 1 << 15,
699 NeedsStyleInvalidationFlag = 1 << 16,
700 ChildNeedsDistributionRecalcFlag = 1 << 17,
701 ChildNeedsStyleRecalcFlag = 1 << 18,
702 StyleChangeMask = 1 << nodeStyleChangeShift | 1 << (nodeStyleChangeShift + 1),
704 CustomElementFlag = 1 << 21,
705 CustomElementUpgradedFlag = 1 << 22,
707 HasNameOrIsEditingTextFlag = 1 << 23,
708 HasWeakReferencesFlag = 1 << 24,
709 V8CollectableDuringMinorGCFlag = 1 << 25,
710 HasSyntheticAttrChildNodesFlag = 1 << 26,
711 HasEventTargetDataFlag = 1 << 27,
712 AlreadySpellCheckedFlag = 1 << 28,
715 SelfOrAncestorHasDirAutoFlag = 1 << 29,
717 DefaultNodeFlags = IsFinishedParsingChildrenFlag | ChildNeedsStyleRecalcFlag | NeedsReattachStyleChange
722 bool getFlag(NodeFlags mask) const { return m_nodeFlags & mask; }
723 void setFlag(bool f, NodeFlags mask) { m_nodeFlags = (m_nodeFlags & ~mask) | (-(int32_t)f & mask); }
724 void setFlag(NodeFlags mask) { m_nodeFlags |= mask; }
725 void clearFlag(NodeFlags mask) { m_nodeFlags &= ~mask; }
728 enum ConstructionType {
729 CreateOther = DefaultNodeFlags,
730 CreateText = DefaultNodeFlags | IsTextFlag,
731 CreateContainer = DefaultNodeFlags | IsContainerFlag,
732 CreateElement = CreateContainer | IsElementFlag,
733 CreateShadowRoot = CreateContainer | IsDocumentFragmentFlag | IsInShadowTreeFlag,
734 CreateDocumentFragment = CreateContainer | IsDocumentFragmentFlag,
735 CreateHTMLElement = CreateElement | IsHTMLFlag,
736 CreateSVGElement = CreateElement | IsSVGFlag,
737 CreateDocument = CreateContainer | InDocumentFlag,
738 CreateInsertionPoint = CreateHTMLElement | IsInsertionPointFlag,
739 CreateEditingText = CreateText | HasNameOrIsEditingTextFlag,
742 Node(TreeScope*, ConstructionType);
744 virtual void didMoveToNewDocument(Document& oldDocument);
746 static void reattachWhitespaceSiblings(Text* start);
749 void willBeDeletedFromDocument();
752 bool hasRareData() const { return getFlag(HasRareDataFlag); }
754 NodeRareData* rareData() const;
755 NodeRareData& ensureRareData();
757 void clearRareData();
759 void clearEventTargetData();
762 void setHasCustomStyleCallbacks() { setFlag(true, HasCustomStyleCallbacksFlag); }
764 void setTreeScope(TreeScope* scope) { m_treeScope = scope; }
766 // isTreeScopeInitialized() can be false
767 // - in the destruction of Document or ShadowRoot where m_treeScope is set to null or
768 // - in the Node constructor called by these two classes where m_treeScope is set by TreeScope ctor.
769 bool isTreeScopeInitialized() const { return m_treeScope; }
771 void markAncestorsWithChildNeedsStyleRecalc();
773 void setIsFinishedParsingChildren(bool value) { setFlag(value, IsFinishedParsingChildrenFlag); }
776 friend class TreeShared<Node>;
777 friend class WeakNodeMap;
779 unsigned styledSubtreeSize() const;
782 void removedLastRef();
784 bool hasTreeSharedParent() const { return !!parentOrShadowHostNode(); }
786 enum EditableLevel { Editable, RichlyEditable };
787 bool hasEditableStyle(EditableLevel, UserSelectAllTreatment = UserSelectAllIsAlwaysNonEditable) const;
788 bool isEditableToAccessibility(EditableLevel) const;
790 bool isUserActionElementActive() const;
791 bool isUserActionElementInActiveChain() const;
792 bool isUserActionElementHovered() const;
793 bool isUserActionElementFocused() const;
795 void traceStyleChange(StyleChangeType);
796 void traceStyleChangeIfNeeded(StyleChangeType);
797 void setStyleChange(StyleChangeType);
799 virtual RenderStyle* nonRendererStyle() const { return 0; }
801 virtual RenderStyle* virtualComputedStyle(PseudoId = NOPSEUDO);
803 void trackForDebugging();
805 WillBeHeapVector<OwnPtrWillBeMember<MutationObserverRegistration> >* mutationObserverRegistry();
806 WillBeHeapHashSet<RawPtrWillBeMember<MutationObserverRegistration> >* transientMutationObserverRegistry();
808 uint32_t m_nodeFlags;
809 RawPtrWillBeMember<ContainerNode> m_parentOrShadowHostNode;
810 RawPtrWillBeMember<TreeScope> m_treeScope;
811 RawPtrWillBeMember<Node> m_previous;
812 RawPtrWillBeMember<Node> m_next;
813 // When a node has rare data we move the renderer into the rare data.
815 DataUnion() : m_renderer(0) { }
816 RenderObject* m_renderer;
817 NodeRareDataBase* m_rareData;
821 inline void Node::setParentOrShadowHostNode(ContainerNode* parent)
823 ASSERT(isMainThread());
824 m_parentOrShadowHostNode = parent;
827 inline ContainerNode* Node::parentOrShadowHostNode() const
829 ASSERT(isMainThread());
830 return m_parentOrShadowHostNode;
833 inline ContainerNode* Node::parentNode() const
835 return isShadowRoot() ? 0 : parentOrShadowHostNode();
838 inline void Node::lazyReattachIfAttached()
840 if (styleChangeType() == NeedsReattachStyleChange)
842 if (!inActiveDocument())
845 AttachContext context;
846 context.performingReattach = true;
849 markAncestorsWithChildNeedsStyleRecalc();
852 inline bool Node::shouldCallRecalcStyle(StyleRecalcChange change)
854 return change >= Inherit || needsStyleRecalc() || childNeedsStyleRecalc();
857 inline bool isTreeScopeRoot(const Node* node)
859 return !node || node->isDocumentNode() || node->isShadowRoot();
862 inline bool isTreeScopeRoot(const Node& node)
864 return node.isDocumentNode() || node.isShadowRoot();
867 // Allow equality comparisons of Nodes by reference or pointer, interchangeably.
868 DEFINE_COMPARISON_OPERATORS_WITH_REFERENCES_REFCOUNTED(Node)
871 #define DEFINE_NODE_TYPE_CASTS(thisType, predicate) \
872 template<typename T> inline thisType* to##thisType(const RefPtr<T>& node) { return to##thisType(node.get()); } \
873 DEFINE_TYPE_CASTS(thisType, Node, node, node->predicate, node.predicate)
875 // This requires isClassName(const Node&).
876 #define DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(thisType) \
877 template<typename T> inline thisType* to##thisType(const RefPtr<T>& node) { return to##thisType(node.get()); } \
878 DEFINE_TYPE_CASTS(thisType, Node, node, is##thisType(*node), is##thisType(node))
880 #define DECLARE_NODE_FACTORY(T) \
881 static PassRefPtrWillBeRawPtr<T> create(Document&)
882 #define DEFINE_NODE_FACTORY(T) \
883 PassRefPtrWillBeRawPtr<T> T::create(Document& document) \
885 return adoptRefWillBeNoop(new T(document)); \
891 // Outside the WebCore namespace for ease of invocation from gdb.
892 void showNode(const blink::Node*);
893 void showTree(const blink::Node*);
894 void showNodePath(const blink::Node*);