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