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 "KURLHash.h"
30 #include "RenderStyleConstants.h"
31 #include "ScriptWrappable.h"
32 #include "TreeShared.h"
33 #include <wtf/Forward.h>
34 #include <wtf/ListHashSet.h>
35 
36 #if USE(JSC)
37 namespace JSC {
38     class JSGlobalData;
39     class MarkStack;
40     typedef MarkStack SlotVisitor;
41 }
42 #endif
43 
44 namespace WebCore {
45 
46 class Attribute;
47 class ClassNodeList;
48 class ContainerNode;
49 class Document;
50 class DynamicNodeList;
51 class Element;
52 class Event;
53 class EventContext;
54 class EventListener;
55 class FloatPoint;
56 class Frame;
57 class InputElement;
58 class IntRect;
59 class KeyboardEvent;
60 class NSResolver;
61 class NamedNodeMap;
62 class NameNodeList;
63 class NodeList;
64 class NodeRareData;
65 class PlatformKeyboardEvent;
66 class PlatformMouseEvent;
67 class PlatformWheelEvent;
68 class QualifiedName;
69 class RegisteredEventListener;
70 class RenderArena;
71 class RenderBox;
72 class RenderBoxModelObject;
73 class RenderObject;
74 class RenderStyle;
75 #if ENABLE(SVG)
76 class SVGUseElement;
77 #endif
78 class TagNodeList;
79 class TreeScope;
80 
81 typedef int ExceptionCode;
82 
83 const int nodeStyleChangeShift = 25;
84 
85 // SyntheticStyleChange means that we need to go through the entire style change logic even though
86 // no style property has actually changed. It is used to restructure the tree when, for instance,
87 // RenderLayers are created or destroyed due to animation changes.
88 enum StyleChangeType {
89     NoStyleChange = 0,
90     InlineStyleChange = 1 << nodeStyleChangeShift,
91     FullStyleChange = 2 << nodeStyleChangeShift,
92     SyntheticStyleChange = 3 << nodeStyleChangeShift
93 };
94 
95 class Node : public EventTarget, public TreeShared<ContainerNode>, public ScriptWrappable {
96     friend class Document;
97     friend class TreeScope;
98 
99 public:
100     enum NodeType {
101         ELEMENT_NODE = 1,
102         ATTRIBUTE_NODE = 2,
103         TEXT_NODE = 3,
104         CDATA_SECTION_NODE = 4,
105         ENTITY_REFERENCE_NODE = 5,
106         ENTITY_NODE = 6,
107         PROCESSING_INSTRUCTION_NODE = 7,
108         COMMENT_NODE = 8,
109         DOCUMENT_NODE = 9,
110         DOCUMENT_TYPE_NODE = 10,
111         DOCUMENT_FRAGMENT_NODE = 11,
112         NOTATION_NODE = 12,
113         XPATH_NAMESPACE_NODE = 13,
114         SHADOW_ROOT_NODE = 14
115     };
116     enum DocumentPosition {
117         DOCUMENT_POSITION_EQUIVALENT = 0x00,
118         DOCUMENT_POSITION_DISCONNECTED = 0x01,
119         DOCUMENT_POSITION_PRECEDING = 0x02,
120         DOCUMENT_POSITION_FOLLOWING = 0x04,
121         DOCUMENT_POSITION_CONTAINS = 0x08,
122         DOCUMENT_POSITION_CONTAINED_BY = 0x10,
123         DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 0x20,
124     };
125 
126     static bool isSupported(const String& feature, const String& version);
127 
128     static void startIgnoringLeaks();
129     static void stopIgnoringLeaks();
130 
131     static void dumpStatistics();
132 
133     enum StyleChange { NoChange, NoInherit, Inherit, Detach, Force };
134     static StyleChange diff(const RenderStyle*, const RenderStyle*);
135 
136     virtual ~Node();
137 
138     // DOM methods & attributes for Node
139 
140     bool hasTagName(const QualifiedName&) const;
141     bool hasLocalName(const AtomicString&) const;
142     virtual String nodeName() const = 0;
143     virtual String nodeValue() const;
144     virtual void setNodeValue(const String&, ExceptionCode&);
145     virtual NodeType nodeType() const = 0;
146     ContainerNode* parentNode() const;
147     Element* parentElement() const;
previousSibling()148     Node* previousSibling() const { return m_previous; }
nextSibling()149     Node* nextSibling() const { return m_next; }
150     PassRefPtr<NodeList> childNodes();
151     Node* firstChild() const;
152     Node* lastChild() const;
153     bool hasAttributes() const;
154     NamedNodeMap* attributes() const;
155 
156     virtual KURL baseURI() const;
157 
158     void getSubresourceURLs(ListHashSet<KURL>&) const;
159 
160     // These should all actually return a node, but this is only important for language bindings,
161     // which will already know and hold a ref on the right node to return. Returning bool allows
162     // these methods to be more efficient since they don't need to return a ref
163     bool insertBefore(PassRefPtr<Node> newChild, Node* refChild, ExceptionCode&, bool shouldLazyAttach = false);
164     bool replaceChild(PassRefPtr<Node> newChild, Node* oldChild, ExceptionCode&, bool shouldLazyAttach = false);
165     bool removeChild(Node* child, ExceptionCode&);
166     bool appendChild(PassRefPtr<Node> newChild, ExceptionCode&, bool shouldLazyAttach = false);
167 
168     void remove(ExceptionCode&);
hasChildNodes()169     bool hasChildNodes() const { return firstChild(); }
170     virtual PassRefPtr<Node> cloneNode(bool deep) = 0;
localName()171     const AtomicString& localName() const { return virtualLocalName(); }
namespaceURI()172     const AtomicString& namespaceURI() const { return virtualNamespaceURI(); }
prefix()173     const AtomicString& prefix() const { return virtualPrefix(); }
174     virtual void setPrefix(const AtomicString&, ExceptionCode&);
175     void normalize();
176 
isSameNode(Node * other)177     bool isSameNode(Node* other) const { return this == other; }
178     bool isEqualNode(Node*) const;
179     bool isDefaultNamespace(const AtomicString& namespaceURI) const;
180     String lookupPrefix(const AtomicString& namespaceURI) const;
181     String lookupNamespaceURI(const String& prefix) const;
182     String lookupNamespacePrefix(const AtomicString& namespaceURI, const Element* originalElement) const;
183 
184     String textContent(bool convertBRsToNewlines = false) const;
185     void setTextContent(const String&, ExceptionCode&);
186 
187     Node* lastDescendant() const;
188     Node* firstDescendant() const;
189 
190     // Other methods (not part of DOM)
191 
isElementNode()192     bool isElementNode() const { return getFlag(IsElementFlag); }
isContainerNode()193     bool isContainerNode() const { return getFlag(IsContainerFlag); }
isTextNode()194     bool isTextNode() const { return getFlag(IsTextFlag); }
195 
isHTMLElement()196     bool isHTMLElement() const { return getFlag(IsHTMLFlag); }
197 
isSVGElement()198     bool isSVGElement() const { return getFlag(IsSVGFlag); }
isSVGShadowRoot()199     virtual bool isSVGShadowRoot() const { return false; }
200 #if ENABLE(SVG)
201     SVGUseElement* svgShadowHost() const;
202 #endif
203 
isMediaControlElement()204     virtual bool isMediaControlElement() const { return false; }
isMediaControls()205     virtual bool isMediaControls() const { return false; }
isStyledElement()206     bool isStyledElement() const { return getFlag(IsStyledElementFlag); }
isFrameOwnerElement()207     virtual bool isFrameOwnerElement() const { return false; }
isAttributeNode()208     virtual bool isAttributeNode() const { return false; }
isCommentNode()209     bool isCommentNode() const { return getFlag(IsCommentFlag); }
isCharacterDataNode()210     virtual bool isCharacterDataNode() const { return false; }
211     bool isDocumentNode() const;
isShadowRoot()212     bool isShadowRoot() const { return getFlag(IsShadowRootFlag); }
213     // FIXME: Remove this when all shadow roots are ShadowRoots.
isShadowBoundary()214     virtual bool isShadowBoundary() const { return false; }
canHaveLightChildRendererWithShadow()215     virtual bool canHaveLightChildRendererWithShadow() const { return false; }
216 
217     Node* shadowAncestorNode();
218     Node* shadowTreeRootNode();
219     bool isInShadowTree();
220     // Node's parent, shadow tree host, or SVG use.
221     ContainerNode* parentOrHostNode() const;
222     Element* parentOrHostElement() const;
223     // Use when it's guaranteed to that shadowHost is 0 and svgShadowHost is 0.
224     ContainerNode* parentNodeGuaranteedHostFree() const;
225 
226     Element* shadowHost() const;
227     void setShadowHost(Element*);
228 
selfOrAncestorHasDirAutoAttribute()229     bool selfOrAncestorHasDirAutoAttribute() const { return getFlag(SelfOrAncestorHasDirAutoFlag); }
setSelfOrAncestorHasDirAutoAttribute(bool flag)230     void setSelfOrAncestorHasDirAutoAttribute(bool flag) { setFlag(flag, SelfOrAncestorHasDirAutoFlag); }
231 
232     // Returns the enclosing event parent node (or self) that, when clicked, would trigger a navigation.
233     Node* enclosingLinkEventParentOrSelf();
234 
235     bool isBlockFlow() const;
236     bool isBlockFlowOrBlockTable() const;
237 
238     // These low-level calls give the caller responsibility for maintaining the integrity of the tree.
setPreviousSibling(Node * previous)239     void setPreviousSibling(Node* previous) { m_previous = previous; }
setNextSibling(Node * next)240     void setNextSibling(Node* next) { m_next = next; }
241 
242     // FIXME: These two functions belong in editing -- "atomic node" is an editing concept.
243     Node* previousNodeConsideringAtomicNodes() const;
244     Node* nextNodeConsideringAtomicNodes() const;
245 
246     // Returns the next leaf node or 0 if there are no more.
247     // Delivers leaf nodes as if the whole DOM tree were a linear chain of its leaf nodes.
248     // Uses an editing-specific concept of what a leaf node is, and should probably be moved
249     // out of the Node class into an editing-specific source file.
250     Node* nextLeafNode() const;
251 
252     // Returns the previous leaf node or 0 if there are no more.
253     // Delivers leaf nodes as if the whole DOM tree were a linear chain of its leaf nodes.
254     // Uses an editing-specific concept of what a leaf node is, and should probably be moved
255     // out of the Node class into an editing-specific source file.
256     Node* previousLeafNode() const;
257 
258     // enclosingBlockFlowElement() is deprecated. Use enclosingBlock instead.
259     Element* enclosingBlockFlowElement() const;
260 
261     Element* rootEditableElement() const;
262 
263     bool inSameContainingBlockFlowElement(Node*);
264 
265     // FIXME: All callers of this function are almost certainly wrong!
266     virtual void deprecatedParserAddChild(PassRefPtr<Node>);
267 
268     // Called by the parser when this element's close tag is reached,
269     // signaling that all child tags have been parsed and added.
270     // This is needed for <applet> and <object> elements, which can't lay themselves out
271     // until they know all of their nested <param>s. [Radar 3603191, 4040848].
272     // Also used for script elements and some SVG elements for similar purposes,
273     // but making parsing a special case in this respect should be avoided if possible.
finishParsingChildren()274     virtual void finishParsingChildren() { }
beginParsingChildren()275     virtual void beginParsingChildren() { }
276 
277     // Called on the focused node right before dispatching an unload event.
aboutToUnload()278     virtual void aboutToUnload() { }
279 
280     // For <link> and <style> elements.
sheetLoaded()281     virtual bool sheetLoaded() { return true; }
282 
hasID()283     bool hasID() const { return getFlag(HasIDFlag); }
hasClass()284     bool hasClass() const { return getFlag(HasClassFlag); }
active()285     bool active() const { return getFlag(IsActiveFlag); }
inActiveChain()286     bool inActiveChain() const { return getFlag(InActiveChainFlag); }
inDetach()287     bool inDetach() const { return getFlag(InDetachFlag); }
hovered()288     bool hovered() const { return getFlag(IsHoveredFlag); }
focused()289     bool focused() const { return hasRareData() ? rareDataFocused() : false; }
attached()290     bool attached() const { return getFlag(IsAttachedFlag); }
setAttached()291     void setAttached() { setFlag(IsAttachedFlag); }
needsStyleRecalc()292     bool needsStyleRecalc() const { return styleChangeType() != NoStyleChange; }
styleChangeType()293     StyleChangeType styleChangeType() const { return static_cast<StyleChangeType>(m_nodeFlags & StyleChangeMask); }
childNeedsStyleRecalc()294     bool childNeedsStyleRecalc() const { return getFlag(ChildNeedsStyleRecalcFlag); }
isLink()295     bool isLink() const { return getFlag(IsLinkFlag); }
296 
setHasID(bool f)297     void setHasID(bool f) { setFlag(f, HasIDFlag); }
setHasClass(bool f)298     void setHasClass(bool f) { setFlag(f, HasClassFlag); }
setChildNeedsStyleRecalc()299     void setChildNeedsStyleRecalc() { setFlag(ChildNeedsStyleRecalcFlag); }
clearChildNeedsStyleRecalc()300     void clearChildNeedsStyleRecalc() { clearFlag(ChildNeedsStyleRecalcFlag); }
setInDocument()301     void setInDocument() { setFlag(InDocumentFlag); }
clearInDocument()302     void clearInDocument() { clearFlag(InDocumentFlag); }
303 
setInActiveChain()304     void setInActiveChain() { setFlag(InActiveChainFlag); }
clearInActiveChain()305     void clearInActiveChain() { clearFlag(InActiveChainFlag); }
306 
307     void setNeedsStyleRecalc(StyleChangeType changeType = FullStyleChange);
clearNeedsStyleRecalc()308     void clearNeedsStyleRecalc() { m_nodeFlags &= ~StyleChangeMask; }
309 
setIsLink(bool f)310     void setIsLink(bool f) { setFlag(f, IsLinkFlag); }
setIsLink()311     void setIsLink() { setFlag(IsLinkFlag); }
clearIsLink()312     void clearIsLink() { clearFlag(IsLinkFlag); }
313 
314     enum ShouldSetAttached {
315         SetAttached,
316         DoNotSetAttached
317     };
318     void lazyAttach(ShouldSetAttached = SetAttached);
319 
320     virtual void setFocus(bool = true);
321     virtual void setActive(bool f = true, bool /*pause*/ = false) { setFlag(f, IsActiveFlag); }
322     virtual void setHovered(bool f = true) { setFlag(f, IsHoveredFlag); }
323 
324     virtual short tabIndex() const;
325 
326     // Whether this kind of node can receive focus by default. Most nodes are
327     // not focusable but some elements, such as form controls and links, are.
328     virtual bool supportsFocus() const;
329     // Whether the node can actually be focused.
330     virtual bool isFocusable() const;
331     virtual bool isKeyboardFocusable(KeyboardEvent*) const;
332     virtual bool isMouseFocusable() const;
333 
334     bool isContentEditable() const;
335 
rendererIsEditable()336     bool rendererIsEditable() const { return rendererIsEditable(Editable); }
rendererIsRichlyEditable()337     bool rendererIsRichlyEditable() const { return rendererIsEditable(RichlyEditable); }
338     virtual bool shouldUseInputMethod() const;
339     virtual IntRect getRect() const;
340     IntRect renderRect(bool* isReplaced);
341 
342     // Returns true if the node has a non-empty bounding box in layout.
343     // This does not 100% guarantee the user can see it, but is pretty close.
344     // Note: This method only works properly after layout has occurred.
345     bool hasNonEmptyBoundingBox() const;
346 
347     virtual void recalcStyle(StyleChange = NoChange) { }
348 
349     unsigned nodeIndex() const;
350 
351     // Returns the DOM ownerDocument attribute. This method never returns NULL, except in the case
352     // of (1) a Document node or (2) a DocumentType node that is not used with any Document yet.
353     Document* ownerDocument() const;
354 
355     // Returns the document associated with this node. This method never returns NULL, except in the case
356     // of a DocumentType node that is not used with any Document yet. A Document node returns itself.
document()357     Document* document() const
358     {
359         ASSERT(this);
360         // FIXME: below ASSERT is useful, but prevents the use of document() in the constructor or destructor
361         // due to the virtual function call to nodeType().
362         ASSERT(m_document || (nodeType() == DOCUMENT_TYPE_NODE && !inDocument()));
363         return m_document;
364     }
365 
366     TreeScope* treeScope() const;
367 
368     // Used by the basic DOM methods (e.g., appendChild()).
369     void setTreeScopeRecursively(TreeScope*, bool includeRoot = true);
370 
371     // Returns true if this node is associated with a document and is in its associated document's
372     // node tree, false otherwise.
inDocument()373     bool inDocument() const
374     {
375         ASSERT(m_document || !getFlag(InDocumentFlag));
376         return getFlag(InDocumentFlag);
377     }
378 
isReadOnlyNode()379     bool isReadOnlyNode() const { return nodeType() == ENTITY_REFERENCE_NODE; }
childTypeAllowed(NodeType)380     virtual bool childTypeAllowed(NodeType) const { return false; }
381     unsigned childNodeCount() const;
382     Node* childNode(unsigned index) const;
383 
384     // Does a pre-order traversal of the tree to find the next node after this one.
385     // This uses the same order that tags appear in the source file. If the stayWithin
386     // argument is non-null, the traversal will stop once the specified node is reached.
387     // This can be used to restrict traversal to a particular sub-tree.
388     Node* traverseNextNode(const Node* stayWithin = 0) const;
389 
390     // Like traverseNextNode, but skips children and starts with the next sibling.
391     Node* traverseNextSibling(const Node* stayWithin = 0) const;
392 
393     // Does a reverse pre-order traversal to find the node that comes before the current one in document order
394     Node* traversePreviousNode(const Node* stayWithin = 0) const;
395 
396     // Like traverseNextNode, but visits parents after their children.
397     Node* traverseNextNodePostOrder() const;
398 
399     // Like traversePreviousNode, but visits parents before their children.
400     Node* traversePreviousNodePostOrder(const Node* stayWithin = 0) const;
401     Node* traversePreviousSiblingPostOrder(const Node* stayWithin = 0) const;
402 
403     void checkSetPrefix(const AtomicString& prefix, ExceptionCode&);
404     bool isDescendantOf(const Node*) const;
405     bool contains(const Node*) const;
406     bool containsIncludingShadowDOM(Node*);
407 
408     // This method is used to do strict error-checking when adding children via
409     // the public DOM API (e.g., appendChild()).
410     void checkAddChild(Node* newChild, ExceptionCode&); // Error-checking when adding via the DOM API
411 
412     void checkReplaceChild(Node* newChild, Node* oldChild, ExceptionCode&);
413     virtual bool canReplaceChild(Node* newChild, Node* oldChild);
414 
415     // Used to determine whether range offsets use characters or node indices.
416     virtual bool offsetInCharacters() const;
417     // Number of DOM 16-bit units contained in node. Note that rendered text length can be different - e.g. because of
418     // css-transform:capitalize breaking up precomposed characters and ligatures.
419     virtual int maxCharacterOffset() const;
420 
421     // FIXME: We should try to find a better location for these methods.
canSelectAll()422     virtual bool canSelectAll() const { return false; }
selectAll()423     virtual void selectAll() { }
424 
425     // Whether or not a selection can be started in this object
426     virtual bool canStartSelection() const;
427 
428     // Getting points into and out of screen space
429     FloatPoint convertToPage(const FloatPoint&) const;
430     FloatPoint convertFromPage(const FloatPoint&) const;
431 
432     // -----------------------------------------------------------------------------
433     // Integration with rendering tree
434 
renderer()435     RenderObject* renderer() const { return m_renderer; }
436     RenderObject* nextRenderer();
437     RenderObject* previousRenderer();
setRenderer(RenderObject * renderer)438     void setRenderer(RenderObject* renderer) { m_renderer = renderer; }
439 
440     // Use these two methods with caution.
441     RenderBox* renderBox() const;
442     RenderBoxModelObject* renderBoxModelObject() const;
443 
444     // Attaches this node to the rendering tree. This calculates the style to be applied to the node and creates an
445     // appropriate RenderObject which will be inserted into the tree (except when the style has display: none). This
446     // makes the node visible in the FrameView.
447     virtual void attach();
448 
449     // Detaches the node from the rendering tree, making it invisible in the rendered view. This method will remove
450     // the node's rendering object from the rendering tree and delete it.
451     virtual void detach();
452 
453     virtual void willRemove();
454     void createRendererIfNeeded();
455     PassRefPtr<RenderStyle> styleForRenderer();
456     virtual bool rendererIsNeeded(RenderStyle*);
childShouldCreateRenderer(Node *)457     virtual bool childShouldCreateRenderer(Node*) const { return true; }
458     virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
459     ContainerNode* parentNodeForRenderingAndStyle();
460 
461     // Wrapper for nodes that don't have a renderer, but still cache the style (like HTMLOptionElement).
462     RenderStyle* renderStyle() const;
463     virtual void setRenderStyle(PassRefPtr<RenderStyle>);
464 
465     RenderStyle* computedStyle(PseudoId pseudoElementSpecifier = NOPSEUDO) { return virtualComputedStyle(pseudoElementSpecifier); }
466 
467     // -----------------------------------------------------------------------------
468     // Notification of document structure changes
469 
470     // Notifies the node that it has been inserted into the document. This is called during document parsing, and also
471     // when a node is added through the DOM methods insertBefore(), appendChild() or replaceChild(). Note that this only
472     // happens when the node becomes part of the document tree, i.e. only when the document is actually an ancestor of
473     // the node. The call happens _after_ the node has been added to the tree.
474     //
475     // This is similar to the DOMNodeInsertedIntoDocument DOM event, but does not require the overhead of event
476     // dispatching.
477     virtual void insertedIntoDocument();
478 
479     // Notifies the node that it is no longer part of the document tree, i.e. when the document is no longer an ancestor
480     // node.
481     //
482     // This is similar to the DOMNodeRemovedFromDocument DOM event, but does not require the overhead of event
483     // dispatching, and is called _after_ the node is removed from the tree.
484     virtual void removedFromDocument();
485 
486     // These functions are called whenever you are connected or disconnected from a tree.  That tree may be the main
487     // document tree, or it could be another disconnected tree.  Override these functions to do any work that depends
488     // on connectedness to some ancestor (e.g., an ancestor <form> for example).
insertedIntoTree(bool)489     virtual void insertedIntoTree(bool /*deep*/) { }
removedFromTree(bool)490     virtual void removedFromTree(bool /*deep*/) { }
491 
492     // Notifies the node that it's list of children have changed (either by adding or removing child nodes), or a child
493     // node that is of the type CDATA_SECTION_NODE, TEXT_NODE or COMMENT_NODE has changed its value.
494     virtual void childrenChanged(bool /*changedByParser*/ = false, Node* /*beforeChange*/ = 0, Node* /*afterChange*/ = 0, int /*childCountDelta*/ = 0) { }
495 
496 #ifndef NDEBUG
497     virtual void formatForDebugger(char* buffer, unsigned length) const;
498 
499     void showNode(const char* prefix = "") const;
500     void showTreeForThis() const;
501     void showTreeAndMark(const Node* markedNode1, const char* markedLabel1, const Node* markedNode2 = 0, const char* markedLabel2 = 0) const;
502 #endif
503 
504     void registerDynamicNodeList(DynamicNodeList*);
505     void unregisterDynamicNodeList(DynamicNodeList*);
506     void notifyNodeListsChildrenChanged();
507     void notifyLocalNodeListsChildrenChanged();
508     void notifyNodeListsAttributeChanged();
509     void notifyLocalNodeListsAttributeChanged();
510     void notifyLocalNodeListsLabelChanged();
511     void removeCachedClassNodeList(ClassNodeList*, const String&);
512     void removeCachedNameNodeList(NameNodeList*, const String&);
513     void removeCachedTagNodeList(TagNodeList*, const AtomicString&);
514     void removeCachedTagNodeList(TagNodeList*, const QualifiedName&);
515     void removeCachedLabelsNodeList(DynamicNodeList*);
516 
517     PassRefPtr<NodeList> getElementsByTagName(const AtomicString&);
518     PassRefPtr<NodeList> getElementsByTagNameNS(const AtomicString& namespaceURI, const AtomicString& localName);
519     PassRefPtr<NodeList> getElementsByName(const String& elementName);
520     PassRefPtr<NodeList> getElementsByClassName(const String& classNames);
521 
522     PassRefPtr<Element> querySelector(const String& selectors, ExceptionCode&);
523     PassRefPtr<NodeList> querySelectorAll(const String& selectors, ExceptionCode&);
524 
525     unsigned short compareDocumentPosition(Node*);
526 
toNode()527     virtual Node* toNode() { return this; }
528 
529     virtual InputElement* toInputElement();
530 
531     virtual ScriptExecutionContext* scriptExecutionContext() const;
532 
533     virtual bool addEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, bool useCapture);
534     virtual bool removeEventListener(const AtomicString& eventType, EventListener*, bool useCapture);
535 
536     // Handlers to do/undo actions on the target node before an event is dispatched to it and after the event
537     // has been dispatched.  The data pointer is handed back by the preDispatch and passed to postDispatch.
preDispatchEventHandler(Event *)538     virtual void* preDispatchEventHandler(Event*) { return 0; }
postDispatchEventHandler(Event *,void *)539     virtual void postDispatchEventHandler(Event*, void* /*dataFromPreDispatch*/) { }
540 
541     using EventTarget::dispatchEvent;
542     bool dispatchEvent(PassRefPtr<Event>);
543     void dispatchScopedEvent(PassRefPtr<Event>);
544 
545     virtual void handleLocalEvents(Event*);
546 
547     void dispatchSubtreeModifiedEvent();
548     void dispatchUIEvent(const AtomicString& eventType, int detail, PassRefPtr<Event> underlyingEvent);
549     bool dispatchKeyEvent(const PlatformKeyboardEvent&);
550     bool dispatchWheelEvent(const PlatformWheelEvent&);
551     bool dispatchMouseEvent(const PlatformMouseEvent&, const AtomicString& eventType, int clickCount = 0, Node* relatedTarget = 0);
552     void dispatchSimulatedClick(PassRefPtr<Event> underlyingEvent, bool sendMouseEvents = false, bool showPressedLook = true);
553 
554     virtual void dispatchFocusEvent();
555     virtual void dispatchBlurEvent();
556     virtual void dispatchChangeEvent();
557     virtual void dispatchInputEvent();
558 
559     // Perform the default action for an event.
560     virtual void defaultEventHandler(Event*);
561 
562     // Used for disabled form elements; if true, prevents mouse events from being dispatched
563     // to event listeners, and prevents DOMActivate events from being sent at all.
564     virtual bool disabled() const;
565 
566     using TreeShared<ContainerNode>::ref;
567     using TreeShared<ContainerNode>::deref;
568 
569     virtual EventTargetData* eventTargetData();
570     virtual EventTargetData* ensureEventTargetData();
571 
572 private:
573     enum NodeFlags {
574         IsTextFlag = 1,
575         IsCommentFlag = 1 << 1,
576         IsContainerFlag = 1 << 2,
577         IsElementFlag = 1 << 3,
578         IsStyledElementFlag = 1 << 4,
579         IsHTMLFlag = 1 << 5,
580         IsSVGFlag = 1 << 6,
581         HasIDFlag = 1 << 7,
582         HasClassFlag = 1 << 8,
583         IsAttachedFlag = 1 << 9,
584         ChildNeedsStyleRecalcFlag = 1 << 10,
585         InDocumentFlag = 1 << 11,
586         IsLinkFlag = 1 << 12,
587         IsActiveFlag = 1 << 13,
588         IsHoveredFlag = 1 << 14,
589         InActiveChainFlag = 1 << 15,
590         InDetachFlag = 1 << 16,
591         HasRareDataFlag = 1 << 17,
592         IsShadowRootFlag = 1 << 18,
593 
594         // These bits are used by derived classes, pulled up here so they can
595         // be stored in the same memory word as the Node bits above.
596         IsParsingChildrenFinishedFlag = 1 << 19, // Element
597         IsStyleAttributeValidFlag = 1 << 20, // StyledElement
598         IsSynchronizingStyleAttributeFlag = 1 << 21, // StyledElement
599 #if ENABLE(SVG)
600         AreSVGAttributesValidFlag = 1 << 22, // Element
601         IsSynchronizingSVGAttributesFlag = 1 << 23, // SVGElement
602         HasSVGRareDataFlag = 1 << 24, // SVGElement
603 #endif
604 
605         StyleChangeMask = 1 << nodeStyleChangeShift | 1 << (nodeStyleChangeShift + 1),
606 
607         SelfOrAncestorHasDirAutoFlag = 1 << 27,
608 
609 #if ENABLE(SVG)
610         DefaultNodeFlags = IsParsingChildrenFinishedFlag | IsStyleAttributeValidFlag | AreSVGAttributesValidFlag
611 #else
612         DefaultNodeFlags = IsParsingChildrenFinishedFlag | IsStyleAttributeValidFlag
613 #endif
614     };
615 
616     // 4 bits remaining
617 
getFlag(NodeFlags mask)618     bool getFlag(NodeFlags mask) const { return m_nodeFlags & mask; }
setFlag(bool f,NodeFlags mask)619     void setFlag(bool f, NodeFlags mask) const { m_nodeFlags = (m_nodeFlags & ~mask) | (-(int32_t)f & mask); }
setFlag(NodeFlags mask)620     void setFlag(NodeFlags mask) const { m_nodeFlags |= mask; }
clearFlag(NodeFlags mask)621     void clearFlag(NodeFlags mask) const { m_nodeFlags &= ~mask; }
622 
623 protected:
624     enum ConstructionType {
625         CreateOther = DefaultNodeFlags,
626         CreateText = DefaultNodeFlags | IsTextFlag,
627         CreateComment = DefaultNodeFlags | IsCommentFlag,
628         CreateContainer = DefaultNodeFlags | IsContainerFlag,
629         CreateElement = CreateContainer | IsElementFlag,
630         CreateStyledElement = CreateElement | IsStyledElementFlag,
631         CreateHTMLElement = CreateStyledElement | IsHTMLFlag,
632         CreateSVGElement = CreateStyledElement | IsSVGFlag,
633     };
634     Node(Document*, ConstructionType);
635 
636     // Do not use this method to change the document of a node until after the node has been
637     // removed from its previous document.
638     void setDocument(Document*);
639     void setDocumentRecursively(Document*);
640 
641     virtual void willMoveToNewOwnerDocument();
642     virtual void didMoveToNewOwnerDocument();
643 
addSubresourceAttributeURLs(ListHashSet<KURL> &)644     virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const { }
645     void setTabIndexExplicitly(short);
646     void clearTabIndexExplicitly();
647 
hasRareData()648     bool hasRareData() const { return getFlag(HasRareDataFlag); }
649 
650     NodeRareData* rareData() const;
651     NodeRareData* ensureRareData();
652 
653 private:
654     enum EditableLevel { Editable, RichlyEditable };
655     bool rendererIsEditable(EditableLevel) const;
656 
657     void setStyleChange(StyleChangeType);
658 
659     // Used to share code between lazyAttach and setNeedsStyleRecalc.
660     void markAncestorsWithChildNeedsStyleRecalc();
661 
662     virtual void refEventTarget();
663     virtual void derefEventTarget();
664 
665     virtual NodeRareData* createRareData();
666     bool rareDataFocused() const;
667 
668     virtual RenderStyle* nonRendererRenderStyle() const;
669 
670     virtual const AtomicString& virtualPrefix() const;
671     virtual const AtomicString& virtualLocalName() const;
672     virtual const AtomicString& virtualNamespaceURI() const;
673     virtual RenderStyle* virtualComputedStyle(PseudoId = NOPSEUDO);
674 
675     Element* ancestorElement() const;
676 
677     // Use Node::parentNode as the consistent way of querying a parent node.
678     // This method is made private to ensure a compiler error on call sites that
679     // don't follow this rule.
680     using TreeShared<ContainerNode>::parent;
681 
682     void trackForDebugging();
683 
684     Document* m_document;
685     Node* m_previous;
686     Node* m_next;
687     RenderObject* m_renderer;
688     mutable uint32_t m_nodeFlags;
689 
690 protected:
isParsingChildrenFinished()691     bool isParsingChildrenFinished() const { return getFlag(IsParsingChildrenFinishedFlag); }
setIsParsingChildrenFinished()692     void setIsParsingChildrenFinished() { setFlag(IsParsingChildrenFinishedFlag); }
clearIsParsingChildrenFinished()693     void clearIsParsingChildrenFinished() { clearFlag(IsParsingChildrenFinishedFlag); }
isStyleAttributeValid()694     bool isStyleAttributeValid() const { return getFlag(IsStyleAttributeValidFlag); }
setIsStyleAttributeValid(bool f)695     void setIsStyleAttributeValid(bool f) { setFlag(f, IsStyleAttributeValidFlag); }
setIsStyleAttributeValid()696     void setIsStyleAttributeValid() const { setFlag(IsStyleAttributeValidFlag); }
clearIsStyleAttributeValid()697     void clearIsStyleAttributeValid() { clearFlag(IsStyleAttributeValidFlag); }
isSynchronizingStyleAttribute()698     bool isSynchronizingStyleAttribute() const { return getFlag(IsSynchronizingStyleAttributeFlag); }
setIsSynchronizingStyleAttribute(bool f)699     void setIsSynchronizingStyleAttribute(bool f) { setFlag(f, IsSynchronizingStyleAttributeFlag); }
setIsSynchronizingStyleAttribute()700     void setIsSynchronizingStyleAttribute() const { setFlag(IsSynchronizingStyleAttributeFlag); }
clearIsSynchronizingStyleAttribute()701     void clearIsSynchronizingStyleAttribute() const { clearFlag(IsSynchronizingStyleAttributeFlag); }
702 
703 #if ENABLE(SVG)
areSVGAttributesValid()704     bool areSVGAttributesValid() const { return getFlag(AreSVGAttributesValidFlag); }
setAreSVGAttributesValid()705     void setAreSVGAttributesValid() const { setFlag(AreSVGAttributesValidFlag); }
clearAreSVGAttributesValid()706     void clearAreSVGAttributesValid() { clearFlag(AreSVGAttributesValidFlag); }
isSynchronizingSVGAttributes()707     bool isSynchronizingSVGAttributes() const { return getFlag(IsSynchronizingSVGAttributesFlag); }
setIsSynchronizingSVGAttributes()708     void setIsSynchronizingSVGAttributes() const { setFlag(IsSynchronizingSVGAttributesFlag); }
clearIsSynchronizingSVGAttributes()709     void clearIsSynchronizingSVGAttributes() const { clearFlag(IsSynchronizingSVGAttributesFlag); }
hasRareSVGData()710     bool hasRareSVGData() const { return getFlag(HasSVGRareDataFlag); }
setHasRareSVGData()711     void setHasRareSVGData() { setFlag(HasSVGRareDataFlag); }
clearHasRareSVGData()712     void clearHasRareSVGData() { clearFlag(HasSVGRareDataFlag); }
713 #endif
714 };
715 
716 // Used in Node::addSubresourceAttributeURLs() and in addSubresourceStyleURLs()
addSubresourceURL(ListHashSet<KURL> & urls,const KURL & url)717 inline void addSubresourceURL(ListHashSet<KURL>& urls, const KURL& url)
718 {
719     if (!url.isNull())
720         urls.add(url);
721 }
722 
parentNode()723 inline ContainerNode* Node::parentNode() const
724 {
725     return getFlag(IsShadowRootFlag) || isSVGShadowRoot() ? 0 : parent();
726 }
727 
parentOrHostNode()728 inline ContainerNode* Node::parentOrHostNode() const
729 {
730     return parent();
731 }
732 
parentNodeGuaranteedHostFree()733 inline ContainerNode* Node::parentNodeGuaranteedHostFree() const
734 {
735     ASSERT(!getFlag(IsShadowRootFlag) && !isSVGShadowRoot());
736     return parentOrHostNode();
737 }
738 
739 } //namespace
740 
741 #ifndef NDEBUG
742 // Outside the WebCore namespace for ease of invocation from gdb.
743 void showTree(const WebCore::Node*);
744 #endif
745 
746 #endif
747