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