Tizen 2.1 base
[framework/web/webkit-efl.git] / Source / WebCore / dom / Document.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  *           (C) 2006 Alexey Proskuryakov (ap@webkit.org)
6  * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2012 Apple Inc. All rights reserved.
7  * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
8  * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
9  * Copyright (C) 2011 Google Inc. All rights reserved.
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Library General Public
13  * License as published by the Free Software Foundation; either
14  * version 2 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Library General Public License for more details.
20  *
21  * You should have received a copy of the GNU Library General Public License
22  * along with this library; see the file COPYING.LIB.  If not, write to
23  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24  * Boston, MA 02110-1301, USA.
25  *
26  */
27
28 #ifndef Document_h
29 #define Document_h
30
31 #include "CollectionType.h"
32 #include "Color.h"
33 #include "ContainerNode.h"
34 #include "DOMTimeStamp.h"
35 #include "DocumentEventQueue.h"
36 #include "DocumentTiming.h"
37 #include "IconURL.h"
38 #include "InspectorCounters.h"
39 #include "IntRect.h"
40 #include "LayoutTypes.h"
41 #include "MutationObserver.h"
42 #include "PageVisibilityState.h"
43 #include "PlatformScreen.h"
44 #include "QualifiedName.h"
45 #include "ReferrerPolicy.h"
46 #include "ScriptExecutionContext.h"
47 #include "StringWithDirection.h"
48 #include "Timer.h"
49 #include "TreeScope.h"
50 #include "ViewportArguments.h"
51 #include <wtf/Deque.h>
52 #include <wtf/FixedArray.h>
53 #include <wtf/OwnPtr.h>
54 #include <wtf/PassOwnPtr.h>
55 #include <wtf/PassRefPtr.h>
56
57 namespace WebCore {
58
59 class AXObjectCache;
60 class Attr;
61 class CDATASection;
62 class CSSStyleDeclaration;
63 class CSSStyleSheet;
64 class CachedCSSStyleSheet;
65 class CachedResourceLoader;
66 class CachedScript;
67 class CanvasRenderingContext;
68 class CharacterData;
69 class Comment;
70 class ContextFeatures;
71 class DOMImplementation;
72 class DOMSelection;
73 class DOMWindow;
74 class Database;
75 class DatabaseThread;
76 class DocumentFragment;
77 class DocumentLoader;
78 class DocumentMarkerController;
79 class DocumentParser;
80 class DocumentType;
81 class DocumentWeakReference;
82 class DynamicNodeListCacheBase;
83 class EditingText;
84 class Element;
85 class EntityReference;
86 class Event;
87 class EventListener;
88 class FloatRect;
89 class FloatQuad;
90 class FontData;
91 class FormController;
92 class Frame;
93 class FrameView;
94 class HTMLCanvasElement;
95 class HTMLCollection;
96 class HTMLAllCollection;
97 class HTMLDocument;
98 class HTMLElement;
99 class HTMLFrameOwnerElement;
100 class HTMLHeadElement;
101 class HTMLIFrameElement;
102 class HTMLMapElement;
103 class HTMLNameCollection;
104 class HitTestRequest;
105 class HitTestResult;
106 class IntPoint;
107 class DOMWrapperWorld;
108 class JSNode;
109 class MediaCanStartListener;
110 class MediaQueryList;
111 class MediaQueryMatcher;
112 class MouseEventWithHitTestResults;
113 class NodeFilter;
114 class NodeIterator;
115 class NodeRareData;
116 class Page;
117 class PlatformMouseEvent;
118 class ProcessingInstruction;
119 class Range;
120 class RegisteredEventListener;
121 class RenderArena;
122 class RenderView;
123 class RenderFullScreen;
124 class ScriptableDocumentParser;
125 class ScriptElementData;
126 class ScriptRunner;
127 class SecurityOrigin;
128 class SelectorQueryCache;
129 class SerializedScriptValue;
130 class SegmentedString;
131 class Settings;
132 class StyleResolver;
133 class StyleSheet;
134 class StyleSheetContents;
135 class StyleSheetList;
136 class Text;
137 class TextResourceDecoder;
138 class TreeWalker;
139 class UndoManager;
140 class WebKitNamedFlow;
141 class WebKitNamedFlowCollection;
142 class XMLHttpRequest;
143 class XPathEvaluator;
144 class XPathExpression;
145 class XPathNSResolver;
146 class XPathResult;
147
148 #if ENABLE(SVG)
149 class SVGDocumentExtensions;
150 #endif
151
152 #if ENABLE(XSLT)
153 class TransformSource;
154 #endif
155
156 #if ENABLE(DASHBOARD_SUPPORT)
157 struct DashboardRegionValue;
158 #endif
159
160 #if ENABLE(TOUCH_EVENTS)
161 class Touch;
162 class TouchList;
163 #endif
164
165 #if ENABLE(REQUEST_ANIMATION_FRAME)
166 class RequestAnimationFrameCallback;
167 class ScriptedAnimationController;
168 #endif
169
170 #if ENABLE(MICRODATA)
171 class MicroDataItemList;
172 #endif
173
174 #if ENABLE(LINK_PRERENDER)
175 class Prerenderer;
176 #endif
177
178 #if ENABLE(TEXT_AUTOSIZING)
179 class TextAutosizer;
180 #endif
181
182 #if ENABLE(CSP_NEXT)
183 class DOMSecurityPolicy;
184 #endif
185
186 typedef int ExceptionCode;
187
188 enum PageshowEventPersistence {
189     PageshowEventNotPersisted = 0,
190     PageshowEventPersisted = 1
191 };
192
193 enum StyleResolverUpdateFlag { RecalcStyleImmediately, DeferRecalcStyle, RecalcStyleIfNeeded };
194
195 enum NodeListInvalidationType {
196     DoNotInvalidateOnAttributeChanges = 0,
197     InvalidateOnClassAttrChange,
198     InvalidateOnIdNameAttrChange,
199     InvalidateOnNameAttrChange,
200     InvalidateOnForAttrChange,
201     InvalidateForFormControls,
202     InvalidateOnHRefAttrChange,
203     InvalidateOnItemAttrChange,
204     InvalidateOnAnyAttrChange,
205 };
206 const int numNodeListInvalidationTypes = InvalidateOnAnyAttrChange + 1;
207
208 class Document : public ContainerNode, public TreeScope, public ScriptExecutionContext {
209 public:
210     static PassRefPtr<Document> create(Frame* frame, const KURL& url)
211     {
212         return adoptRef(new Document(frame, url, false, false));
213     }
214     static PassRefPtr<Document> createXHTML(Frame* frame, const KURL& url)
215     {
216         return adoptRef(new Document(frame, url, true, false));
217     }
218     virtual ~Document();
219
220     MediaQueryMatcher* mediaQueryMatcher();
221
222     using ContainerNode::ref;
223     using ContainerNode::deref;
224
225     // Nodes belonging to this document hold guard references -
226     // these are enough to keep the document from being destroyed, but
227     // not enough to keep it from removing its children. This allows a
228     // node that outlives its document to still have a valid document
229     // pointer without introducing reference cycles.
230     void guardRef()
231     {
232         ASSERT(!m_deletionHasBegun);
233         ++m_guardRefCount;
234     }
235
236     void guardDeref()
237     {
238         ASSERT(!m_deletionHasBegun);
239         --m_guardRefCount;
240         if (!m_guardRefCount && !refCount()) {
241 #ifndef NDEBUG
242             m_deletionHasBegun = true;
243 #endif
244             delete this;
245         }
246     }
247
248     Element* getElementById(const AtomicString& id) const;
249
250     virtual bool canContainRangeEndPoint() const { return true; }
251
252     Element* getElementByAccessKey(const String& key);
253     void invalidateAccessKeyMap();
254
255     SelectorQueryCache* selectorQueryCache();
256
257     // DOM methods & attributes for Document
258
259     DEFINE_ATTRIBUTE_EVENT_LISTENER(abort);
260     DEFINE_ATTRIBUTE_EVENT_LISTENER(change);
261     DEFINE_ATTRIBUTE_EVENT_LISTENER(click);
262     DEFINE_ATTRIBUTE_EVENT_LISTENER(contextmenu);
263     DEFINE_ATTRIBUTE_EVENT_LISTENER(dblclick);
264     DEFINE_ATTRIBUTE_EVENT_LISTENER(dragenter);
265     DEFINE_ATTRIBUTE_EVENT_LISTENER(dragover);
266     DEFINE_ATTRIBUTE_EVENT_LISTENER(dragleave);
267     DEFINE_ATTRIBUTE_EVENT_LISTENER(drop);
268     DEFINE_ATTRIBUTE_EVENT_LISTENER(dragstart);
269     DEFINE_ATTRIBUTE_EVENT_LISTENER(drag);
270     DEFINE_ATTRIBUTE_EVENT_LISTENER(dragend);
271     DEFINE_ATTRIBUTE_EVENT_LISTENER(input);
272     DEFINE_ATTRIBUTE_EVENT_LISTENER(invalid);
273     DEFINE_ATTRIBUTE_EVENT_LISTENER(keydown);
274     DEFINE_ATTRIBUTE_EVENT_LISTENER(keypress);
275     DEFINE_ATTRIBUTE_EVENT_LISTENER(keyup);
276     DEFINE_ATTRIBUTE_EVENT_LISTENER(mousedown);
277     DEFINE_ATTRIBUTE_EVENT_LISTENER(mousemove);
278     DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseout);
279     DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseover);
280     DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseup);
281     DEFINE_ATTRIBUTE_EVENT_LISTENER(mousewheel);
282     DEFINE_ATTRIBUTE_EVENT_LISTENER(scroll);
283     DEFINE_ATTRIBUTE_EVENT_LISTENER(select);
284     DEFINE_ATTRIBUTE_EVENT_LISTENER(submit);
285
286     DEFINE_ATTRIBUTE_EVENT_LISTENER(blur);
287     DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
288     DEFINE_ATTRIBUTE_EVENT_LISTENER(focus);
289     DEFINE_ATTRIBUTE_EVENT_LISTENER(load);
290     DEFINE_ATTRIBUTE_EVENT_LISTENER(readystatechange);
291
292     // WebKit extensions
293     DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecut);
294     DEFINE_ATTRIBUTE_EVENT_LISTENER(cut);
295     DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecopy);
296     DEFINE_ATTRIBUTE_EVENT_LISTENER(copy);
297     DEFINE_ATTRIBUTE_EVENT_LISTENER(beforepaste);
298     DEFINE_ATTRIBUTE_EVENT_LISTENER(paste);
299     DEFINE_ATTRIBUTE_EVENT_LISTENER(reset);
300     DEFINE_ATTRIBUTE_EVENT_LISTENER(search);
301     DEFINE_ATTRIBUTE_EVENT_LISTENER(selectstart);
302     DEFINE_ATTRIBUTE_EVENT_LISTENER(selectionchange);
303 #if ENABLE(TOUCH_EVENTS)
304     DEFINE_ATTRIBUTE_EVENT_LISTENER(touchstart);
305     DEFINE_ATTRIBUTE_EVENT_LISTENER(touchmove);
306     DEFINE_ATTRIBUTE_EVENT_LISTENER(touchend);
307     DEFINE_ATTRIBUTE_EVENT_LISTENER(touchcancel);
308 #endif
309 #if ENABLE(FULLSCREEN_API)
310     DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitfullscreenchange);
311     DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitfullscreenerror);
312 #endif
313 #if ENABLE(POINTER_LOCK)
314     DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitpointerlockchange);
315     DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitpointerlockerror);
316 #endif
317 #if ENABLE(PAGE_VISIBILITY_API)
318     DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitvisibilitychange);
319 #endif
320
321     ViewportArguments viewportArguments() const { return m_viewportArguments; }
322 #ifndef NDEBUG
323     bool didDispatchViewportPropertiesChanged() const { return m_didDispatchViewportPropertiesChanged; }
324 #endif
325
326     void setReferrerPolicy(ReferrerPolicy referrerPolicy) { m_referrerPolicy = referrerPolicy; }
327     ReferrerPolicy referrerPolicy() const { return m_referrerPolicy; }
328
329     DocumentType* doctype() const { return m_docType.get(); }
330
331     DOMImplementation* implementation();
332     
333     Element* documentElement() const
334     {
335         return m_documentElement.get();
336     }
337     
338     virtual PassRefPtr<Element> createElement(const AtomicString& tagName, ExceptionCode&);
339     PassRefPtr<DocumentFragment> createDocumentFragment();
340     PassRefPtr<Text> createTextNode(const String& data);
341     PassRefPtr<Comment> createComment(const String& data);
342     PassRefPtr<CDATASection> createCDATASection(const String& data, ExceptionCode&);
343     PassRefPtr<ProcessingInstruction> createProcessingInstruction(const String& target, const String& data, ExceptionCode&);
344     PassRefPtr<Attr> createAttribute(const String& name, ExceptionCode&);
345     PassRefPtr<Attr> createAttributeNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode&, bool shouldIgnoreNamespaceChecks = false);
346     PassRefPtr<EntityReference> createEntityReference(const String& name, ExceptionCode&);
347     PassRefPtr<Node> importNode(Node* importedNode, ExceptionCode& ec) { return importNode(importedNode, true, ec); }
348     PassRefPtr<Node> importNode(Node* importedNode, bool deep, ExceptionCode&);
349     virtual PassRefPtr<Element> createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode&);
350     PassRefPtr<Element> createElement(const QualifiedName&, bool createdByParser);
351
352     bool cssRegionsEnabled() const;
353 #if ENABLE(CSS_REGIONS)
354     PassRefPtr<WebKitNamedFlow> webkitGetFlowByName(const String&);
355 #endif
356
357     WebKitNamedFlowCollection* namedFlows();
358
359     bool regionBasedColumnsEnabled() const;
360
361     bool cssGridLayoutEnabled() const;
362
363     /**
364      * Retrieve all nodes that intersect a rect in the window's document, until it is fully enclosed by
365      * the boundaries of a node.
366      *
367      * @param centerX x reference for the rectangle in CSS pixels
368      * @param centerY y reference for the rectangle in CSS pixels
369      * @param topPadding How much to expand the top of the rectangle
370      * @param rightPadding How much to expand the right of the rectangle
371      * @param bottomPadding How much to expand the bottom of the rectangle
372      * @param leftPadding How much to expand the left of the rectangle
373      * @param ignoreClipping whether or not to ignore the root scroll frame when retrieving the element.
374      *        If false, this method returns null for coordinates outside of the viewport.
375      */
376     PassRefPtr<NodeList> nodesFromRect(int centerX, int centerY, unsigned topPadding, unsigned rightPadding,
377                                        unsigned bottomPadding, unsigned leftPadding, bool ignoreClipping, bool allowShadowContent) const;
378     Element* elementFromPoint(int x, int y) const;
379     PassRefPtr<Range> caretRangeFromPoint(int x, int y);
380
381     String readyState() const;
382
383     String defaultCharset() const;
384
385     String inputEncoding() const { return Document::encoding(); }
386     String charset() const { return Document::encoding(); }
387     String characterSet() const { return Document::encoding(); }
388
389     String encoding() const;
390
391     void setCharset(const String&);
392
393     void setContent(const String&);
394
395     String suggestedMIMEType() const;
396
397     String contentLanguage() const { return m_contentLanguage; }
398     void setContentLanguage(const String&);
399
400     String xmlEncoding() const { return m_xmlEncoding; }
401     String xmlVersion() const { return m_xmlVersion; }
402     enum StandaloneStatus { StandaloneUnspecified, Standalone, NotStandalone };
403     bool xmlStandalone() const { return m_xmlStandalone == Standalone; }
404     StandaloneStatus xmlStandaloneStatus() const { return static_cast<StandaloneStatus>(m_xmlStandalone); }
405     bool hasXMLDeclaration() const { return m_hasXMLDeclaration; }
406
407     void setXMLEncoding(const String& encoding) { m_xmlEncoding = encoding; } // read-only property, only to be set from XMLDocumentParser
408     void setXMLVersion(const String&, ExceptionCode&);
409     void setXMLStandalone(bool, ExceptionCode&);
410     void setHasXMLDeclaration(bool hasXMLDeclaration) { m_hasXMLDeclaration = hasXMLDeclaration ? 1 : 0; }
411
412     String documentURI() const { return m_documentURI; }
413     void setDocumentURI(const String&);
414
415     virtual KURL baseURI() const;
416
417 #if ENABLE(PAGE_VISIBILITY_API)
418     String webkitVisibilityState() const;
419     bool webkitHidden() const;
420     void dispatchVisibilityStateChangeEvent();
421 #endif
422
423 #if ENABLE(CSP_NEXT)
424     DOMSecurityPolicy* securityPolicy();
425 #endif
426
427     PassRefPtr<Node> adoptNode(PassRefPtr<Node> source, ExceptionCode&);
428
429     PassRefPtr<HTMLCollection> images();
430     PassRefPtr<HTMLCollection> embeds();
431     PassRefPtr<HTMLCollection> plugins(); // an alias for embeds() required for the JS DOM bindings.
432     PassRefPtr<HTMLCollection> applets();
433     PassRefPtr<HTMLCollection> links();
434     PassRefPtr<HTMLCollection> forms();
435     PassRefPtr<HTMLCollection> anchors();
436     PassRefPtr<HTMLCollection> objects();
437     PassRefPtr<HTMLCollection> scripts();
438     PassRefPtr<HTMLCollection> all();
439     void removeCachedHTMLCollection(HTMLCollection*, CollectionType);
440
441     PassRefPtr<HTMLCollection> windowNamedItems(const AtomicString& name);
442     PassRefPtr<HTMLCollection> documentNamedItems(const AtomicString& name);
443     void removeWindowNamedItemCache(HTMLCollection*, const AtomicString&);
444     void removeDocumentNamedItemCache(HTMLCollection*, const AtomicString&);
445
446     // Other methods (not part of DOM)
447     bool isHTMLDocument() const { return m_isHTML; }
448     bool isXHTMLDocument() const { return m_isXHTML; }
449     virtual bool isImageDocument() const { return false; }
450 #if ENABLE(SVG)
451     virtual bool isSVGDocument() const { return false; }
452     bool hasSVGRootNode() const;
453 #else
454     static bool isSVGDocument() { return false; }
455     static bool hasSVGRootNode() { return false; }
456 #endif
457     virtual bool isPluginDocument() const { return false; }
458     virtual bool isMediaDocument() const { return false; }
459     virtual bool isFrameSet() const { return false; }
460
461     bool isSrcdocDocument() const { return m_isSrcdocDocument; }
462
463     NodeRareData* documentRareData() const { return m_documentRareData; };
464     void setDocumentRareData(NodeRareData*);
465
466     StyleResolver* styleResolverIfExists() const { return m_styleResolver.get(); }
467
468     bool isViewSource() const { return m_isViewSource; }
469     void setIsViewSource(bool);
470
471     bool sawElementsInKnownNamespaces() const { return m_sawElementsInKnownNamespaces; }
472
473     StyleResolver* styleResolver()
474     { 
475         if (!m_styleResolver)
476             createStyleResolver();
477         return m_styleResolver.get();
478     }
479
480     /**
481      * Updates the pending sheet count and then calls updateActiveStylesheets.
482      */
483     void removePendingSheet();
484
485     /**
486      * This method returns true if all top-level stylesheets have loaded (including
487      * any @imports that they may be loading).
488      */
489     bool haveStylesheetsLoaded() const
490     {
491         return m_pendingStylesheets <= 0 || m_ignorePendingStylesheets;
492     }
493
494     /**
495      * Increments the number of pending sheets.  The <link> elements
496      * invoke this to add themselves to the loading list.
497      */
498     void addPendingSheet() { m_pendingStylesheets++; }
499
500     void addStyleSheetCandidateNode(Node*, bool createdByParser);
501     void removeStyleSheetCandidateNode(Node*);
502
503     bool gotoAnchorNeededAfterStylesheetsLoad() { return m_gotoAnchorNeededAfterStylesheetsLoad; }
504     void setGotoAnchorNeededAfterStylesheetsLoad(bool b) { m_gotoAnchorNeededAfterStylesheetsLoad = b; }
505
506     /**
507      * Called when one or more stylesheets in the document may have been added, removed or changed.
508      *
509      * Creates a new style resolver and assign it to this document. This is done by iterating through all nodes in
510      * document (or those before <BODY> in a HTML document), searching for stylesheets. Stylesheets can be contained in
511      * <LINK>, <STYLE> or <BODY> elements, as well as processing instructions (XML documents only). A list is
512      * constructed from these which is used to create the a new style selector which collates all of the stylesheets
513      * found and is used to calculate the derived styles for all rendering objects.
514      */
515     void styleResolverChanged(StyleResolverUpdateFlag);
516
517     void evaluateMediaQueryList();
518
519     bool usesSiblingRules() const { return m_usesSiblingRules || m_usesSiblingRulesOverride; }
520     void setUsesSiblingRules(bool b) { m_usesSiblingRulesOverride = b; }
521     bool usesFirstLineRules() const { return m_usesFirstLineRules; }
522     bool usesFirstLetterRules() const { return m_usesFirstLetterRules; }
523     void setUsesFirstLetterRules(bool b) { m_usesFirstLetterRules = b; }
524     bool usesBeforeAfterRules() const { return m_usesBeforeAfterRules || m_usesBeforeAfterRulesOverride; }
525     void setUsesBeforeAfterRules(bool b) { m_usesBeforeAfterRulesOverride = b; }
526     bool usesRemUnits() const { return m_usesRemUnits; }
527     bool usesLinkRules() const { return linkColor() != visitedLinkColor() || m_usesLinkRules; }
528     void setUsesLinkRules(bool b) { m_usesLinkRules = b; }
529
530     // Never returns 0.
531     FormController* formController();
532     Vector<String> formElementsState() const;
533     void setStateForNewFormElements(const Vector<String>&);
534
535     FrameView* view() const; // can be NULL
536     Frame* frame() const { return m_frame; } // can be NULL
537     Page* page() const; // can be NULL
538     Settings* settings() const; // can be NULL
539
540     PassRefPtr<Range> createRange();
541
542     PassRefPtr<NodeIterator> createNodeIterator(Node* root, unsigned whatToShow,
543         PassRefPtr<NodeFilter>, bool expandEntityReferences, ExceptionCode&);
544
545     PassRefPtr<TreeWalker> createTreeWalker(Node* root, unsigned whatToShow, 
546         PassRefPtr<NodeFilter>, bool expandEntityReferences, ExceptionCode&);
547
548     // Special support for editing
549     PassRefPtr<CSSStyleDeclaration> createCSSStyleDeclaration();
550     PassRefPtr<EditingText> createEditingTextNode(const String&);
551
552     void recalcStyle(StyleChange = NoChange);
553     bool childNeedsAndNotInStyleRecalc();
554     virtual void updateStyleIfNeeded();
555     void updateLayout();
556     void updateLayoutIgnorePendingStylesheets();
557     PassRefPtr<RenderStyle> styleForElementIgnoringPendingStylesheets(Element*);
558     PassRefPtr<RenderStyle> styleForPage(int pageIndex);
559
560     void registerCustomFont(PassOwnPtr<FontData>);
561
562     // Returns true if page box (margin boxes and page borders) is visible.
563     bool isPageBoxVisible(int pageIndex);
564
565     // Returns the preferred page size and margins in pixels, assuming 96
566     // pixels per inch. pageSize, marginTop, marginRight, marginBottom,
567     // marginLeft must be initialized to the default values that are used if
568     // auto is specified.
569     void pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft);
570
571     static void updateStyleForAllDocuments(); // FIXME: Try to reduce the # of calls to this function.
572     CachedResourceLoader* cachedResourceLoader() { return m_cachedResourceLoader.get(); }
573
574     virtual void attach();
575     virtual void detach();
576     void prepareForDestruction();
577
578     // Override ScriptExecutionContext methods to do additional work
579     virtual void suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension) OVERRIDE;
580     virtual void resumeActiveDOMObjects() OVERRIDE;
581
582     RenderArena* renderArena() { return m_renderArena.get(); }
583
584     RenderView* renderView() const;
585
586     void clearAXObjectCache();
587     AXObjectCache* axObjectCache() const;
588     bool axObjectCacheExists() const;
589     
590     // to get visually ordered hebrew and arabic pages right
591     void setVisuallyOrdered();
592     bool visuallyOrdered() const { return m_visuallyOrdered; }
593     
594     DocumentLoader* loader() const;
595
596     void open(Document* ownerDocument = 0);
597     void implicitOpen();
598
599     // close() is the DOM API document.close()
600     void close();
601     // In some situations (see the code), we ignore document.close().
602     // explicitClose() bypass these checks and actually tries to close the
603     // input stream.
604     void explicitClose();
605     // implicitClose() actually does the work of closing the input stream.
606     void implicitClose();
607
608     void cancelParsing();
609
610     void write(const SegmentedString& text, Document* ownerDocument = 0);
611     void write(const String& text, Document* ownerDocument = 0);
612     void writeln(const String& text, Document* ownerDocument = 0);
613
614     bool wellFormed() const { return m_wellFormed; }
615
616     const KURL& url() const { return m_url; }
617     void setURL(const KURL&);
618
619     // To understand how these concepts relate to one another, please see the
620     // comments surrounding their declaration.
621     const KURL& baseURL() const { return m_baseURL; }
622     void setBaseURLOverride(const KURL&);
623     const KURL& baseURLOverride() const { return m_baseURLOverride; }
624     const KURL& baseElementURL() const { return m_baseElementURL; }
625     const String& baseTarget() const { return m_baseTarget; }
626     void processBaseElement();
627
628     KURL completeURL(const String&) const;
629     KURL completeURL(const String&, const KURL& baseURLOverride) const;
630
631     virtual String userAgent(const KURL&) const;
632
633     virtual void disableEval();
634
635     bool canNavigate(Frame* targetFrame);
636     Frame* findUnsafeParentScrollPropagationBoundary();
637
638     CSSStyleSheet* pageUserSheet();
639     void clearPageUserSheet();
640     void updatePageUserSheet();
641
642     const Vector<RefPtr<CSSStyleSheet> >* pageGroupUserSheets() const;
643     void clearPageGroupUserSheets();
644     void updatePageGroupUserSheets();
645
646     const Vector<RefPtr<CSSStyleSheet> >* documentUserSheets() const { return m_userSheets.get(); }
647     void addUserSheet(PassRefPtr<StyleSheetContents> userSheet);
648
649     CSSStyleSheet* elementSheet();
650     
651     virtual PassRefPtr<DocumentParser> createParser();
652     DocumentParser* parser() const { return m_parser.get(); }
653     ScriptableDocumentParser* scriptableDocumentParser() const;
654     
655     bool printing() const { return m_printing; }
656     void setPrinting(bool p) { m_printing = p; }
657
658     bool paginatedForScreen() const { return m_paginatedForScreen; }
659     void setPaginatedForScreen(bool p) { m_paginatedForScreen = p; }
660     
661     bool paginated() const { return printing() || paginatedForScreen(); }
662
663     enum CompatibilityMode { QuirksMode, LimitedQuirksMode, NoQuirksMode };
664
665     virtual void setCompatibilityModeFromDoctype() { }
666     void setCompatibilityMode(CompatibilityMode m);
667     void lockCompatibilityMode() { m_compatibilityModeLocked = true; }
668     CompatibilityMode compatibilityMode() const { return m_compatibilityMode; }
669
670     String compatMode() const;
671
672     bool inQuirksMode() const { return m_compatibilityMode == QuirksMode; }
673     bool inLimitedQuirksMode() const { return m_compatibilityMode == LimitedQuirksMode; }
674     bool inNoQuirksMode() const { return m_compatibilityMode == NoQuirksMode; }
675
676     enum ReadyState {
677         Loading,
678         Interactive,
679         Complete
680     };
681     void setReadyState(ReadyState);
682     void setParsing(bool);
683     bool parsing() const { return m_bParsing; }
684     int minimumLayoutDelay();
685
686     bool shouldScheduleLayout();
687     bool isLayoutTimerActive();
688     int elapsedTime() const;
689     
690     void setTextColor(const Color& color) { m_textColor = color; }
691     Color textColor() const { return m_textColor; }
692
693     const Color& linkColor() const { return m_linkColor; }
694     const Color& visitedLinkColor() const { return m_visitedLinkColor; }
695     const Color& activeLinkColor() const { return m_activeLinkColor; }
696     void setLinkColor(const Color& c) { m_linkColor = c; }
697     void setVisitedLinkColor(const Color& c) { m_visitedLinkColor = c; }
698     void setActiveLinkColor(const Color& c) { m_activeLinkColor = c; }
699     void resetLinkColor();
700     void resetVisitedLinkColor();
701     void resetActiveLinkColor();
702     
703     MouseEventWithHitTestResults prepareMouseEvent(const HitTestRequest&, const LayoutPoint&, const PlatformMouseEvent&);
704
705     StyleSheetList* styleSheets();
706
707     /* Newly proposed CSS3 mechanism for selecting alternate
708        stylesheets using the DOM. May be subject to change as
709        spec matures. - dwh
710     */
711     String preferredStylesheetSet() const;
712     String selectedStylesheetSet() const;
713     void setSelectedStylesheetSet(const String&);
714
715     bool setFocusedNode(PassRefPtr<Node>);
716     Node* focusedNode() const { return m_focusedNode.get(); }
717
718     void getFocusableNodes(Vector<RefPtr<Node> >&);
719     
720     // The m_ignoreAutofocus flag specifies whether or not the document has been changed by the user enough 
721     // for WebCore to ignore the autofocus attribute on any form controls
722     bool ignoreAutofocus() const { return m_ignoreAutofocus; };
723     void setIgnoreAutofocus(bool shouldIgnore = true) { m_ignoreAutofocus = shouldIgnore; };
724
725     void setHoverNode(PassRefPtr<Node>);
726     Node* hoverNode() const { return m_hoverNode.get(); }
727
728     void setActiveNode(PassRefPtr<Node>);
729     Node* activeNode() const { return m_activeNode.get(); }
730
731     void focusedNodeRemoved();
732     void removeFocusedNodeOfSubtree(Node*, bool amongChildrenOnly = false);
733     void hoveredNodeDetached(Node*);
734     void activeChainNodeDetached(Node*);
735
736     // Updates for :target (CSS3 selector).
737     void setCSSTarget(Element*);
738     Element* cssTarget() const { return m_cssTarget; }
739     
740     void scheduleForcedStyleRecalc();
741     void scheduleStyleRecalc();
742     void unscheduleStyleRecalc();
743     bool isPendingStyleRecalc() const;
744     void styleRecalcTimerFired(Timer<Document>*);
745
746     void registerNodeListCache(DynamicNodeListCacheBase*);
747     void unregisterNodeListCache(DynamicNodeListCacheBase*);
748     bool shouldInvalidateNodeListCaches(const QualifiedName* attrName = 0) const;
749     void invalidateNodeListCaches(const QualifiedName* attrName);
750
751     void attachNodeIterator(NodeIterator*);
752     void detachNodeIterator(NodeIterator*);
753     void moveNodeIteratorsToNewDocument(Node*, Document*);
754
755     void attachRange(Range*);
756     void detachRange(Range*);
757
758     void updateRangesAfterChildrenChanged(ContainerNode*);
759     // nodeChildrenWillBeRemoved is used when removing all node children at once.
760     void nodeChildrenWillBeRemoved(ContainerNode*);
761     // nodeWillBeRemoved is only safe when removing one node at a time.
762     void nodeWillBeRemoved(Node*);
763
764     void textInserted(Node*, unsigned offset, unsigned length);
765     void textRemoved(Node*, unsigned offset, unsigned length);
766     void textNodesMerged(Text* oldNode, unsigned offset);
767     void textNodeSplit(Text* oldNode);
768
769     DOMWindow* defaultView() const { return domWindow(); } 
770     DOMWindow* domWindow() const;
771
772     // Helper functions for forwarding DOMWindow event related tasks to the DOMWindow if it exists.
773     void setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener>);
774     EventListener* getWindowAttributeEventListener(const AtomicString& eventType);
775     void dispatchWindowEvent(PassRefPtr<Event>, PassRefPtr<EventTarget> = 0);
776     void dispatchWindowLoadEvent();
777
778     PassRefPtr<Event> createEvent(const String& eventType, ExceptionCode&);
779
780     // keep track of what types of event listeners are registered, so we don't
781     // dispatch events unnecessarily
782     enum ListenerType {
783         DOMSUBTREEMODIFIED_LISTENER          = 0x01,
784         DOMNODEINSERTED_LISTENER             = 0x02,
785         DOMNODEREMOVED_LISTENER              = 0x04,
786         DOMNODEREMOVEDFROMDOCUMENT_LISTENER  = 0x08,
787         DOMNODEINSERTEDINTODOCUMENT_LISTENER = 0x10,
788         DOMATTRMODIFIED_LISTENER             = 0x20,
789         DOMCHARACTERDATAMODIFIED_LISTENER    = 0x40,
790         OVERFLOWCHANGED_LISTENER             = 0x80,
791         ANIMATIONEND_LISTENER                = 0x100,
792         ANIMATIONSTART_LISTENER              = 0x200,
793         ANIMATIONITERATION_LISTENER          = 0x400,
794         TRANSITIONEND_LISTENER               = 0x800,
795         BEFORELOAD_LISTENER                  = 0x1000,
796         TOUCH_LISTENER                       = 0x2000,
797         SCROLL_LISTENER                      = 0x4000,
798         REGIONLAYOUTUPDATE_LISTENER          = 0x8000
799     };
800
801     bool hasListenerType(ListenerType listenerType) const { return (m_listenerTypes & listenerType); }
802     void addListenerType(ListenerType listenerType) { m_listenerTypes = m_listenerTypes | listenerType; }
803     void addListenerTypeIfNeeded(const AtomicString& eventType);
804
805 #if ENABLE(TIZEN_PLUGIN_TOUCH_EVENT)
806     void removeListenerType(const AtomicString& eventType);
807 #endif
808
809 #if ENABLE(MUTATION_OBSERVERS)
810     bool hasMutationObserversOfType(MutationObserver::MutationType type) const
811     {
812         return m_mutationObserverTypes & type;
813     }
814     bool hasMutationObservers() const { return m_mutationObserverTypes; }
815     void addMutationObserverTypes(MutationObserverOptions types) { m_mutationObserverTypes |= types; }
816 #endif
817
818     CSSStyleDeclaration* getOverrideStyle(Element*, const String& pseudoElt);
819
820     int nodeAbsIndex(Node*);
821     Node* nodeWithAbsIndex(int absIndex);
822
823     /**
824      * Handles a HTTP header equivalent set by a meta tag using <meta http-equiv="..." content="...">. This is called
825      * when a meta tag is encountered during document parsing, and also when a script dynamically changes or adds a meta
826      * tag. This enables scripts to use meta tags to perform refreshes and set expiry dates in addition to them being
827      * specified in a HTML file.
828      *
829      * @param equiv The http header name (value of the meta tag's "equiv" attribute)
830      * @param content The header value (value of the meta tag's "content" attribute)
831      */
832     void processHttpEquiv(const String& equiv, const String& content);
833     void processViewport(const String& features, ViewportArguments::Type origin);
834     void updateViewportArguments();
835     void processReferrerPolicy(const String& policy);
836
837     // Returns the owning element in the parent document.
838     // Returns 0 if this is the top level document.
839     HTMLFrameOwnerElement* ownerElement() const;
840
841     HTMLIFrameElement* seamlessParentIFrame() const;
842     bool shouldDisplaySeamlesslyWithParent() const;
843
844     // Used by DOM bindings; no direction known.
845     String title() const { return m_title.string(); }
846     void setTitle(const String&);
847
848     void setTitleElement(const StringWithDirection&, Element* titleElement);
849     void removeTitle(Element* titleElement);
850
851     String cookie(ExceptionCode&) const;
852     void setCookie(const String&, ExceptionCode&);
853
854     String referrer() const;
855
856     String domain() const;
857     void setDomain(const String& newDomain, ExceptionCode&);
858
859     String lastModified() const;
860
861     // The cookieURL is used to query the cookie database for this document's
862     // cookies. For example, if the cookie URL is http://example.com, we'll
863     // use the non-Secure cookies for example.com when computing
864     // document.cookie.
865     //
866     // Q: How is the cookieURL different from the document's URL?
867     // A: The two URLs are the same almost all the time.  However, if one
868     //    document inherits the security context of another document, it
869     //    inherits its cookieURL but not its URL.
870     //
871     const KURL& cookieURL() const { return m_cookieURL; }
872     void setCookieURL(const KURL& url) { m_cookieURL = url; }
873
874     // The firstPartyForCookies is used to compute whether this document
875     // appears in a "third-party" context for the purpose of third-party
876     // cookie blocking.  The document is in a third-party context if the
877     // cookieURL and the firstPartyForCookies are from different hosts.
878     //
879     // Note: Some ports (including possibly Apple's) only consider the
880     //       document in a third-party context if the cookieURL and the
881     //       firstPartyForCookies have a different registry-controlled
882     //       domain.
883     //
884     const KURL& firstPartyForCookies() const { return m_firstPartyForCookies; }
885     void setFirstPartyForCookies(const KURL& url) { m_firstPartyForCookies = url; }
886     
887     // The following implements the rule from HTML 4 for what valid names are.
888     // To get this right for all the XML cases, we probably have to improve this or move it
889     // and make it sensitive to the type of document.
890     static bool isValidName(const String&);
891
892     // The following breaks a qualified name into a prefix and a local name.
893     // It also does a validity check, and returns false if the qualified name
894     // is invalid.  It also sets ExceptionCode when name is invalid.
895     static bool parseQualifiedName(const String& qualifiedName, String& prefix, String& localName, ExceptionCode&);
896
897     // Checks to make sure prefix and namespace do not conflict (per DOM Core 3)
898     static bool hasValidNamespaceForElements(const QualifiedName&);
899     static bool hasValidNamespaceForAttributes(const QualifiedName&);
900
901     HTMLElement* body() const;
902     void setBody(PassRefPtr<HTMLElement>, ExceptionCode&);
903
904     HTMLHeadElement* head();
905
906     DocumentMarkerController* markers() const { return m_markers.get(); }
907
908     bool directionSetOnDocumentElement() const { return m_directionSetOnDocumentElement; }
909     bool writingModeSetOnDocumentElement() const { return m_writingModeSetOnDocumentElement; }
910     void setDirectionSetOnDocumentElement(bool b) { m_directionSetOnDocumentElement = b; }
911     void setWritingModeSetOnDocumentElement(bool b) { m_writingModeSetOnDocumentElement = b; }
912
913     bool execCommand(const String& command, bool userInterface = false, const String& value = String());
914     bool queryCommandEnabled(const String& command);
915     bool queryCommandIndeterm(const String& command);
916     bool queryCommandState(const String& command);
917     bool queryCommandSupported(const String& command);
918     String queryCommandValue(const String& command);
919
920     KURL openSearchDescriptionURL();
921
922     // designMode support
923     enum InheritedBool { off = false, on = true, inherit };    
924     void setDesignMode(InheritedBool value);
925     InheritedBool getDesignMode() const;
926     bool inDesignMode() const;
927
928     Document* parentDocument() const;
929     Document* topDocument() const;
930
931     int docID() const { return m_docID; }
932     
933     ScriptRunner* scriptRunner() { return m_scriptRunner.get(); }
934
935 #if ENABLE(XSLT)
936     void applyXSLTransform(ProcessingInstruction* pi);
937     PassRefPtr<Document> transformSourceDocument() { return m_transformSourceDocument; }
938     void setTransformSourceDocument(Document* doc) { m_transformSourceDocument = doc; }
939
940     void setTransformSource(PassOwnPtr<TransformSource>);
941     TransformSource* transformSource() const { return m_transformSource.get(); }
942 #endif
943
944     void incDOMTreeVersion() { m_domTreeVersion = ++s_globalTreeVersion; }
945     uint64_t domTreeVersion() const { return m_domTreeVersion; }
946
947     void setDocType(PassRefPtr<DocumentType>);
948
949     // XPathEvaluator methods
950     PassRefPtr<XPathExpression> createExpression(const String& expression,
951                                                  XPathNSResolver* resolver,
952                                                  ExceptionCode& ec);
953     PassRefPtr<XPathNSResolver> createNSResolver(Node *nodeResolver);
954     PassRefPtr<XPathResult> evaluate(const String& expression,
955                                      Node* contextNode,
956                                      XPathNSResolver* resolver,
957                                      unsigned short type,
958                                      XPathResult* result,
959                                      ExceptionCode& ec);
960
961     enum PendingSheetLayout { NoLayoutWithPendingSheets, DidLayoutWithPendingSheets, IgnoreLayoutWithPendingSheets };
962
963     bool didLayoutWithPendingStylesheets() const { return m_pendingSheetLayout == DidLayoutWithPendingSheets; }
964     
965     void setHasNodesWithPlaceholderStyle() { m_hasNodesWithPlaceholderStyle = true; }
966
967     const Vector<IconURL>& iconURLs();
968     void addIconURL(const String& url, const String& mimeType, const String& size, IconType);
969
970     void setUseSecureKeyboardEntryWhenActive(bool);
971     bool useSecureKeyboardEntryWhenActive() const;
972
973     void updateFocusAppearanceSoon(bool restorePreviousSelection);
974     void cancelFocusAppearanceUpdate();
975         
976     // Extension for manipulating canvas drawing contexts for use in CSS
977     CanvasRenderingContext* getCSSCanvasContext(const String& type, const String& name, int width, int height);
978     HTMLCanvasElement* getCSSCanvasElement(const String& name);
979
980     bool isDNSPrefetchEnabled() const { return m_isDNSPrefetchEnabled; }
981     void parseDNSPrefetchControlHeader(const String&);
982
983     virtual void postTask(PassOwnPtr<Task>); // Executes the task on context's thread asynchronously.
984
985     virtual void suspendScriptedAnimationControllerCallbacks();
986     virtual void resumeScriptedAnimationControllerCallbacks();
987     
988     void windowScreenDidChange(PlatformDisplayID);
989
990     virtual void finishedParsing();
991
992     bool inPageCache() const { return m_inPageCache; }
993     void setInPageCache(bool flag);
994
995     // Elements can register themselves for the "documentWillSuspendForPageCache()" and  
996     // "documentDidResumeFromPageCache()" callbacks
997     void registerForPageCacheSuspensionCallbacks(Element*);
998     void unregisterForPageCacheSuspensionCallbacks(Element*);
999
1000     void documentWillBecomeInactive();
1001     void documentWillSuspendForPageCache();
1002     void documentDidResumeFromPageCache();
1003
1004     void registerForMediaVolumeCallbacks(Element*);
1005     void unregisterForMediaVolumeCallbacks(Element*);
1006     void mediaVolumeDidChange();
1007
1008     void registerForPrivateBrowsingStateChangedCallbacks(Element*);
1009     void unregisterForPrivateBrowsingStateChangedCallbacks(Element*);
1010     void privateBrowsingStateDidChange();
1011
1012     void setShouldCreateRenderers(bool);
1013     bool shouldCreateRenderers();
1014
1015     void setDecoder(PassRefPtr<TextResourceDecoder>);
1016     TextResourceDecoder* decoder() const { return m_decoder.get(); }
1017
1018     String displayStringModifiedByEncoding(const String&) const;
1019     PassRefPtr<StringImpl> displayStringModifiedByEncoding(PassRefPtr<StringImpl>) const;
1020     void displayBufferModifiedByEncoding(UChar* buffer, unsigned len) const;
1021
1022     // Quirk for the benefit of Apple's Dictionary application.
1023     void setFrameElementsShouldIgnoreScrolling(bool ignore) { m_frameElementsShouldIgnoreScrolling = ignore; }
1024     bool frameElementsShouldIgnoreScrolling() const { return m_frameElementsShouldIgnoreScrolling; }
1025
1026 #if ENABLE(DASHBOARD_SUPPORT)
1027     void setDashboardRegionsDirty(bool f) { m_dashboardRegionsDirty = f; }
1028     bool dashboardRegionsDirty() const { return m_dashboardRegionsDirty; }
1029     bool hasDashboardRegions () const { return m_hasDashboardRegions; }
1030     void setHasDashboardRegions(bool f) { m_hasDashboardRegions = f; }
1031     const Vector<DashboardRegionValue>& dashboardRegions() const;
1032     void setDashboardRegions(const Vector<DashboardRegionValue>&);
1033 #endif
1034
1035     virtual void removeAllEventListeners();
1036
1037 #if ENABLE(SVG)
1038     const SVGDocumentExtensions* svgExtensions();
1039     SVGDocumentExtensions* accessSVGExtensions();
1040 #endif
1041
1042     void initSecurityContext();
1043     void initContentSecurityPolicy();
1044
1045     void updateURLForPushOrReplaceState(const KURL&);
1046     void statePopped(PassRefPtr<SerializedScriptValue>);
1047
1048     bool processingLoadEvent() const { return m_processingLoadEvent; }
1049     bool loadEventFinished() const { return m_loadEventFinished; }
1050
1051     virtual bool isContextThread() const;
1052     virtual bool isJSExecutionForbidden() const { return false; }
1053
1054     bool containsValidityStyleRules() const { return m_containsValidityStyleRules; }
1055     void setContainsValidityStyleRules() { m_containsValidityStyleRules = true; }
1056
1057     void enqueueWindowEvent(PassRefPtr<Event>);
1058     void enqueueDocumentEvent(PassRefPtr<Event>);
1059     void enqueuePageshowEvent(PageshowEventPersistence);
1060     void enqueueHashchangeEvent(const String& oldURL, const String& newURL);
1061     void enqueuePopstateEvent(PassRefPtr<SerializedScriptValue> stateObject);
1062     virtual DocumentEventQueue* eventQueue() const { return m_eventQueue.get(); }
1063
1064     void addMediaCanStartListener(MediaCanStartListener*);
1065     void removeMediaCanStartListener(MediaCanStartListener*);
1066     MediaCanStartListener* takeAnyMediaCanStartListener();
1067
1068     const QualifiedName& idAttributeName() const { return m_idAttributeName; }
1069     
1070 #if ENABLE(FULLSCREEN_API)
1071     bool webkitIsFullScreen() const { return m_fullScreenElement.get(); }
1072     bool webkitFullScreenKeyboardInputAllowed() const { return m_fullScreenElement.get() && m_areKeysEnabledInFullScreen; }
1073     Element* webkitCurrentFullScreenElement() const { return m_fullScreenElement.get(); }
1074     
1075     enum FullScreenCheckType {
1076         EnforceIFrameAllowFullScreenRequirement,
1077         ExemptIFrameAllowFullScreenRequirement,
1078     };
1079
1080     void requestFullScreenForElement(Element*, unsigned short flags, FullScreenCheckType);
1081     void webkitCancelFullScreen();
1082     
1083     void webkitWillEnterFullScreenForElement(Element*);
1084     void webkitDidEnterFullScreenForElement(Element*);
1085     void webkitWillExitFullScreenForElement(Element*);
1086     void webkitDidExitFullScreenForElement(Element*);
1087     
1088     void setFullScreenRenderer(RenderFullScreen*);
1089     RenderFullScreen* fullScreenRenderer() const { return m_fullScreenRenderer; }
1090     void fullScreenRendererDestroyed();
1091     
1092     void setFullScreenRendererSize(const IntSize&);
1093     void setFullScreenRendererBackgroundColor(Color);
1094     
1095     void fullScreenChangeDelayTimerFired(Timer<Document>*);
1096     bool fullScreenIsAllowedForElement(Element*) const;
1097     void fullScreenElementRemoved();
1098     void removeFullScreenElementOfSubtree(Node*, bool amongChildrenOnly = false);
1099     bool isAnimatingFullScreen() const;
1100     void setAnimatingFullScreen(bool);
1101
1102     // W3C API
1103     bool webkitFullscreenEnabled() const;
1104     Element* webkitFullscreenElement() const { return !m_fullScreenElementStack.isEmpty() ? m_fullScreenElementStack.first().get() : 0; }
1105     void webkitExitFullscreen();
1106 #endif
1107
1108 #if ENABLE(POINTER_LOCK)
1109     void webkitExitPointerLock();
1110     Element* webkitPointerLockElement() const;
1111 #endif
1112
1113     // Used to allow element that loads data without going through a FrameLoader to delay the 'load' event.
1114     void incrementLoadEventDelayCount() { ++m_loadEventDelayCount; }
1115     void decrementLoadEventDelayCount();
1116     bool isDelayingLoadEvent() const { return m_loadEventDelayCount; }
1117
1118 #if ENABLE(TOUCH_EVENTS)
1119     PassRefPtr<Touch> createTouch(DOMWindow*, EventTarget*, int identifier, int pageX, int pageY, int screenX, int screenY, int radiusX, int radiusY, float rotationAngle, float force, ExceptionCode&) const;
1120 #endif
1121
1122     const DocumentTiming* timing() const { return &m_documentTiming; }
1123
1124 #if ENABLE(REQUEST_ANIMATION_FRAME)
1125     int webkitRequestAnimationFrame(PassRefPtr<RequestAnimationFrameCallback>);
1126     void webkitCancelAnimationFrame(int id);
1127     void serviceScriptedAnimations(DOMTimeStamp);
1128 #endif
1129
1130     virtual EventTarget* errorEventTarget();
1131     virtual void logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, PassRefPtr<ScriptCallStack>);
1132
1133     void initDNSPrefetch();
1134
1135     unsigned wheelEventHandlerCount() const { return m_wheelEventHandlerCount; }
1136     void didAddWheelEventHandler();
1137     void didRemoveWheelEventHandler();
1138
1139 #if ENABLE(TOUCH_EVENTS)
1140     unsigned touchEventHandlerCount() const { return m_touchEventHandlerCount; }
1141 #else
1142     unsigned touchEventHandlerCount() const { return 0; }
1143 #endif
1144
1145     void didAddTouchEventHandler();
1146     void didRemoveTouchEventHandler();
1147
1148     bool visualUpdatesAllowed() const { return m_visualUpdatesAllowed; }
1149
1150 #if ENABLE(MICRODATA)
1151     PassRefPtr<NodeList> getItems(const String& typeNames);
1152 #endif
1153     
1154 #if ENABLE(UNDO_MANAGER)
1155     PassRefPtr<UndoManager> undoManager();
1156 #endif
1157     
1158     bool isInDocumentWrite() { return m_writeRecursionDepth > 0; }
1159
1160     void suspendScheduledTasks(ActiveDOMObject::ReasonForSuspension);
1161     void resumeScheduledTasks();
1162
1163     IntSize viewportSize() const;
1164
1165 #if ENABLE(LINK_PRERENDER)
1166     Prerenderer* prerenderer() { return m_prerenderer.get(); }
1167 #endif
1168
1169 #if ENABLE(TEXT_AUTOSIZING)
1170     TextAutosizer* textAutosizer() { return m_textAutosizer.get(); }
1171 #endif
1172
1173     void adjustFloatQuadsForScrollAndAbsoluteZoomAndFrameScale(Vector<FloatQuad>&, RenderObject*);
1174     void adjustFloatRectForScrollAndAbsoluteZoomAndFrameScale(FloatRect&, RenderObject*);
1175
1176     void setContextFeatures(PassRefPtr<ContextFeatures>);
1177     ContextFeatures* contextFeatures() { return m_contextFeatures.get(); }
1178
1179     virtual void reportMemoryUsage(MemoryObjectInfo*) const OVERRIDE;
1180
1181 protected:
1182     Document(Frame*, const KURL&, bool isXHTML, bool isHTML);
1183
1184     virtual void didUpdateSecurityOrigin() OVERRIDE;
1185
1186     void clearXMLVersion() { m_xmlVersion = String(); }
1187
1188 private:
1189     friend class Node;
1190     friend class IgnoreDestructiveWriteCountIncrementer;
1191
1192     void removedLastRef();
1193     
1194     void detachParser();
1195
1196     typedef void (*ArgumentsCallback)(const String& keyString, const String& valueString, Document*, void* data);
1197     void processArguments(const String& features, void* data, ArgumentsCallback);
1198
1199     virtual bool isDocument() const { return true; }
1200
1201     virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
1202
1203     virtual String nodeName() const;
1204     virtual NodeType nodeType() const;
1205     virtual bool childTypeAllowed(NodeType) const;
1206     virtual PassRefPtr<Node> cloneNode(bool deep);
1207     virtual bool canReplaceChild(Node* newChild, Node* oldChild);
1208
1209     virtual void refScriptExecutionContext() { ref(); }
1210     virtual void derefScriptExecutionContext() { deref(); }
1211
1212     virtual const KURL& virtualURL() const; // Same as url(), but needed for ScriptExecutionContext to implement it without a performance loss for direct calls.
1213     virtual KURL virtualCompleteURL(const String&) const; // Same as completeURL() for the same reason as above.
1214
1215     virtual void addMessage(MessageSource, MessageType, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack>);
1216
1217     virtual double minimumTimerInterval() const;
1218
1219     void updateTitle(const StringWithDirection&);
1220     void updateFocusAppearanceTimerFired(Timer<Document>*);
1221     void updateBaseURL();
1222
1223     void buildAccessKeyMap(TreeScope* root);
1224
1225     void createStyleResolver();
1226     void clearStyleResolver();
1227     void combineCSSFeatureFlags();
1228     void resetCSSFeatureFlags();
1229     
1230     bool updateActiveStylesheets(StyleResolverUpdateFlag);
1231     void collectActiveStylesheets(Vector<RefPtr<StyleSheet> >&);
1232     bool testAddedStylesheetRequiresStyleRecalc(StyleSheetContents*);
1233     void analyzeStylesheetChange(StyleResolverUpdateFlag, const Vector<RefPtr<StyleSheet> >& newStylesheets, bool& requiresStyleResolverReset, bool& requiresFullStyleRecalc);
1234
1235     void seamlessParentUpdatedStylesheets();
1236     void notifySeamlessChildDocumentsOfStylesheetUpdate() const;
1237
1238     void deleteCustomFonts();
1239
1240     PassRefPtr<NodeList> handleZeroPadding(const HitTestRequest&, HitTestResult&) const;
1241
1242     void loadEventDelayTimerFired(Timer<Document>*);
1243
1244     void pendingTasksTimerFired(Timer<Document>*);
1245
1246     static void didReceiveTask(void*);
1247
1248 #if ENABLE(PAGE_VISIBILITY_API)
1249     PageVisibilityState visibilityState() const;
1250 #endif
1251
1252     PassRefPtr<HTMLCollection> cachedCollection(CollectionType);
1253
1254 #if ENABLE(FULLSCREEN_API)
1255     void clearFullscreenElementStack();
1256     void popFullscreenElementStack();
1257     void pushFullscreenElementStack(Element*);
1258     void addDocumentToFullScreenChangeEventQueue(Document*);
1259 #endif
1260
1261     void setVisualUpdatesAllowed(ReadyState);
1262     void setVisualUpdatesAllowed(bool);
1263     void visualUpdatesSuppressionTimerFired(Timer<Document>*);
1264
1265     int m_guardRefCount;
1266
1267     OwnPtr<StyleResolver> m_styleResolver;
1268     bool m_didCalculateStyleResolver;
1269     bool m_hasDirtyStyleResolver;
1270     Vector<OwnPtr<FontData> > m_customFonts;
1271
1272     Frame* m_frame;
1273     OwnPtr<CachedResourceLoader> m_cachedResourceLoader;
1274     RefPtr<DocumentParser> m_parser;
1275     RefPtr<ContextFeatures> m_contextFeatures;
1276
1277     bool m_wellFormed;
1278
1279     // Document URLs.
1280     KURL m_url; // Document.URL: The URL from which this document was retrieved.
1281     KURL m_baseURL; // Node.baseURI: The URL to use when resolving relative URLs.
1282     KURL m_baseURLOverride; // An alternative base URL that takes precedence over m_baseURL (but not m_baseElementURL).
1283     KURL m_baseElementURL; // The URL set by the <base> element.
1284     KURL m_cookieURL; // The URL to use for cookie access.
1285     KURL m_firstPartyForCookies; // The policy URL for third-party cookie blocking.
1286
1287     // Document.documentURI:
1288     // Although URL-like, Document.documentURI can actually be set to any
1289     // string by content.  Document.documentURI affects m_baseURL unless the
1290     // document contains a <base> element, in which case the <base> element
1291     // takes precedence.
1292     //
1293     // This property is read-only from JavaScript, but writable from Objective C.
1294     String m_documentURI;
1295
1296     String m_baseTarget;
1297
1298     RefPtr<DocumentType> m_docType;
1299     OwnPtr<DOMImplementation> m_implementation;
1300
1301     // Track the number of currently loading top-level stylesheets needed for rendering.
1302     // Sheets loaded using the @import directive are not included in this count.
1303     // We use this count of pending sheets to detect when we can begin attaching
1304     // elements and when it is safe to execute scripts.
1305     int m_pendingStylesheets;
1306
1307     // But sometimes you need to ignore pending stylesheet count to
1308     // force an immediate layout when requested by JS.
1309     bool m_ignorePendingStylesheets;
1310
1311     // If we do ignore the pending stylesheet count, then we need to add a boolean
1312     // to track that this happened so that we can do a full repaint when the stylesheets
1313     // do eventually load.
1314     PendingSheetLayout m_pendingSheetLayout;
1315     
1316     bool m_hasNodesWithPlaceholderStyle;
1317
1318     RefPtr<CSSStyleSheet> m_elemSheet;
1319     RefPtr<CSSStyleSheet> m_pageUserSheet;
1320     mutable OwnPtr<Vector<RefPtr<CSSStyleSheet> > > m_pageGroupUserSheets;
1321     OwnPtr<Vector<RefPtr<CSSStyleSheet> > > m_userSheets;
1322     mutable bool m_pageGroupUserSheetCacheValid;
1323
1324     bool m_printing;
1325     bool m_paginatedForScreen;
1326
1327     bool m_ignoreAutofocus;
1328
1329     CompatibilityMode m_compatibilityMode;
1330     bool m_compatibilityModeLocked; // This is cheaper than making setCompatibilityMode virtual.
1331
1332     Color m_textColor;
1333
1334     RefPtr<Node> m_focusedNode;
1335     RefPtr<Node> m_hoverNode;
1336     RefPtr<Node> m_activeNode;
1337     RefPtr<Element> m_documentElement;
1338
1339     uint64_t m_domTreeVersion;
1340     static uint64_t s_globalTreeVersion;
1341     
1342     HashSet<NodeIterator*> m_nodeIterators;
1343     HashSet<Range*> m_ranges;
1344
1345     unsigned short m_listenerTypes;
1346
1347 #if ENABLE(MUTATION_OBSERVERS)
1348     MutationObserverOptions m_mutationObserverTypes;
1349 #endif
1350
1351     RefPtr<StyleSheetList> m_styleSheets; // All of the stylesheets that are currently in effect for our media type and stylesheet set.
1352     bool m_hadActiveLoadingStylesheet;
1353     
1354     typedef ListHashSet<Node*, 32> StyleSheetCandidateListHashSet;
1355     StyleSheetCandidateListHashSet m_styleSheetCandidateNodes; // All of the nodes that could potentially provide stylesheets to the document (<link>, <style>, <?xml-stylesheet>)
1356
1357     OwnPtr<FormController> m_formController;
1358
1359     Color m_linkColor;
1360     Color m_visitedLinkColor;
1361     Color m_activeLinkColor;
1362
1363     String m_preferredStylesheetSet;
1364     String m_selectedStylesheetSet;
1365
1366     bool m_loadingSheet;
1367     bool m_visuallyOrdered;
1368     ReadyState m_readyState;
1369     bool m_bParsing;
1370     
1371     Timer<Document> m_styleRecalcTimer;
1372     bool m_pendingStyleRecalcShouldForce;
1373     bool m_inStyleRecalc;
1374     bool m_closeAfterStyleRecalc;
1375
1376     bool m_usesSiblingRules;
1377     bool m_usesSiblingRulesOverride;
1378     bool m_usesFirstLineRules;
1379     bool m_usesFirstLetterRules;
1380     bool m_usesBeforeAfterRules;
1381     bool m_usesBeforeAfterRulesOverride;
1382     bool m_usesRemUnits;
1383     bool m_usesLinkRules;
1384     bool m_gotoAnchorNeededAfterStylesheetsLoad;
1385     bool m_isDNSPrefetchEnabled;
1386     bool m_haveExplicitlyDisabledDNSPrefetch;
1387     bool m_frameElementsShouldIgnoreScrolling;
1388     bool m_containsValidityStyleRules;
1389     bool m_updateFocusAppearanceRestoresSelection;
1390
1391     // http://www.whatwg.org/specs/web-apps/current-work/#ignore-destructive-writes-counter
1392     unsigned m_ignoreDestructiveWriteCount;
1393
1394     StringWithDirection m_title;
1395     StringWithDirection m_rawTitle;
1396     bool m_titleSetExplicitly;
1397     RefPtr<Element> m_titleElement;
1398
1399     OwnPtr<RenderArena> m_renderArena;
1400
1401     mutable AXObjectCache* m_axObjectCache;
1402     OwnPtr<DocumentMarkerController> m_markers;
1403     
1404     Timer<Document> m_updateFocusAppearanceTimer;
1405
1406     Element* m_cssTarget;
1407
1408     // FIXME: Merge these 2 variables into an enum. Also, FrameLoader::m_didCallImplicitClose
1409     // is almost a duplication of this data, so that should probably get merged in too.
1410     // FIXME: Document::m_processingLoadEvent and DocumentLoader::m_wasOnloadHandled are roughly the same
1411     // and should be merged.
1412     bool m_processingLoadEvent;
1413     bool m_loadEventFinished;
1414
1415     RefPtr<SerializedScriptValue> m_pendingStateObject;
1416     double m_startTime;
1417     bool m_overMinimumLayoutThreshold;
1418     
1419     OwnPtr<ScriptRunner> m_scriptRunner;
1420
1421 #if ENABLE(XSLT)
1422     OwnPtr<TransformSource> m_transformSource;
1423     RefPtr<Document> m_transformSourceDocument;
1424 #endif
1425
1426     int m_docID; // A unique document identifier used for things like document-specific mapped attributes.
1427
1428     String m_xmlEncoding;
1429     String m_xmlVersion;
1430     unsigned m_xmlStandalone : 2;
1431     unsigned m_hasXMLDeclaration : 1;
1432
1433     String m_contentLanguage;
1434
1435     RenderObject* m_savedRenderer;
1436     
1437     RefPtr<TextResourceDecoder> m_decoder;
1438
1439     InheritedBool m_designMode;
1440
1441     HashSet<DynamicNodeListCacheBase*> m_listsInvalidatedAtDocument;
1442     unsigned m_nodeListCounts[numNodeListInvalidationTypes];
1443
1444     HTMLCollection* m_collections[NumUnnamedDocumentCachedTypes];
1445     typedef HashMap<AtomicString, HTMLNameCollection*> NamedCollectionMap;
1446     NamedCollectionMap m_documentNamedItemCollections;
1447     NamedCollectionMap m_windowNamedItemCollections;
1448
1449     RefPtr<XPathEvaluator> m_xpathEvaluator;
1450
1451 #if ENABLE(SVG)
1452     OwnPtr<SVGDocumentExtensions> m_svgExtensions;
1453 #endif
1454
1455 #if ENABLE(DASHBOARD_SUPPORT)
1456     Vector<DashboardRegionValue> m_dashboardRegions;
1457     bool m_hasDashboardRegions;
1458     bool m_dashboardRegionsDirty;
1459 #endif
1460
1461     HashMap<String, RefPtr<HTMLCanvasElement> > m_cssCanvasElements;
1462
1463     bool m_createRenderers;
1464     bool m_inPageCache;
1465     Vector<IconURL> m_iconURLs;
1466
1467     HashSet<Element*> m_documentSuspensionCallbackElements;
1468     HashSet<Element*> m_mediaVolumeCallbackElements;
1469     HashSet<Element*> m_privateBrowsingStateChangedElements;
1470
1471     HashMap<StringImpl*, Element*, CaseFoldingHash> m_elementsByAccessKey;    
1472     bool m_accessKeyMapValid;
1473
1474     OwnPtr<SelectorQueryCache> m_selectorQueryCache;
1475
1476     bool m_useSecureKeyboardEntryWhenActive;
1477
1478     bool m_isXHTML;
1479     bool m_isHTML;
1480
1481     bool m_isViewSource;
1482     bool m_sawElementsInKnownNamespaces;
1483     bool m_isSrcdocDocument;
1484
1485     NodeRareData* m_documentRareData;
1486
1487     RefPtr<DocumentEventQueue> m_eventQueue;
1488
1489     RefPtr<DocumentWeakReference> m_weakReference;
1490
1491     HashSet<MediaCanStartListener*> m_mediaCanStartListeners;
1492
1493     QualifiedName m_idAttributeName;
1494
1495 #if ENABLE(FULLSCREEN_API)
1496     bool m_areKeysEnabledInFullScreen;
1497     RefPtr<Element> m_fullScreenElement;
1498     Deque<RefPtr<Element> > m_fullScreenElementStack;
1499     RenderFullScreen* m_fullScreenRenderer;
1500     Timer<Document> m_fullScreenChangeDelayTimer;
1501     Deque<RefPtr<Node> > m_fullScreenChangeEventTargetQueue;
1502     Deque<RefPtr<Node> > m_fullScreenErrorEventTargetQueue;
1503     bool m_isAnimatingFullScreen;
1504     LayoutRect m_savedPlaceholderFrameRect;
1505     RefPtr<RenderStyle> m_savedPlaceholderRenderStyle;
1506 #endif
1507
1508     int m_loadEventDelayCount;
1509     Timer<Document> m_loadEventDelayTimer;
1510
1511     ViewportArguments m_viewportArguments;
1512
1513     ReferrerPolicy m_referrerPolicy;
1514
1515     bool m_directionSetOnDocumentElement;
1516     bool m_writingModeSetOnDocumentElement;
1517
1518     DocumentTiming m_documentTiming;
1519     RefPtr<MediaQueryMatcher> m_mediaQueryMatcher;
1520     bool m_writeRecursionIsTooDeep;
1521     unsigned m_writeRecursionDepth;
1522     
1523     unsigned m_wheelEventHandlerCount;
1524 #if ENABLE(TOUCH_EVENTS)
1525     unsigned m_touchEventHandlerCount;
1526 #endif
1527     
1528 #if ENABLE(UNDO_MANAGER)
1529     RefPtr<UndoManager> m_undoManager;
1530 #endif
1531
1532 #if ENABLE(REQUEST_ANIMATION_FRAME)
1533     RefPtr<ScriptedAnimationController> m_scriptedAnimationController;
1534 #endif
1535
1536     Timer<Document> m_pendingTasksTimer;
1537     Vector<OwnPtr<Task> > m_pendingTasks;
1538
1539 #if ENABLE(LINK_PRERENDER)
1540     OwnPtr<Prerenderer> m_prerenderer;
1541 #endif
1542
1543 #if ENABLE(TEXT_AUTOSIZING)
1544     OwnPtr<TextAutosizer> m_textAutosizer;
1545 #endif
1546
1547     bool m_scheduledTasksAreSuspended;
1548     
1549     bool m_visualUpdatesAllowed;
1550     Timer<Document> m_visualUpdatesSuppressionTimer;
1551
1552     RefPtr<WebKitNamedFlowCollection> m_namedFlows;
1553
1554 #if ENABLE(CSP_NEXT)
1555     RefPtr<DOMSecurityPolicy> m_domSecurityPolicy;
1556 #endif
1557
1558 #ifndef NDEBUG
1559     bool m_didDispatchViewportPropertiesChanged;
1560 #endif
1561 };
1562
1563 // Put these methods here, because they require the Document definition, but we really want to inline them.
1564
1565 inline bool Node::isDocumentNode() const
1566 {
1567     return this == m_document;
1568 }
1569
1570 inline Node::Node(Document* document, ConstructionType type)
1571     : m_nodeFlags(type)
1572     , m_document(document)
1573     , m_previous(0)
1574     , m_next(0)
1575     , m_renderer(0)
1576 #if ENABLE(TIZEN_ELEMENT_CREATED_BY_PARSER_INFO_STORE)
1577     , m_createdByParser(true)
1578 #endif
1579 {
1580     if (document)
1581         document->guardRef();
1582 #if !defined(NDEBUG) || (defined(DUMP_NODE_STATISTICS) && DUMP_NODE_STATISTICS)
1583     trackForDebugging();
1584 #endif
1585     InspectorCounters::incrementCounter(InspectorCounters::NodeCounter);
1586 }
1587
1588 Node* eventTargetNodeForDocument(Document*);
1589
1590 } // namespace WebCore
1591
1592 #endif // Document_h