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