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