Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / 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 "bindings/v8/ExceptionStatePlaceholder.h"
32 #include "bindings/v8/ScriptValue.h"
33 #include "core/animation/CompositorPendingAnimations.h"
34 #include "core/dom/ContainerNode.h"
35 #include "core/dom/DocumentEncodingData.h"
36 #include "core/dom/DocumentInit.h"
37 #include "core/dom/DocumentLifecycle.h"
38 #include "core/dom/DocumentSupplementable.h"
39 #include "core/dom/DocumentTiming.h"
40 #include "core/dom/ExecutionContext.h"
41 #include "core/dom/IconURL.h"
42 #include "core/dom/MutationObserver.h"
43 #include "core/dom/QualifiedName.h"
44 #include "core/dom/TextLinkColors.h"
45 #include "core/dom/TreeScope.h"
46 #include "core/dom/UserActionElementSet.h"
47 #include "core/dom/ViewportDescription.h"
48 #include "core/dom/custom/CustomElement.h"
49 #include "core/html/CollectionType.h"
50 #include "core/page/FocusType.h"
51 #include "core/page/PageVisibilityState.h"
52 #include "core/rendering/HitTestRequest.h"
53 #include "platform/Length.h"
54 #include "platform/Timer.h"
55 #include "platform/heap/Handle.h"
56 #include "platform/weborigin/KURL.h"
57 #include "platform/weborigin/ReferrerPolicy.h"
58 #include "wtf/HashSet.h"
59 #include "wtf/OwnPtr.h"
60 #include "wtf/PassOwnPtr.h"
61 #include "wtf/PassRefPtr.h"
62 #include "wtf/WeakPtr.h"
63
64 namespace WebCore {
65
66 class AXObjectCache;
67 class AnimationClock;
68 class Attr;
69 class CDATASection;
70 class CSSFontSelector;
71 class CSSStyleDeclaration;
72 class CSSStyleSheet;
73 class CSSStyleSheetResource;
74 class CanvasRenderingContext2D;
75 class CharacterData;
76 class Chrome;
77 class Comment;
78 class ContentSecurityPolicyResponseHeaders;
79 class ContextFeatures;
80 class CustomElementRegistrationContext;
81 class DOMImplementation;
82 class DOMSelection;
83 class DOMWindow;
84 class Database;
85 class DatabaseThread;
86 class DocumentFragment;
87 class DocumentLifecycleNotifier;
88 class DocumentLifecycleObserver;
89 class DocumentLoader;
90 class DocumentMarkerController;
91 class DocumentParser;
92 class DocumentState;
93 class DocumentTimeline;
94 class DocumentType;
95 class Element;
96 class ElementDataCache;
97 class Event;
98 class EventListener;
99 class ExceptionState;
100 class FastTextAutosizer;
101 class FloatQuad;
102 class FloatRect;
103 class FontFaceSet;
104 class FormController;
105 class LocalFrame;
106 class FrameHost;
107 class FrameView;
108 class HTMLAllCollection;
109 class HTMLCanvasElement;
110 class HTMLCollection;
111 class HTMLDialogElement;
112 class HTMLDocument;
113 class HTMLElement;
114 class HTMLFrameOwnerElement;
115 class HTMLHeadElement;
116 class HTMLIFrameElement;
117 class HTMLImport;
118 class HTMLImportLoader;
119 class HTMLImportsController;
120 class HTMLMapElement;
121 class HTMLNameCollection;
122 class HTMLScriptElement;
123 class HitTestRequest;
124 class HitTestResult;
125 class IntPoint;
126 class JSNode;
127 class LayoutPoint;
128 class LayoutRect;
129 class LiveNodeListBase;
130 class Locale;
131 class Location;
132 class MainThreadTaskRunner;
133 class MediaQueryList;
134 class MediaQueryMatcher;
135 class MouseEventWithHitTestResults;
136 class NodeFilter;
137 class NodeIterator;
138 class Page;
139 class PlatformMouseEvent;
140 class ProcessingInstruction;
141 class Range;
142 class RegisteredEventListener;
143 class RenderView;
144 class RequestAnimationFrameCallback;
145 class ResourceFetcher;
146 class SVGDocumentExtensions;
147 class SVGUseElement;
148 class ScriptElementData;
149 class ScriptResource;
150 class ScriptRunner;
151 class ScriptableDocumentParser;
152 class ScriptedAnimationController;
153 class SecurityOrigin;
154 class SegmentedString;
155 class SelectorQueryCache;
156 class SerializedScriptValue;
157 class Settings;
158 class StyleEngine;
159 class StyleResolver;
160 class StyleSheet;
161 class StyleSheetContents;
162 class StyleSheetList;
163 class Text;
164 class TextAutosizer;
165 class Touch;
166 class TouchList;
167 class TransformSource;
168 class TreeWalker;
169 class VisitedLinkState;
170 class WebGLRenderingContext;
171 class XMLHttpRequest;
172
173 struct AnnotatedRegionValue;
174
175 typedef int ExceptionCode;
176
177 enum RecalcStyleTime {
178     RecalcStyleImmediately, // synchronous
179     RecalcStyleDeferred // asynchronous
180 };
181
182 enum StyleResolverUpdateMode {
183     // Discards the StyleResolver and rebuilds it.
184     FullStyleUpdate,
185     // Attempts to use StyleInvalidationAnalysis to avoid discarding the entire StyleResolver.
186     AnalyzedStyleUpdate
187 };
188
189 enum NodeListInvalidationType {
190     DoNotInvalidateOnAttributeChanges = 0,
191     InvalidateOnClassAttrChange,
192     InvalidateOnIdNameAttrChange,
193     InvalidateOnNameAttrChange,
194     InvalidateOnForAttrChange,
195     InvalidateForFormControls,
196     InvalidateOnHRefAttrChange,
197     InvalidateOnAnyAttrChange,
198 };
199 const int numNodeListInvalidationTypes = InvalidateOnAnyAttrChange + 1;
200
201 typedef HashCountedSet<Node*> TouchEventTargetSet;
202
203 enum DocumentClass {
204     DefaultDocumentClass = 0,
205     HTMLDocumentClass = 1,
206     XHTMLDocumentClass = 1 << 1,
207     ImageDocumentClass = 1 << 2,
208     PluginDocumentClass = 1 << 3,
209     MediaDocumentClass = 1 << 4,
210     SVGDocumentClass = 1 << 5,
211     XMLDocumentClass = 1 << 6,
212 };
213
214 typedef unsigned char DocumentClassFlags;
215
216 class Document;
217
218 class DocumentVisibilityObserver : public WillBeGarbageCollectedMixin {
219 public:
220     DocumentVisibilityObserver(Document&);
221     virtual ~DocumentVisibilityObserver();
222
223     virtual void didChangeVisibilityState(PageVisibilityState) = 0;
224
225     // Classes that inherit Node and DocumentVisibilityObserver must have a
226     // virtual override of Node::didMoveToNewDocument that calls
227     // DocumentVisibilityObserver::setDocument
228     void setObservedDocument(Document&);
229
230 private:
231     void registerObserver(Document&);
232     void unregisterObserver();
233     Document* m_document;
234 };
235
236 class Document : public ContainerNode, public TreeScope, public SecurityContext, public ExecutionContext, public ExecutionContextClient
237     , public DocumentSupplementable, public LifecycleContext<Document> {
238     WILL_BE_USING_GARBAGE_COLLECTED_MIXIN(Document);
239 public:
240     static PassRefPtr<Document> create(const DocumentInit& initializer = DocumentInit())
241     {
242         return adoptRef(new Document(initializer));
243     }
244     virtual ~Document();
245
246     MediaQueryMatcher& mediaQueryMatcher();
247
248     void mediaQueryAffectingValueChanged();
249
250     using ContainerNode::ref;
251     using ContainerNode::deref;
252     using SecurityContext::securityOrigin;
253     using SecurityContext::contentSecurityPolicy;
254     using ExecutionContextClient::addConsoleMessage;
255     using TreeScope::getElementById;
256
257     virtual bool canContainRangeEndPoint() const OVERRIDE { return true; }
258
259     SelectorQueryCache& selectorQueryCache();
260
261     // Focus Management.
262     Element* activeElement() const;
263     bool hasFocus() const;
264
265     // DOM methods & attributes for Document
266
267     DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecopy);
268     DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecut);
269     DEFINE_ATTRIBUTE_EVENT_LISTENER(beforepaste);
270     DEFINE_ATTRIBUTE_EVENT_LISTENER(copy);
271     DEFINE_ATTRIBUTE_EVENT_LISTENER(cut);
272     DEFINE_ATTRIBUTE_EVENT_LISTENER(paste);
273     DEFINE_ATTRIBUTE_EVENT_LISTENER(pointerlockchange);
274     DEFINE_ATTRIBUTE_EVENT_LISTENER(pointerlockerror);
275     DEFINE_ATTRIBUTE_EVENT_LISTENER(readystatechange);
276     DEFINE_ATTRIBUTE_EVENT_LISTENER(search);
277     DEFINE_ATTRIBUTE_EVENT_LISTENER(securitypolicyviolation);
278     DEFINE_ATTRIBUTE_EVENT_LISTENER(selectionchange);
279     DEFINE_ATTRIBUTE_EVENT_LISTENER(selectstart);
280     DEFINE_ATTRIBUTE_EVENT_LISTENER(touchcancel);
281     DEFINE_ATTRIBUTE_EVENT_LISTENER(touchend);
282     DEFINE_ATTRIBUTE_EVENT_LISTENER(touchmove);
283     DEFINE_ATTRIBUTE_EVENT_LISTENER(touchstart);
284     DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitfullscreenchange);
285     DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitfullscreenerror);
286     DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitpointerlockchange);
287     DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitpointerlockerror);
288     DEFINE_ATTRIBUTE_EVENT_LISTENER(wheel);
289
290     bool shouldMergeWithLegacyDescription(ViewportDescription::Type);
291     bool shouldOverrideLegacyDescription(ViewportDescription::Type);
292     void setViewportDescription(const ViewportDescription&);
293     const ViewportDescription& viewportDescription() const { return m_viewportDescription; }
294     Length viewportDefaultMinWidth() const { return m_viewportDefaultMinWidth; }
295
296 #ifndef NDEBUG
297     bool didDispatchViewportPropertiesChanged() const { return m_didDispatchViewportPropertiesChanged; }
298 #endif
299     bool hasLegacyViewportTag() const { return m_legacyViewportDescription.isLegacyViewportType(); }
300
301     void setReferrerPolicy(ReferrerPolicy);
302     ReferrerPolicy referrerPolicy() const { return m_referrerPolicy; }
303
304     String outgoingReferrer();
305     String outgoingOrigin() const;
306
307     void setDoctype(PassRefPtr<DocumentType>);
308     DocumentType* doctype() const { return m_docType.get(); }
309
310     DOMImplementation& implementation();
311
312     Element* documentElement() const
313     {
314         return m_documentElement.get();
315     }
316
317     bool hasManifest() const;
318
319     Location* location() const;
320
321     PassRefPtr<Element> createElement(const AtomicString& name, ExceptionState&);
322     PassRefPtr<DocumentFragment> createDocumentFragment();
323     PassRefPtr<Text> createTextNode(const String& data);
324     PassRefPtr<Comment> createComment(const String& data);
325     PassRefPtr<CDATASection> createCDATASection(const String& data, ExceptionState&);
326     PassRefPtr<ProcessingInstruction> createProcessingInstruction(const String& target, const String& data, ExceptionState&);
327     PassRefPtr<Attr> createAttribute(const AtomicString& name, ExceptionState&);
328     PassRefPtr<Attr> createAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState&, bool shouldIgnoreNamespaceChecks = false);
329     PassRefPtr<Node> importNode(Node* importedNode, ExceptionState&);
330     PassRefPtr<Node> importNode(Node* importedNode, bool deep, ExceptionState&);
331     PassRefPtr<Element> createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState&);
332     PassRefPtr<Element> createElement(const QualifiedName&, bool createdByParser);
333
334     bool regionBasedColumnsEnabled() const;
335
336     /**
337      * Retrieve all nodes that intersect a rect in the window's document, until it is fully enclosed by
338      * the boundaries of a node.
339      *
340      * @param centerX x reference for the rectangle in CSS pixels
341      * @param centerY y reference for the rectangle in CSS pixels
342      * @param topPadding How much to expand the top of the rectangle
343      * @param rightPadding How much to expand the right of the rectangle
344      * @param bottomPadding How much to expand the bottom of the rectangle
345      * @param leftPadding How much to expand the left of the rectangle
346      */
347     PassRefPtr<NodeList> nodesFromRect(int centerX, int centerY,
348         unsigned topPadding, unsigned rightPadding, unsigned bottomPadding, unsigned leftPadding,
349         HitTestRequest::HitTestRequestType hitType = HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent) const;
350     Element* elementFromPoint(int x, int y) const;
351     PassRefPtrWillBeRawPtr<Range> caretRangeFromPoint(int x, int y);
352
353     String readyState() const;
354
355     String defaultCharset() const;
356
357     AtomicString inputEncoding() const { return Document::encodingName(); }
358     AtomicString charset() const { return Document::encodingName(); }
359     AtomicString characterSet() const { return Document::encodingName(); }
360
361     AtomicString encodingName() const;
362
363     void setCharset(const String&);
364
365     void setContent(const String&);
366
367     String suggestedMIMEType() const;
368     void setMimeType(const AtomicString&);
369     AtomicString contentType() const; // DOM 4 document.contentType
370
371     const AtomicString& contentLanguage() const { return m_contentLanguage; }
372     void setContentLanguage(const AtomicString&);
373
374     String xmlEncoding() const { return m_xmlEncoding; }
375     String xmlVersion() const { return m_xmlVersion; }
376     enum StandaloneStatus { StandaloneUnspecified, Standalone, NotStandalone };
377     bool xmlStandalone() const { return m_xmlStandalone == Standalone; }
378     StandaloneStatus xmlStandaloneStatus() const { return static_cast<StandaloneStatus>(m_xmlStandalone); }
379     bool hasXMLDeclaration() const { return m_hasXMLDeclaration; }
380
381     void setXMLEncoding(const String& encoding) { m_xmlEncoding = encoding; } // read-only property, only to be set from XMLDocumentParser
382     void setXMLVersion(const String&, ExceptionState&);
383     void setXMLStandalone(bool, ExceptionState&);
384     void setHasXMLDeclaration(bool hasXMLDeclaration) { m_hasXMLDeclaration = hasXMLDeclaration ? 1 : 0; }
385
386     virtual KURL baseURI() const OVERRIDE FINAL;
387
388     String visibilityState() const;
389     bool hidden() const;
390     void didChangeVisibilityState();
391
392     PassRefPtr<Node> adoptNode(PassRefPtr<Node> source, ExceptionState&);
393
394     PassRefPtr<HTMLCollection> images();
395     PassRefPtr<HTMLCollection> embeds();
396     PassRefPtr<HTMLCollection> applets();
397     PassRefPtr<HTMLCollection> links();
398     PassRefPtr<HTMLCollection> forms();
399     PassRefPtr<HTMLCollection> anchors();
400     PassRefPtr<HTMLCollection> scripts();
401     PassRefPtr<HTMLAllCollection> allForBinding();
402     PassRefPtr<HTMLAllCollection> all();
403
404     PassRefPtr<HTMLCollection> windowNamedItems(const AtomicString& name);
405     PassRefPtr<HTMLCollection> documentNamedItems(const AtomicString& name);
406
407     bool isHTMLDocument() const { return m_documentClasses & HTMLDocumentClass; }
408     bool isXHTMLDocument() const { return m_documentClasses & XHTMLDocumentClass; }
409     bool isXMLDocument() const { return m_documentClasses & XMLDocumentClass; }
410     bool isImageDocument() const { return m_documentClasses & ImageDocumentClass; }
411     bool isSVGDocument() const { return m_documentClasses & SVGDocumentClass; }
412     bool isPluginDocument() const { return m_documentClasses & PluginDocumentClass; }
413     bool isMediaDocument() const { return m_documentClasses & MediaDocumentClass; }
414
415     bool hasSVGRootNode() const;
416
417     bool isFrameSet() const;
418
419     bool isSrcdocDocument() const { return m_isSrcdocDocument; }
420     bool isMobileDocument() const { return m_isMobileDocument; }
421
422     StyleResolver* styleResolver() const;
423     StyleResolver& ensureStyleResolver() const;
424
425     bool isViewSource() const { return m_isViewSource; }
426     void setIsViewSource(bool);
427
428     bool sawElementsInKnownNamespaces() const { return m_sawElementsInKnownNamespaces; }
429
430     void notifyRemovePendingSheetIfNeeded();
431
432     bool isRenderingReady() const { return haveImportsLoaded() && haveStylesheetsLoaded(); }
433     bool isScriptExecutionReady() const { return isRenderingReady(); }
434
435     // This is a DOM function.
436     StyleSheetList* styleSheets();
437
438     StyleEngine* styleEngine() { return m_styleEngine.get(); }
439
440     bool gotoAnchorNeededAfterStylesheetsLoad() { return m_gotoAnchorNeededAfterStylesheetsLoad; }
441     void setGotoAnchorNeededAfterStylesheetsLoad(bool b) { m_gotoAnchorNeededAfterStylesheetsLoad = b; }
442
443     // Called when one or more stylesheets in the document may have been added, removed, or changed.
444     void styleResolverChanged(RecalcStyleTime, StyleResolverUpdateMode = FullStyleUpdate);
445     void styleResolverMayHaveChanged();
446
447     // FIXME: Switch all callers of styleResolverChanged to these or better ones and then make them
448     // do something smarter.
449     void removedStyleSheet(StyleSheet*, RecalcStyleTime when = RecalcStyleDeferred, StyleResolverUpdateMode = FullStyleUpdate);
450     void addedStyleSheet(StyleSheet*, RecalcStyleTime when = RecalcStyleDeferred) { styleResolverChanged(when); }
451     void modifiedStyleSheet(StyleSheet*, RecalcStyleTime when = RecalcStyleDeferred, StyleResolverUpdateMode = FullStyleUpdate);
452     void changedSelectorWatch() { styleResolverChanged(RecalcStyleDeferred); }
453
454     void scheduleUseShadowTreeUpdate(SVGUseElement&);
455     void unscheduleUseShadowTreeUpdate(SVGUseElement&);
456
457     // FIXME: This should be eliminated and elements that use it should be made to
458     // always have a layer so they don't need to go about creating one from reasons
459     // external to style.
460     void scheduleLayerUpdate(Element&);
461     void unscheduleLayerUpdate(Element&);
462
463     void evaluateMediaQueryList();
464
465     FormController& formController();
466     DocumentState* formElementsState() const;
467     void setStateForNewFormElements(const Vector<String>&);
468
469     FrameView* view() const; // can be null
470     LocalFrame* frame() const { return m_frame; } // can be null
471     FrameHost* frameHost() const; // can be null
472     Page* page() const; // can be null
473     Settings* settings() const; // can be null
474
475     float devicePixelRatio() const;
476
477     PassRefPtrWillBeRawPtr<Range> createRange();
478
479     PassRefPtr<NodeIterator> createNodeIterator(Node* root, ExceptionState&);
480     PassRefPtr<NodeIterator> createNodeIterator(Node* root, unsigned whatToShow, ExceptionState&);
481     PassRefPtr<NodeIterator> createNodeIterator(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter>, ExceptionState&);
482
483     PassRefPtr<TreeWalker> createTreeWalker(Node* root, ExceptionState&);
484     PassRefPtr<TreeWalker> createTreeWalker(Node* root, unsigned whatToShow, ExceptionState&);
485     PassRefPtr<TreeWalker> createTreeWalker(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter>, ExceptionState&);
486
487     // Special support for editing
488     PassRefPtr<Text> createEditingTextNode(const String&);
489
490     void setupFontBuilder(RenderStyle* documentStyle);
491
492     void updateRenderTreeIfNeeded() { updateRenderTree(NoChange); }
493     void updateRenderTreeForNodeIfNeeded(Node*);
494     void updateLayout();
495     enum RunPostLayoutTasks {
496         RunPostLayoutTasksAsyhnchronously,
497         RunPostLayoutTasksSynchronously,
498     };
499     void updateLayoutIgnorePendingStylesheets(RunPostLayoutTasks = RunPostLayoutTasksAsyhnchronously);
500     PassRefPtr<RenderStyle> styleForElementIgnoringPendingStylesheets(Element*);
501     PassRefPtr<RenderStyle> styleForPage(int pageIndex);
502
503     void updateDistributionForNodeIfNeeded(Node*);
504
505     // Returns true if page box (margin boxes and page borders) is visible.
506     bool isPageBoxVisible(int pageIndex);
507
508     // Returns the preferred page size and margins in pixels, assuming 96
509     // pixels per inch. pageSize, marginTop, marginRight, marginBottom,
510     // marginLeft must be initialized to the default values that are used if
511     // auto is specified.
512     void pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft);
513
514     ResourceFetcher* fetcher() { return m_fetcher.get(); }
515
516     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
517     virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
518     void prepareForDestruction();
519
520     RenderView* renderView() const { return m_renderView; }
521
522     AXObjectCache* existingAXObjectCache() const;
523     AXObjectCache* axObjectCache() const;
524     void clearAXObjectCache();
525
526     // to get visually ordered hebrew and arabic pages right
527     bool visuallyOrdered() const { return m_visuallyOrdered; }
528
529     DocumentLoader* loader() const;
530
531     void open(Document* ownerDocument = 0, ExceptionState& = ASSERT_NO_EXCEPTION);
532     PassRefPtr<DocumentParser> implicitOpen();
533
534     // close() is the DOM API document.close()
535     void close(ExceptionState& = ASSERT_NO_EXCEPTION);
536     // In some situations (see the code), we ignore document.close().
537     // explicitClose() bypass these checks and actually tries to close the
538     // input stream.
539     void explicitClose();
540     // implicitClose() actually does the work of closing the input stream.
541     void implicitClose();
542
543     bool dispatchBeforeUnloadEvent(Chrome&, bool&);
544     void dispatchUnloadEvents();
545
546     enum PageDismissalType {
547         NoDismissal = 0,
548         BeforeUnloadDismissal = 1,
549         PageHideDismissal = 2,
550         UnloadDismissal = 3
551     };
552     PageDismissalType pageDismissalEventBeingDispatched() const;
553
554     void cancelParsing();
555
556     void write(const SegmentedString& text, Document* ownerDocument = 0, ExceptionState& = ASSERT_NO_EXCEPTION);
557     void write(const String& text, Document* ownerDocument = 0, ExceptionState& = ASSERT_NO_EXCEPTION);
558     void writeln(const String& text, Document* ownerDocument = 0, ExceptionState& = ASSERT_NO_EXCEPTION);
559
560     bool wellFormed() const { return m_wellFormed; }
561
562     const KURL& url() const { return m_url; }
563     void setURL(const KURL&);
564
565     // To understand how these concepts relate to one another, please see the
566     // comments surrounding their declaration.
567     const KURL& baseURL() const { return m_baseURL; }
568     void setBaseURLOverride(const KURL&);
569     const KURL& baseURLOverride() const { return m_baseURLOverride; }
570     const KURL& baseElementURL() const { return m_baseElementURL; }
571     const AtomicString& baseTarget() const { return m_baseTarget; }
572     void processBaseElement();
573
574     KURL completeURL(const String&) const;
575     KURL completeURLWithOverride(const String&, const KURL& baseURLOverride) const;
576
577     virtual String userAgent(const KURL&) const OVERRIDE FINAL;
578     virtual void disableEval(const String& errorMessage) OVERRIDE FINAL;
579
580     bool canNavigate(LocalFrame* targetFrame);
581     LocalFrame* findUnsafeParentScrollPropagationBoundary();
582
583     CSSStyleSheet& elementSheet();
584
585     virtual PassRefPtr<DocumentParser> createParser();
586     DocumentParser* parser() const { return m_parser.get(); }
587     ScriptableDocumentParser* scriptableDocumentParser() const;
588
589     bool printing() const { return m_printing; }
590     void setPrinting(bool p) { m_printing = p; }
591
592     bool paginatedForScreen() const { return m_paginatedForScreen; }
593     void setPaginatedForScreen(bool p) { m_paginatedForScreen = p; }
594
595     bool paginated() const { return printing() || paginatedForScreen(); }
596
597     enum CompatibilityMode { QuirksMode, LimitedQuirksMode, NoQuirksMode };
598
599     void setCompatibilityMode(CompatibilityMode m);
600     CompatibilityMode compatibilityMode() const { return m_compatibilityMode; }
601
602     String compatMode() const;
603
604     bool inQuirksMode() const { return m_compatibilityMode == QuirksMode; }
605     bool inLimitedQuirksMode() const { return m_compatibilityMode == LimitedQuirksMode; }
606     bool inNoQuirksMode() const { return m_compatibilityMode == NoQuirksMode; }
607
608     enum ReadyState {
609         Loading,
610         Interactive,
611         Complete
612     };
613     void setReadyState(ReadyState);
614     bool isLoadCompleted();
615
616     void setParsing(bool);
617     bool parsing() const { return m_isParsing; }
618
619     bool shouldScheduleLayout() const;
620     int elapsedTime() const;
621
622     TextLinkColors& textLinkColors() { return m_textLinkColors; }
623     VisitedLinkState& visitedLinkState() const { return *m_visitedLinkState; }
624
625     MouseEventWithHitTestResults prepareMouseEvent(const HitTestRequest&, const LayoutPoint&, const PlatformMouseEvent&);
626
627     /* Newly proposed CSS3 mechanism for selecting alternate
628        stylesheets using the DOM. May be subject to change as
629        spec matures. - dwh
630     */
631     String preferredStylesheetSet() const;
632     String selectedStylesheetSet() const;
633     void setSelectedStylesheetSet(const String&);
634
635     bool setFocusedElement(PassRefPtr<Element>, FocusType = FocusTypeNone);
636     Element* focusedElement() const { return m_focusedElement.get(); }
637     UserActionElementSet& userActionElements()  { return m_userActionElements; }
638     const UserActionElementSet& userActionElements() const { return m_userActionElements; }
639     void setNeedsFocusedElementCheck();
640     void setAutofocusElement(Element*);
641     Element* autofocusElement() const { return m_autofocusElement.get(); }
642
643     void setHoverNode(PassRefPtr<Node>);
644     Node* hoverNode() const { return m_hoverNode.get(); }
645
646     void setActiveHoverElement(PassRefPtr<Element>);
647     Element* activeHoverElement() const { return m_activeHoverElement.get(); }
648
649     void removeFocusedElementOfSubtree(Node*, bool amongChildrenOnly = false);
650     void hoveredNodeDetached(Node*);
651     void activeChainNodeDetached(Node*);
652
653     void updateHoverActiveState(const HitTestRequest&, Element*, const PlatformMouseEvent* = 0);
654
655     // Updates for :target (CSS3 selector).
656     void setCSSTarget(Element*);
657     Element* cssTarget() const { return m_cssTarget; }
658
659     void scheduleRenderTreeUpdateIfNeeded();
660     bool hasPendingForcedStyleRecalc() const;
661
662     void registerNodeList(LiveNodeListBase*);
663     void unregisterNodeList(LiveNodeListBase*);
664     void incrementNodeListWithIdNameCacheCount();
665     void decrementNodeListWithIdNameCacheCount();
666     bool shouldInvalidateNodeListCaches(const QualifiedName* attrName = 0) const;
667     void invalidateNodeListCaches(const QualifiedName* attrName);
668
669     void attachNodeIterator(NodeIterator*);
670     void detachNodeIterator(NodeIterator*);
671     void moveNodeIteratorsToNewDocument(Node&, Document&);
672
673     void attachRange(Range*);
674     void detachRange(Range*);
675
676     void updateRangesAfterChildrenChanged(ContainerNode*);
677     // nodeChildrenWillBeRemoved is used when removing all node children at once.
678     void nodeChildrenWillBeRemoved(ContainerNode&);
679     // nodeWillBeRemoved is only safe when removing one node at a time.
680     void nodeWillBeRemoved(Node&);
681     bool canReplaceChild(const Node& newChild, const Node& oldChild) const;
682
683     void didInsertText(Node*, unsigned offset, unsigned length);
684     void didRemoveText(Node*, unsigned offset, unsigned length);
685     void didMergeTextNodes(Text& oldNode, unsigned offset);
686     void didSplitTextNode(Text& oldNode);
687
688     void clearDOMWindow() { m_domWindow = 0; }
689     DOMWindow* domWindow() const { return m_domWindow; }
690
691     // Helper functions for forwarding DOMWindow event related tasks to the DOMWindow if it exists.
692     void setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener>);
693     EventListener* getWindowAttributeEventListener(const AtomicString& eventType);
694
695     PassRefPtrWillBeRawPtr<Event> createEvent(const String& eventType, ExceptionState&);
696
697     // keep track of what types of event listeners are registered, so we don't
698     // dispatch events unnecessarily
699     enum ListenerType {
700         DOMSUBTREEMODIFIED_LISTENER          = 1,
701         DOMNODEINSERTED_LISTENER             = 1 << 1,
702         DOMNODEREMOVED_LISTENER              = 1 << 2,
703         DOMNODEREMOVEDFROMDOCUMENT_LISTENER  = 1 << 3,
704         DOMNODEINSERTEDINTODOCUMENT_LISTENER = 1 << 4,
705         DOMCHARACTERDATAMODIFIED_LISTENER    = 1 << 5,
706         OVERFLOWCHANGED_LISTENER             = 1 << 6,
707         ANIMATIONEND_LISTENER                = 1 << 7,
708         ANIMATIONSTART_LISTENER              = 1 << 8,
709         ANIMATIONITERATION_LISTENER          = 1 << 9,
710         TRANSITIONEND_LISTENER               = 1 << 10,
711         SCROLL_LISTENER                      = 1 << 12
712         // 4 bits remaining
713     };
714
715     bool hasListenerType(ListenerType listenerType) const { return (m_listenerTypes & listenerType); }
716     void addListenerTypeIfNeeded(const AtomicString& eventType);
717
718     bool hasMutationObserversOfType(MutationObserver::MutationType type) const
719     {
720         return m_mutationObserverTypes & type;
721     }
722     bool hasMutationObservers() const { return m_mutationObserverTypes; }
723     void addMutationObserverTypes(MutationObserverOptions types) { m_mutationObserverTypes |= types; }
724
725     CSSStyleDeclaration* getOverrideStyle(Element*, const String& pseudoElt);
726
727     /**
728      * Handles a HTTP header equivalent set by a meta tag using <meta http-equiv="..." content="...">. This is called
729      * when a meta tag is encountered during document parsing, and also when a script dynamically changes or adds a meta
730      * tag. This enables scripts to use meta tags to perform refreshes and set expiry dates in addition to them being
731      * specified in a HTML file.
732      *
733      * @param equiv The http header name (value of the meta tag's "equiv" attribute)
734      * @param content The header value (value of the meta tag's "content" attribute)
735      * @param inDocumentHeadElement Is the element in the document's <head> element?
736      */
737     void processHttpEquiv(const AtomicString& equiv, const AtomicString& content, bool inDocumentHeadElement);
738     void updateViewportDescription();
739     void processReferrerPolicy(const String& policy);
740
741     // Returns the owning element in the parent document.
742     // Returns 0 if this is the top level document.
743     HTMLFrameOwnerElement* ownerElement() const;
744
745     String title() const { return m_title; }
746     void setTitle(const String&);
747
748     Element* titleElement() const { return m_titleElement.get(); }
749     void setTitleElement(const String& title, Element* titleElement);
750     void removeTitle(Element* titleElement);
751
752     const AtomicString& dir();
753     void setDir(const AtomicString&);
754
755     String cookie(ExceptionState&) const;
756     void setCookie(const String&, ExceptionState&);
757
758     const AtomicString& referrer() const;
759
760     String domain() const;
761     void setDomain(const String& newDomain, ExceptionState&);
762
763     String lastModified() const;
764
765     // The cookieURL is used to query the cookie database for this document's
766     // cookies. For example, if the cookie URL is http://example.com, we'll
767     // use the non-Secure cookies for example.com when computing
768     // document.cookie.
769     //
770     // Q: How is the cookieURL different from the document's URL?
771     // A: The two URLs are the same almost all the time.  However, if one
772     //    document inherits the security context of another document, it
773     //    inherits its cookieURL but not its URL.
774     //
775     const KURL& cookieURL() const { return m_cookieURL; }
776     void setCookieURL(const KURL& url) { m_cookieURL = url; }
777
778     const KURL& firstPartyForCookies() const;
779
780     // The following implements the rule from HTML 4 for what valid names are.
781     // To get this right for all the XML cases, we probably have to improve this or move it
782     // and make it sensitive to the type of document.
783     static bool isValidName(const String&);
784
785     // The following breaks a qualified name into a prefix and a local name.
786     // It also does a validity check, and returns false if the qualified name
787     // is invalid.  It also sets ExceptionCode when name is invalid.
788     static bool parseQualifiedName(const AtomicString& qualifiedName, AtomicString& prefix, AtomicString& localName, ExceptionState&);
789
790     // Checks to make sure prefix and namespace do not conflict (per DOM Core 3)
791     static bool hasValidNamespaceForElements(const QualifiedName&);
792     static bool hasValidNamespaceForAttributes(const QualifiedName&);
793
794     HTMLElement* body() const;
795     void setBody(PassRefPtr<HTMLElement>, ExceptionState&);
796
797     HTMLHeadElement* head();
798
799     // Decide which element is to define the viewport's overflow policy. If |rootStyle| is set, use
800     // that as the style for the root element, rather than obtaining it on our own. The reason for
801     // this is that style may not have been associated with the elements yet - in which case it may
802     // have been calculated on the fly (without associating it with the actual element) somewhere.
803     Element* viewportDefiningElement(RenderStyle* rootStyle = 0) const;
804
805     DocumentMarkerController& markers() const { return *m_markers; }
806
807     bool directionSetOnDocumentElement() const { return m_directionSetOnDocumentElement; }
808     bool writingModeSetOnDocumentElement() const { return m_writingModeSetOnDocumentElement; }
809     void setDirectionSetOnDocumentElement(bool b) { m_directionSetOnDocumentElement = b; }
810     void setWritingModeSetOnDocumentElement(bool b) { m_writingModeSetOnDocumentElement = b; }
811
812     bool execCommand(const String& command, bool userInterface = false, const String& value = String());
813     bool queryCommandEnabled(const String& command);
814     bool queryCommandIndeterm(const String& command);
815     bool queryCommandState(const String& command);
816     bool queryCommandSupported(const String& command);
817     String queryCommandValue(const String& command);
818
819     KURL openSearchDescriptionURL();
820
821     // designMode support
822     enum InheritedBool { off = false, on = true, inherit };
823     void setDesignMode(InheritedBool value);
824     InheritedBool getDesignMode() const;
825     bool inDesignMode() const;
826     String designMode() const;
827     void setDesignMode(const String&);
828
829     Document* parentDocument() const;
830     Document& topDocument() const;
831     WeakPtr<Document> contextDocument();
832
833     ScriptRunner* scriptRunner() { return m_scriptRunner.get(); }
834
835     HTMLScriptElement* currentScript() const { return !m_currentScriptStack.isEmpty() ? m_currentScriptStack.last().get() : 0; }
836     void pushCurrentScript(PassRefPtr<HTMLScriptElement>);
837     void popCurrentScript();
838
839     void applyXSLTransform(ProcessingInstruction* pi);
840     PassRefPtrWillBeRawPtr<Document> transformSourceDocument() { return m_transformSourceDocument; }
841     void setTransformSourceDocument(Document* doc) { m_transformSourceDocument = doc; }
842
843     void setTransformSource(PassOwnPtr<TransformSource>);
844     TransformSource* transformSource() const { return m_transformSource.get(); }
845
846     void incDOMTreeVersion() { ASSERT(m_lifecycle.stateAllowsTreeMutations()); m_domTreeVersion = ++s_globalTreeVersion; }
847     uint64_t domTreeVersion() const { return m_domTreeVersion; }
848
849     enum PendingSheetLayout { NoLayoutWithPendingSheets, DidLayoutWithPendingSheets, IgnoreLayoutWithPendingSheets };
850
851     bool didLayoutWithPendingStylesheets() const { return m_pendingSheetLayout == DidLayoutWithPendingSheets; }
852
853     bool hasNodesWithPlaceholderStyle() const { return m_hasNodesWithPlaceholderStyle; }
854     void setHasNodesWithPlaceholderStyle() { m_hasNodesWithPlaceholderStyle = true; }
855
856     Vector<IconURL> iconURLs(int iconTypesMask);
857
858     void setUseSecureKeyboardEntryWhenActive(bool);
859     bool useSecureKeyboardEntryWhenActive() const;
860
861     void updateFocusAppearanceSoon(bool restorePreviousSelection);
862     void cancelFocusAppearanceUpdate();
863
864     // Extension for manipulating canvas drawing contexts for use in CSS
865     void getCSSCanvasContext(const String& type, const String& name, int width, int height, bool&, RefPtrWillBeRawPtr<CanvasRenderingContext2D>&, bool&, RefPtrWillBeRawPtr<WebGLRenderingContext>&);
866     HTMLCanvasElement& getCSSCanvasElement(const String& name);
867
868     bool isDNSPrefetchEnabled() const { return m_isDNSPrefetchEnabled; }
869     void parseDNSPrefetchControlHeader(const String&);
870
871     // FIXME(crbug.com/305497): This should be removed once DOMWindow is an ExecutionContext.
872     virtual void postTask(PassOwnPtr<ExecutionContextTask>) OVERRIDE; // Executes the task on context's thread asynchronously.
873
874     virtual void tasksWereSuspended() OVERRIDE FINAL;
875     virtual void tasksWereResumed() OVERRIDE FINAL;
876     virtual void suspendScheduledTasks() OVERRIDE FINAL;
877     virtual void resumeScheduledTasks() OVERRIDE FINAL;
878     virtual bool tasksNeedSuspension() OVERRIDE FINAL;
879
880     void finishedParsing();
881
882     void setEncodingData(const DocumentEncodingData& newData);
883     const WTF::TextEncoding& encoding() const { return m_encodingData.encoding(); }
884
885     bool encodingWasDetectedHeuristically() const { return m_encodingData.wasDetectedHeuristically(); }
886     bool sawDecodingError() const { return m_encodingData.sawDecodingError(); }
887
888     void setAnnotatedRegionsDirty(bool f) { m_annotatedRegionsDirty = f; }
889     bool annotatedRegionsDirty() const { return m_annotatedRegionsDirty; }
890     bool hasAnnotatedRegions () const { return m_hasAnnotatedRegions; }
891     void setHasAnnotatedRegions(bool f) { m_hasAnnotatedRegions = f; }
892     const Vector<AnnotatedRegionValue>& annotatedRegions() const;
893     void setAnnotatedRegions(const Vector<AnnotatedRegionValue>&);
894
895     virtual void removeAllEventListeners() OVERRIDE FINAL;
896
897     const SVGDocumentExtensions* svgExtensions();
898     SVGDocumentExtensions& accessSVGExtensions();
899
900     void initSecurityContext();
901     void initSecurityContext(const DocumentInit&);
902     void initContentSecurityPolicy(const ContentSecurityPolicyResponseHeaders&);
903
904     bool allowInlineEventHandlers(Node*, EventListener*, const String& contextURL, const WTF::OrdinalNumber& contextLine);
905     bool allowExecutingScripts(Node*);
906
907     void statePopped(PassRefPtr<SerializedScriptValue>);
908
909     enum LoadEventProgress {
910         LoadEventNotRun,
911         LoadEventTried,
912         LoadEventInProgress,
913         LoadEventCompleted,
914         BeforeUnloadEventInProgress,
915         BeforeUnloadEventCompleted,
916         PageHideInProgress,
917         UnloadEventInProgress,
918         UnloadEventHandled
919     };
920     bool loadEventStillNeeded() const { return m_loadEventProgress == LoadEventNotRun; }
921     bool processingLoadEvent() const { return m_loadEventProgress == LoadEventInProgress; }
922     bool loadEventFinished() const { return m_loadEventProgress >= LoadEventCompleted; }
923     bool unloadStarted() const { return m_loadEventProgress >= PageHideInProgress; }
924
925     void setContainsPlugins() { m_containsPlugins = true; }
926     bool containsPlugins() const { return m_containsPlugins; }
927
928     virtual bool isContextThread() const OVERRIDE FINAL;
929     virtual bool isJSExecutionForbidden() const OVERRIDE FINAL { return false; }
930
931     bool containsValidityStyleRules() const { return m_containsValidityStyleRules; }
932     void setContainsValidityStyleRules() { m_containsValidityStyleRules = true; }
933
934     void enqueueResizeEvent();
935     void enqueueScrollEventForNode(Node*);
936     void enqueueAnimationFrameEvent(PassRefPtrWillBeRawPtr<Event>);
937
938     bool hasFullscreenElementStack() const { return m_hasFullscreenElementStack; }
939     void setHasFullscreenElementStack() { m_hasFullscreenElementStack = true; }
940
941     void webkitExitPointerLock();
942     Element* webkitPointerLockElement() const;
943
944     // Used to allow element that loads data without going through a FrameLoader to delay the 'load' event.
945     void incrementLoadEventDelayCount() { ++m_loadEventDelayCount; }
946     void decrementLoadEventDelayCount();
947     void checkLoadEventSoon();
948     bool isDelayingLoadEvent();
949     void loadPluginsSoon();
950
951     PassRefPtrWillBeRawPtr<Touch> createTouch(DOMWindow*, EventTarget*, int identifier, int pageX, int pageY, int screenX, int screenY, int radiusX, int radiusY, float rotationAngle, float force) const;
952     PassRefPtrWillBeRawPtr<TouchList> createTouchList(WillBeHeapVector<RefPtrWillBeMember<Touch> >&) const;
953
954     const DocumentTiming& timing() const { return m_documentTiming; }
955
956     int requestAnimationFrame(PassOwnPtr<RequestAnimationFrameCallback>);
957     void cancelAnimationFrame(int id);
958     void serviceScriptedAnimations(double monotonicAnimationStartTime);
959
960     virtual EventTarget* errorEventTarget() OVERRIDE FINAL;
961     virtual void logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack>) OVERRIDE FINAL;
962
963     void initDNSPrefetch();
964
965     bool hasTouchEventHandlers() const { return (m_touchEventTargets.get()) ? m_touchEventTargets->size() : false; }
966
967     // Called when a single touch event handler has been added or removed for a node.
968     // The Node should always be in this Document, except for child Documents which report
969     // themselves to their parent exactly once if they have any touch handlers.
970     // Handlers added/removed from the DOMWindow are reported as the Document.
971     void didAddTouchEventHandler(Node*);
972     void didRemoveTouchEventHandler(Node* handler) { didRemoveTouchEventHandler(handler, false); }
973
974     // Called whenever all touch event handlers have been removed for a node (such as when the
975     // node itself is being removed from the document).
976     void didClearTouchEventHandlers(Node* handler) { didRemoveTouchEventHandler(handler, true); }
977
978     const TouchEventTargetSet* touchEventTargets() const { return m_touchEventTargets.get(); }
979
980     bool isInDocumentWrite() { return m_writeRecursionDepth > 0; }
981
982     IntSize initialViewportSize() const;
983
984     // There are currently two parallel autosizing implementations: TextAutosizer and FastTextAutosizer.
985     // See http://tinyurl.com/chromium-fast-autosizer for more details.
986     TextAutosizer* textAutosizer();
987     FastTextAutosizer* fastTextAutosizer();
988
989     PassRefPtr<Element> createElement(const AtomicString& localName, const AtomicString& typeExtension, ExceptionState&);
990     PassRefPtr<Element> createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& typeExtension, ExceptionState&);
991     ScriptValue registerElement(WebCore::ScriptState*, const AtomicString& name, ExceptionState&);
992     ScriptValue registerElement(WebCore::ScriptState*, const AtomicString& name, const Dictionary& options, ExceptionState&, CustomElement::NameSet validNames = CustomElement::StandardNames);
993     CustomElementRegistrationContext* registrationContext() { return m_registrationContext.get(); }
994
995     void setImportsController(HTMLImportsController*);
996     HTMLImportsController* importsController() const { return m_importsController; }
997     HTMLImportLoader* importLoader() const;
998
999     bool haveImportsLoaded() const;
1000     void didLoadAllImports();
1001
1002     void adjustFloatQuadsForScrollAndAbsoluteZoom(Vector<FloatQuad>&, RenderObject&);
1003     void adjustFloatRectForScrollAndAbsoluteZoom(FloatRect&, RenderObject&);
1004
1005     bool hasActiveParser();
1006     unsigned activeParserCount() { return m_activeParserCount; }
1007     void incrementActiveParserCount() { ++m_activeParserCount; }
1008     void decrementActiveParserCount();
1009
1010     void setContextFeatures(ContextFeatures&);
1011     ContextFeatures& contextFeatures() const { return *m_contextFeatures; }
1012
1013     ElementDataCache* elementDataCache() { return m_elementDataCache.get(); }
1014
1015     void didLoadAllScriptBlockingResources();
1016     void didRemoveAllPendingStylesheet();
1017     void setNeedsNotifyRemoveAllPendingStylesheet() { m_needsNotifyRemoveAllPendingStylesheet = true; }
1018     void clearStyleResolver();
1019
1020     bool inStyleRecalc() const { return m_lifecycle.state() == DocumentLifecycle::InStyleRecalc; }
1021
1022     // Return a Locale for the default locale if the argument is null or empty.
1023     Locale& getCachedLocale(const AtomicString& locale = nullAtom);
1024
1025     AnimationClock& animationClock() { return *m_animationClock; }
1026     DocumentTimeline& timeline() const { return *m_timeline; }
1027     DocumentTimeline& transitionTimeline() const { return *m_transitionTimeline; }
1028     CompositorPendingAnimations& compositorPendingAnimations() { return m_compositorPendingAnimations; }
1029
1030     void addToTopLayer(Element*, const Element* before = 0);
1031     void removeFromTopLayer(Element*);
1032     const WillBeHeapVector<RefPtrWillBeMember<Element> >& topLayerElements() const { return m_topLayerElements; }
1033     HTMLDialogElement* activeModalDialog() const;
1034
1035     // A non-null m_templateDocumentHost implies that |this| was created by ensureTemplateDocument().
1036     bool isTemplateDocument() const { return !!m_templateDocumentHost; }
1037     Document& ensureTemplateDocument();
1038     Document* templateDocumentHost() { return m_templateDocumentHost; }
1039
1040     void didAssociateFormControl(Element*);
1041
1042     void addConsoleMessageWithRequestIdentifier(MessageSource, MessageLevel, const String& message, unsigned long requestIdentifier);
1043
1044     virtual DOMWindow* executingWindow() OVERRIDE FINAL;
1045     LocalFrame* executingFrame();
1046
1047     DocumentLifecycleNotifier& lifecycleNotifier();
1048     DocumentLifecycle& lifecycle() { return m_lifecycle; }
1049     bool isActive() const { return m_lifecycle.isActive(); }
1050     bool isStopped() const { return m_lifecycle.state() == DocumentLifecycle::Stopped; }
1051     bool isDisposed() const { return m_lifecycle.state() == DocumentLifecycle::Disposed; }
1052
1053     enum HttpRefreshType {
1054         HttpRefreshFromHeader,
1055         HttpRefreshFromMetaTag
1056     };
1057     void maybeHandleHttpRefresh(const String&, HttpRefreshType);
1058
1059     void updateSecurityOrigin(PassRefPtr<SecurityOrigin>);
1060     PassOwnPtr<LifecycleNotifier<Document> > createLifecycleNotifier();
1061
1062     void setHasViewportUnits() { m_hasViewportUnits = true; }
1063     bool hasViewportUnits() const { return m_hasViewportUnits; }
1064     void notifyResizeForViewportUnits();
1065
1066     void registerVisibilityObserver(DocumentVisibilityObserver*);
1067     void unregisterVisibilityObserver(DocumentVisibilityObserver*);
1068
1069     void updateStyleInvalidationIfNeeded();
1070
1071     virtual void trace(Visitor*) OVERRIDE;
1072
1073     bool hasElementsRequiringLayerUpdate() const { return m_layerUpdateElements.size(); }
1074     void didRecalculateStyleForElement() { ++m_styleRecalcElementCounter; }
1075
1076 protected:
1077     Document(const DocumentInit&, DocumentClassFlags = DefaultDocumentClass);
1078
1079     virtual void didUpdateSecurityOrigin() OVERRIDE FINAL;
1080
1081     void clearXMLVersion() { m_xmlVersion = String(); }
1082
1083     virtual void dispose() OVERRIDE;
1084
1085     virtual PassRefPtr<Document> cloneDocumentWithoutChildren();
1086
1087     bool importContainerNodeChildren(ContainerNode* oldContainerNode, PassRefPtr<ContainerNode> newContainerNode, ExceptionState&);
1088     void lockCompatibilityMode() { m_compatibilityModeLocked = true; }
1089
1090 private:
1091     friend class Node;
1092     friend class IgnoreDestructiveWriteCountIncrementer;
1093
1094     ScriptedAnimationController& ensureScriptedAnimationController();
1095     virtual SecurityContext& securityContext() OVERRIDE FINAL { return *this; }
1096     virtual EventQueue* eventQueue() const OVERRIDE FINAL;
1097
1098     // FIXME: Rename the StyleRecalc state to RenderTreeUpdate.
1099     bool hasPendingStyleRecalc() const { return m_lifecycle.state() == DocumentLifecycle::VisualUpdatePending; }
1100
1101     bool shouldScheduleRenderTreeUpdate() const;
1102     void scheduleRenderTreeUpdate();
1103
1104     bool needsFullRenderTreeUpdate() const;
1105     bool needsRenderTreeUpdate() const;
1106
1107     void inheritHtmlAndBodyElementStyles(StyleRecalcChange);
1108
1109     bool dirtyElementsForLayerUpdate();
1110     void updateDistributionIfNeeded();
1111     void updateUseShadowTreesIfNeeded();
1112     void evaluateMediaQueryListIfNeeded();
1113
1114     void updateRenderTree(StyleRecalcChange);
1115     void updateStyle(StyleRecalcChange);
1116
1117     void detachParser();
1118
1119     void clearWeakMembers(Visitor*);
1120
1121     virtual bool isDocument() const OVERRIDE FINAL { return true; }
1122
1123     virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
1124
1125     virtual String nodeName() const OVERRIDE FINAL;
1126     virtual NodeType nodeType() const OVERRIDE FINAL;
1127     virtual bool childTypeAllowed(NodeType) const OVERRIDE FINAL;
1128     virtual PassRefPtr<Node> cloneNode(bool deep = true) OVERRIDE FINAL;
1129     void cloneDataFromDocument(const Document&);
1130
1131     virtual void refExecutionContext() OVERRIDE FINAL { ref(); }
1132     virtual void derefExecutionContext() OVERRIDE FINAL { deref(); }
1133
1134     virtual const KURL& virtualURL() const OVERRIDE FINAL; // Same as url(), but needed for ExecutionContext to implement it without a performance loss for direct calls.
1135     virtual KURL virtualCompleteURL(const String&) const OVERRIDE FINAL; // Same as completeURL() for the same reason as above.
1136
1137     virtual void reportBlockedScriptExecutionToInspector(const String& directiveText) OVERRIDE FINAL;
1138     virtual void addMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState*) OVERRIDE FINAL;
1139     void internalAddMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack>, ScriptState*);
1140
1141     virtual double timerAlignmentInterval() const OVERRIDE FINAL;
1142
1143     void updateTitle(const String&);
1144     void updateFocusAppearanceTimerFired(Timer<Document>*);
1145     void updateBaseURL();
1146
1147     void executeScriptsWaitingForResourcesIfNeeded();
1148
1149     PassRefPtr<NodeList> handleZeroPadding(const HitTestRequest&, HitTestResult&) const;
1150
1151     void loadEventDelayTimerFired(Timer<Document>*);
1152     void pluginLoadingTimerFired(Timer<Document>*);
1153
1154     PageVisibilityState pageVisibilityState() const;
1155
1156     PassRefPtr<HTMLCollection> ensureCachedCollection(CollectionType);
1157
1158     // Note that dispatching a window load event may cause the DOMWindow to be detached from
1159     // the LocalFrame, so callers should take a reference to the DOMWindow (which owns us) to
1160     // prevent the Document from getting blown away from underneath them.
1161     void dispatchWindowLoadEvent();
1162
1163     void addListenerType(ListenerType listenerType) { m_listenerTypes |= listenerType; }
1164     void addMutationEventListenerTypeIfEnabled(ListenerType);
1165
1166     void didAssociateFormControlsTimerFired(Timer<Document>*);
1167
1168     void clearFocusedElementSoon();
1169     void clearFocusedElementTimerFired(Timer<Document>*);
1170
1171     void processHttpEquivDefaultStyle(const AtomicString& content);
1172     void processHttpEquivRefresh(const AtomicString& content);
1173     void processHttpEquivSetCookie(const AtomicString& content);
1174     void processHttpEquivXFrameOptions(const AtomicString& content);
1175     void processHttpEquivContentSecurityPolicy(const AtomicString& equiv, const AtomicString& content);
1176
1177     void didRemoveTouchEventHandler(Node*, bool clearAll);
1178
1179     bool haveStylesheetsLoaded() const;
1180
1181     DocumentLifecycle m_lifecycle;
1182
1183     bool m_hasNodesWithPlaceholderStyle;
1184     bool m_needsNotifyRemoveAllPendingStylesheet;
1185     bool m_evaluateMediaQueriesOnStyleRecalc;
1186
1187     // If we do ignore the pending stylesheet count, then we need to add a boolean
1188     // to track that this happened so that we can do a full repaint when the stylesheets
1189     // do eventually load.
1190     PendingSheetLayout m_pendingSheetLayout;
1191
1192     LocalFrame* m_frame;
1193     DOMWindow* m_domWindow;
1194     HTMLImportsController* m_importsController;
1195
1196     RefPtrWillBeMember<ResourceFetcher> m_fetcher;
1197     RefPtr<DocumentParser> m_parser;
1198     unsigned m_activeParserCount;
1199     RefPtrWillBeMember<ContextFeatures> m_contextFeatures;
1200
1201     bool m_wellFormed;
1202
1203     // Document URLs.
1204     KURL m_url; // Document.URL: The URL from which this document was retrieved.
1205     KURL m_baseURL; // Node.baseURI: The URL to use when resolving relative URLs.
1206     KURL m_baseURLOverride; // An alternative base URL that takes precedence over m_baseURL (but not m_baseElementURL).
1207     KURL m_baseElementURL; // The URL set by the <base> element.
1208     KURL m_cookieURL; // The URL to use for cookie access.
1209
1210     AtomicString m_baseTarget;
1211
1212     // Mime-type of the document in case it was cloned or created by XHR.
1213     AtomicString m_mimeType;
1214
1215     RefPtrWillBeMember<DocumentType> m_docType;
1216     OwnPtrWillBeMember<DOMImplementation> m_implementation;
1217
1218     RefPtrWillBeMember<CSSStyleSheet> m_elemSheet;
1219
1220     bool m_printing;
1221     bool m_paginatedForScreen;
1222
1223     CompatibilityMode m_compatibilityMode;
1224     bool m_compatibilityModeLocked; // This is cheaper than making setCompatibilityMode virtual.
1225
1226     bool m_hasAutofocused;
1227     Timer<Document> m_clearFocusedElementTimer;
1228     RefPtrWillBeMember<Element> m_autofocusElement;
1229     RefPtrWillBeMember<Element> m_focusedElement;
1230     RefPtrWillBeMember<Node> m_hoverNode;
1231     RefPtrWillBeMember<Element> m_activeHoverElement;
1232     RefPtrWillBeMember<Element> m_documentElement;
1233     UserActionElementSet m_userActionElements;
1234
1235     uint64_t m_domTreeVersion;
1236     static uint64_t s_globalTreeVersion;
1237
1238     HashSet<NodeIterator*> m_nodeIterators;
1239     HashSet<Range*> m_ranges;
1240
1241     unsigned short m_listenerTypes;
1242
1243     MutationObserverOptions m_mutationObserverTypes;
1244
1245     OwnPtrWillBeMember<StyleEngine> m_styleEngine;
1246     RefPtrWillBeMember<StyleSheetList> m_styleSheetList;
1247
1248     OwnPtrWillBeMember<FormController> m_formController;
1249
1250     TextLinkColors m_textLinkColors;
1251     const OwnPtr<VisitedLinkState> m_visitedLinkState;
1252
1253     bool m_visuallyOrdered;
1254     ReadyState m_readyState;
1255     bool m_isParsing;
1256
1257     bool m_gotoAnchorNeededAfterStylesheetsLoad;
1258     bool m_isDNSPrefetchEnabled;
1259     bool m_haveExplicitlyDisabledDNSPrefetch;
1260     bool m_containsValidityStyleRules;
1261     bool m_updateFocusAppearanceRestoresSelection;
1262     bool m_containsPlugins;
1263
1264     // http://www.whatwg.org/specs/web-apps/current-work/#ignore-destructive-writes-counter
1265     unsigned m_ignoreDestructiveWriteCount;
1266
1267     String m_title;
1268     String m_rawTitle;
1269     bool m_titleSetExplicitly;
1270     RefPtrWillBeMember<Element> m_titleElement;
1271
1272     OwnPtr<AXObjectCache> m_axObjectCache;
1273     OwnPtr<DocumentMarkerController> m_markers;
1274
1275     Timer<Document> m_updateFocusAppearanceTimer;
1276
1277     Element* m_cssTarget;
1278
1279     LoadEventProgress m_loadEventProgress;
1280
1281     double m_startTime;
1282
1283     OwnPtr<ScriptRunner> m_scriptRunner;
1284
1285     WillBeHeapVector<RefPtrWillBeMember<HTMLScriptElement> > m_currentScriptStack;
1286
1287     OwnPtr<TransformSource> m_transformSource;
1288     RefPtrWillBeMember<Document> m_transformSourceDocument;
1289
1290     String m_xmlEncoding;
1291     String m_xmlVersion;
1292     unsigned m_xmlStandalone : 2;
1293     unsigned m_hasXMLDeclaration : 1;
1294
1295     AtomicString m_contentLanguage;
1296
1297     DocumentEncodingData m_encodingData;
1298
1299     InheritedBool m_designMode;
1300
1301     HashSet<LiveNodeListBase*> m_listsInvalidatedAtDocument;
1302     unsigned m_nodeListCounts[numNodeListInvalidationTypes];
1303
1304     OwnPtr<SVGDocumentExtensions> m_svgExtensions;
1305
1306     Vector<AnnotatedRegionValue> m_annotatedRegions;
1307     bool m_hasAnnotatedRegions;
1308     bool m_annotatedRegionsDirty;
1309
1310     WillBeHeapHashMap<String, RefPtrWillBeMember<HTMLCanvasElement> > m_cssCanvasElements;
1311
1312     OwnPtr<SelectorQueryCache> m_selectorQueryCache;
1313
1314     bool m_useSecureKeyboardEntryWhenActive;
1315
1316     DocumentClassFlags m_documentClasses;
1317
1318     bool m_isViewSource;
1319     bool m_sawElementsInKnownNamespaces;
1320     bool m_isSrcdocDocument;
1321     bool m_isMobileDocument;
1322
1323     RenderView* m_renderView;
1324
1325     // FIXME: Oilpan: We should use a real weak pointer here.
1326     WeakPtrFactory<Document> m_weakFactory;
1327     WeakPtr<Document> m_contextDocument;
1328
1329     bool m_hasFullscreenElementStack; // For early return in FullscreenElementStack::fromIfExists()
1330
1331     WillBeHeapVector<RefPtrWillBeMember<Element> > m_topLayerElements;
1332
1333     int m_loadEventDelayCount;
1334     Timer<Document> m_loadEventDelayTimer;
1335     Timer<Document> m_pluginLoadingTimer;
1336
1337     ViewportDescription m_viewportDescription;
1338     ViewportDescription m_legacyViewportDescription;
1339     Length m_viewportDefaultMinWidth;
1340
1341     bool m_didSetReferrerPolicy;
1342     ReferrerPolicy m_referrerPolicy;
1343
1344     bool m_directionSetOnDocumentElement;
1345     bool m_writingModeSetOnDocumentElement;
1346     DocumentTiming m_documentTiming;
1347     RefPtrWillBeMember<MediaQueryMatcher> m_mediaQueryMatcher;
1348     bool m_writeRecursionIsTooDeep;
1349     unsigned m_writeRecursionDepth;
1350
1351     OwnPtr<TouchEventTargetSet> m_touchEventTargets;
1352
1353     RefPtr<ScriptedAnimationController> m_scriptedAnimationController;
1354     OwnPtr<MainThreadTaskRunner> m_taskRunner;
1355     OwnPtr<TextAutosizer> m_textAutosizer;
1356     OwnPtr<FastTextAutosizer> m_fastTextAutosizer;
1357
1358     RefPtr<CustomElementRegistrationContext> m_registrationContext;
1359
1360     void elementDataCacheClearTimerFired(Timer<Document>*);
1361     Timer<Document> m_elementDataCacheClearTimer;
1362
1363     OwnPtr<ElementDataCache> m_elementDataCache;
1364
1365 #ifndef NDEBUG
1366     bool m_didDispatchViewportPropertiesChanged;
1367 #endif
1368
1369     typedef HashMap<AtomicString, OwnPtr<Locale> > LocaleIdentifierToLocaleMap;
1370     LocaleIdentifierToLocaleMap m_localeCache;
1371
1372     OwnPtr<AnimationClock> m_animationClock;
1373     RefPtr<DocumentTimeline> m_timeline;
1374     RefPtr<DocumentTimeline> m_transitionTimeline;
1375     CompositorPendingAnimations m_compositorPendingAnimations;
1376
1377     RefPtrWillBeMember<Document> m_templateDocument;
1378     // With Oilpan the templateDocument and the templateDocumentHost
1379     // live and die together. Without Oilpan, the templateDocumentHost
1380     // is a manually managed backpointer from m_templateDocument.
1381     RawPtrWillBeMember<Document> m_templateDocumentHost;
1382
1383     Timer<Document> m_didAssociateFormControlsTimer;
1384     WillBeHeapHashSet<RefPtrWillBeMember<Element> > m_associatedFormControls;
1385
1386     HashSet<SVGUseElement*> m_useElementsNeedingUpdate;
1387     HashSet<Element*> m_layerUpdateElements;
1388
1389     bool m_hasViewportUnits;
1390
1391     typedef WillBeHeapHashSet<RawPtrWillBeWeakMember<DocumentVisibilityObserver> > DocumentVisibilityObserverSet;
1392     DocumentVisibilityObserverSet m_visibilityObservers;
1393
1394     int m_styleRecalcElementCounter;
1395 };
1396
1397 inline void Document::notifyRemovePendingSheetIfNeeded()
1398 {
1399     if (m_needsNotifyRemoveAllPendingStylesheet)
1400         didRemoveAllPendingStylesheet();
1401 }
1402
1403 inline bool Document::shouldOverrideLegacyDescription(ViewportDescription::Type origin)
1404 {
1405     // The different (legacy) meta tags have different priorities based on the type
1406     // regardless of which order they appear in the DOM. The priority is given by the
1407     // ViewportDescription::Type enum.
1408     return origin >= m_legacyViewportDescription.type;
1409 }
1410
1411 inline void Document::incrementNodeListWithIdNameCacheCount()
1412 {
1413     m_nodeListCounts[InvalidateOnIdNameAttrChange]++;
1414 }
1415
1416 inline void Document::decrementNodeListWithIdNameCacheCount()
1417 {
1418     ASSERT(m_nodeListCounts[InvalidateOnIdNameAttrChange] > 0);
1419     m_nodeListCounts[InvalidateOnIdNameAttrChange]--;
1420 }
1421
1422 inline void Document::scheduleRenderTreeUpdateIfNeeded()
1423 {
1424     // Inline early out to avoid the function calls below.
1425     if (hasPendingStyleRecalc())
1426         return;
1427     if (shouldScheduleRenderTreeUpdate() && needsRenderTreeUpdate())
1428         scheduleRenderTreeUpdate();
1429 }
1430
1431 DEFINE_TYPE_CASTS(Document, ExecutionContextClient, client, client->isDocument(), client.isDocument());
1432 DEFINE_TYPE_CASTS(Document, ExecutionContext, context, context->isDocument(), context.isDocument());
1433 DEFINE_NODE_TYPE_CASTS(Document, isDocumentNode());
1434
1435 #define DEFINE_DOCUMENT_TYPE_CASTS(thisType) \
1436     DEFINE_TYPE_CASTS(thisType, Document, document, document->is##thisType(), document.is##thisType())
1437
1438 // All these varations are needed to avoid ambiguous overloads with the Node and TreeScope versions.
1439 inline bool operator==(const Document& a, const Document& b) { return &a == &b; }
1440 inline bool operator==(const Document& a, const Document* b) { return &a == b; }
1441 inline bool operator==(const Document* a, const Document& b) { return a == &b; }
1442 inline bool operator!=(const Document& a, const Document& b) { return !(a == b); }
1443 inline bool operator!=(const Document& a, const Document* b) { return !(a == b); }
1444 inline bool operator!=(const Document* a, const Document& b) { return !(a == b); }
1445
1446 // Put these methods here, because they require the Document definition, but we really want to inline them.
1447
1448 inline bool Node::isDocumentNode() const
1449 {
1450     return this == document();
1451 }
1452
1453 Node* eventTargetNodeForDocument(Document*);
1454
1455 } // namespace WebCore
1456
1457 #endif // Document_h