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