• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
canContainRangeEndPoint()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&);
viewportDescription()271     const ViewportDescription& viewportDescription() const { return m_viewportDescription; }
viewportDefaultMinWidth()272     Length viewportDefaultMinWidth() const { return m_viewportDefaultMinWidth; }
273 
hasLegacyViewportTag()274     bool hasLegacyViewportTag() const { return m_legacyViewportDescription.isLegacyViewportType(); }
275 
276     void setReferrerPolicy(ReferrerPolicy);
referrerPolicy()277     ReferrerPolicy referrerPolicy() const { return m_referrerPolicy; }
278 
279     String outgoingReferrer();
280     String outgoingOrigin() const;
281 
282     void setDoctype(PassRefPtrWillBeRawPtr<DocumentType>);
doctype()283     DocumentType* doctype() const { return m_docType.get(); }
284 
285     DOMImplementation& implementation();
286 
documentElement()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 
inputEncoding()318     AtomicString inputEncoding() const { return Document::encodingName(); }
charset()319     AtomicString charset() const { return Document::encodingName(); }
characterSet()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 
contentLanguage()332     const AtomicString& contentLanguage() const { return m_contentLanguage; }
333     void setContentLanguage(const AtomicString&);
334 
xmlEncoding()335     String xmlEncoding() const { return m_xmlEncoding; }
xmlVersion()336     String xmlVersion() const { return m_xmlVersion; }
337     enum StandaloneStatus { StandaloneUnspecified, Standalone, NotStandalone };
xmlStandalone()338     bool xmlStandalone() const { return m_xmlStandalone == Standalone; }
xmlStandaloneStatus()339     StandaloneStatus xmlStandaloneStatus() const { return static_cast<StandaloneStatus>(m_xmlStandalone); }
hasXMLDeclaration()340     bool hasXMLDeclaration() const { return m_hasXMLDeclaration; }
341 
setXMLEncoding(const String & encoding)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&);
setHasXMLDeclaration(bool hasXMLDeclaration)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 
isHTMLDocument()368     bool isHTMLDocument() const { return m_documentClasses & HTMLDocumentClass; }
isXHTMLDocument()369     bool isXHTMLDocument() const { return m_documentClasses & XHTMLDocumentClass; }
isXMLDocument()370     bool isXMLDocument() const { return m_documentClasses & XMLDocumentClass; }
isImageDocument()371     bool isImageDocument() const { return m_documentClasses & ImageDocumentClass; }
isSVGDocument()372     bool isSVGDocument() const { return m_documentClasses & SVGDocumentClass; }
isPluginDocument()373     bool isPluginDocument() const { return m_documentClasses & PluginDocumentClass; }
isMediaDocument()374     bool isMediaDocument() const { return m_documentClasses & MediaDocumentClass; }
375 
376     bool hasSVGRootNode() const;
377 
378     bool isFrameSet() const;
379 
isSrcdocDocument()380     bool isSrcdocDocument() const { return m_isSrcdocDocument; }
isMobileDocument()381     bool isMobileDocument() const { return m_isMobileDocument; }
382 
isTransitionDocument()383     bool isTransitionDocument() const { return m_isTransitionDocument; }
setIsTransitionDocument()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 
isViewSource()397     bool isViewSource() const { return m_isViewSource; }
398     void setIsViewSource(bool);
399 
sawElementsInKnownNamespaces()400     bool sawElementsInKnownNamespaces() const { return m_sawElementsInKnownNamespaces; }
401 
isRenderingReady()402     bool isRenderingReady() const { return haveImportsLoaded() && haveStylesheetsLoaded(); }
isScriptExecutionReady()403     bool isScriptExecutionReady() const { return isRenderingReady(); }
404 
405     // This is a DOM function.
406     StyleSheetList* styleSheets();
407 
styleEngine()408     StyleEngine* styleEngine() { return m_styleEngine.get(); }
409 
gotoAnchorNeededAfterStylesheetsLoad()410     bool gotoAnchorNeededAfterStylesheetsLoad() { return m_gotoAnchorNeededAfterStylesheetsLoad; }
setGotoAnchorNeededAfterStylesheetsLoad(bool b)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);
addedStyleSheet(StyleSheet *)420     void addedStyleSheet(StyleSheet*) { styleResolverChanged(); }
421     void modifiedStyleSheet(StyleSheet*, StyleResolverUpdateMode = FullStyleUpdate);
changedSelectorWatch()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
frame()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;
updateRenderTreeIfNeeded()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 
fetcher()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 
renderView()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
visuallyOrdered()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 
wellFormed()529     bool wellFormed() const { return m_wellFormed; }
530 
url()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.
baseURL()536     const KURL& baseURL() const { return m_baseURL; }
537     void setBaseURLOverride(const KURL&);
baseURLOverride()538     const KURL& baseURLOverride() const { return m_baseURLOverride; }
baseElementURL()539     const KURL& baseElementURL() const { return m_baseElementURL; }
baseTarget()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();
parser()555     DocumentParser* parser() const { return m_parser.get(); }
556     ScriptableDocumentParser* scriptableDocumentParser() const;
557 
printing()558     bool printing() const { return m_printing; }
setPrinting(bool p)559     void setPrinting(bool p) { m_printing = p; }
560 
paginatedForScreen()561     bool paginatedForScreen() const { return m_paginatedForScreen; }
setPaginatedForScreen(bool p)562     void setPaginatedForScreen(bool p) { m_paginatedForScreen = p; }
563 
paginated()564     bool paginated() const { return printing() || paginatedForScreen(); }
565 
566     enum CompatibilityMode { QuirksMode, LimitedQuirksMode, NoQuirksMode };
567 
568     void setCompatibilityMode(CompatibilityMode m);
compatibilityMode()569     CompatibilityMode compatibilityMode() const { return m_compatibilityMode; }
570 
571     String compatMode() const;
572 
inQuirksMode()573     bool inQuirksMode() const { return m_compatibilityMode == QuirksMode; }
inLimitedQuirksMode()574     bool inLimitedQuirksMode() const { return m_compatibilityMode == LimitedQuirksMode; }
inNoQuirksMode()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);
parsing()586     bool parsing() const { return m_isParsing; }
587 
588     bool shouldScheduleLayout() const;
589     int elapsedTime() const;
590 
textLinkColors()591     TextLinkColors& textLinkColors() { return m_textLinkColors; }
visitedLinkState()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);
focusedElement()605     Element* focusedElement() const { return m_focusedElement.get(); }
userActionElements()606     UserActionElementSet& userActionElements()  { return m_userActionElements; }
userActionElements()607     const UserActionElementSet& userActionElements() const { return m_userActionElements; }
608     void setNeedsFocusedElementCheck();
609     void setAutofocusElement(Element*);
autofocusElement()610     Element* autofocusElement() const { return m_autofocusElement.get(); }
611 
612     void setActiveHoverElement(PassRefPtrWillBeRawPtr<Element>);
activeHoverElement()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*);
cssTarget()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 
clearDOMWindow()655     void clearDOMWindow() { m_domWindow = nullptr; }
domWindow()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 
hasListenerType(ListenerType listenerType)683     bool hasListenerType(ListenerType listenerType) const { return (m_listenerTypes & listenerType); }
684     void addListenerTypeIfNeeded(const AtomicString& eventType);
685 
hasMutationObserversOfType(MutationObserver::MutationType type)686     bool hasMutationObserversOfType(MutationObserver::MutationType type) const
687     {
688         return m_mutationObserverTypes & type;
689     }
hasMutationObservers()690     bool hasMutationObservers() const { return m_mutationObserverTypes; }
addMutationObserverTypes(MutationObserverOptions types)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 
title()717     String title() const { return m_title; }
718     void setTitle(const String&);
719 
titleElement()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     //
cookieURL()747     const KURL& cookieURL() const { return m_cookieURL; }
setCookieURL(const KURL & url)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 
markers()777     DocumentMarkerController& markers() const { return *m_markers; }
778 
directionSetOnDocumentElement()779     bool directionSetOnDocumentElement() const { return m_directionSetOnDocumentElement; }
writingModeSetOnDocumentElement()780     bool writingModeSetOnDocumentElement() const { return m_writingModeSetOnDocumentElement; }
setDirectionSetOnDocumentElement(bool b)781     void setDirectionSetOnDocumentElement(bool b) { m_directionSetOnDocumentElement = b; }
setWritingModeSetOnDocumentElement(bool 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 
scriptRunner()805     ScriptRunner* scriptRunner() { return m_scriptRunner.get(); }
806 
currentScript()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);
transformSourceDocument()812     PassRefPtrWillBeRawPtr<Document> transformSourceDocument() { return m_transformSourceDocument; }
setTransformSourceDocument(Document * doc)813     void setTransformSourceDocument(Document* doc) { m_transformSourceDocument = doc; }
814 
815     void setTransformSource(PassOwnPtr<TransformSource>);
transformSource()816     TransformSource* transformSource() const { return m_transformSource.get(); }
817 
incDOMTreeVersion()818     void incDOMTreeVersion() { ASSERT(m_lifecycle.stateAllowsTreeMutations()); m_domTreeVersion = ++s_globalTreeVersion; }
domTreeVersion()819     uint64_t domTreeVersion() const { return m_domTreeVersion; }
820 
821     enum PendingSheetLayout { NoLayoutWithPendingSheets, DidLayoutWithPendingSheets, IgnoreLayoutWithPendingSheets };
822 
didLayoutWithPendingStylesheets()823     bool didLayoutWithPendingStylesheets() const { return m_pendingSheetLayout == DidLayoutWithPendingSheets; }
ignoreLayoutWithPendingStylesheets()824     bool ignoreLayoutWithPendingStylesheets() const { return m_pendingSheetLayout == IgnoreLayoutWithPendingSheets; }
825 
hasNodesWithPlaceholderStyle()826     bool hasNodesWithPlaceholderStyle() const { return m_hasNodesWithPlaceholderStyle; }
setHasNodesWithPlaceholderStyle()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 
isDNSPrefetchEnabled()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);
encoding()863     const WTF::TextEncoding& encoding() const { return m_encodingData.encoding(); }
864 
encodingWasDetectedHeuristically()865     bool encodingWasDetectedHeuristically() const { return m_encodingData.wasDetectedHeuristically(); }
sawDecodingError()866     bool sawDecodingError() const { return m_encodingData.sawDecodingError(); }
867 
setAnnotatedRegionsDirty(bool f)868     void setAnnotatedRegionsDirty(bool f) { m_annotatedRegionsDirty = f; }
annotatedRegionsDirty()869     bool annotatedRegionsDirty() const { return m_annotatedRegionsDirty; }
hasAnnotatedRegions()870     bool hasAnnotatedRegions () const { return m_hasAnnotatedRegions; }
setHasAnnotatedRegions(bool f)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     };
loadEventStillNeeded()899     bool loadEventStillNeeded() const { return m_loadEventProgress == LoadEventNotRun; }
processingLoadEvent()900     bool processingLoadEvent() const { return m_loadEventProgress == LoadEventInProgress; }
loadEventFinished()901     bool loadEventFinished() const { return m_loadEventProgress >= LoadEventCompleted; }
unloadStarted()902     bool unloadStarted() const { return m_loadEventProgress >= PageHideInProgress; }
903 
setContainsPlugins()904     void setContainsPlugins() { m_containsPlugins = true; }
containsPlugins()905     bool containsPlugins() const { return m_containsPlugins; }
906 
907     virtual bool isContextThread() const OVERRIDE FINAL;
isJSExecutionForbidden()908     virtual bool isJSExecutionForbidden() const OVERRIDE FINAL { return false; }
909 
containsValidityStyleRules()910     bool containsValidityStyleRules() const { return m_containsValidityStyleRules; }
setContainsValidityStyleRules()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 
hasFullscreenSupplement()920     bool hasFullscreenSupplement() const { return m_hasFullscreenSupplement; }
setHasFullscreenSupplement()921     void setHasFullscreenSupplement() { m_hasFullscreenSupplement = true; }
922 
923     void exitPointerLock();
924     Element* pointerLockElement() const;
925 
926     // Used to allow element that loads data without going through a FrameLoader to delay the 'load' event.
incrementLoadEventDelayCount()927     void incrementLoadEventDelayCount() { ++m_loadEventDelayCount; }
928     void decrementLoadEventDelayCount();
929     void checkLoadEventSoon();
930     bool isDelayingLoadEvent();
931     void loadPluginsSoon();
932 
933     PassRefPtrWillBeRawPtr<Touch> createTouch(LocalDOMWindow*, EventTarget*, int identifier, double pageX, double pageY, double screenX, double screenY, double radiusX, double radiusY, float rotationAngle, float force) const;
934     PassRefPtrWillBeRawPtr<TouchList> createTouchList(WillBeHeapVector<RefPtrWillBeMember<Touch> >&) const;
935 
timing()936     const DocumentTiming& timing() const { return m_documentTiming; }
937 
938     int requestAnimationFrame(RequestAnimationFrameCallback*);
939     void cancelAnimationFrame(int id);
940     void serviceScriptedAnimations(double monotonicAnimationStartTime);
941 
942     virtual EventTarget* errorEventTarget() OVERRIDE FINAL;
943     virtual void logExceptionToConsole(const String& errorMessage, int scriptId, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtrWillBeRawPtr<ScriptCallStack>) OVERRIDE FINAL;
944 
945     void initDNSPrefetch();
946 
isInDocumentWrite()947     bool isInDocumentWrite() { return m_writeRecursionDepth > 0; }
948 
949     IntSize initialViewportSize() const;
950 
951     TextAutosizer* textAutosizer();
952 
953     PassRefPtrWillBeRawPtr<Element> createElement(const AtomicString& localName, const AtomicString& typeExtension, ExceptionState&);
954     PassRefPtrWillBeRawPtr<Element> createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& typeExtension, ExceptionState&);
955     ScriptValue registerElement(ScriptState*, const AtomicString& name, ExceptionState&);
956     ScriptValue registerElement(ScriptState*, const AtomicString& name, const Dictionary& options, ExceptionState&, CustomElement::NameSet validNames = CustomElement::StandardNames);
registrationContext()957     CustomElementRegistrationContext* registrationContext() { return m_registrationContext.get(); }
958     CustomElementMicrotaskRunQueue* customElementMicrotaskRunQueue();
959 
960     void setImportsController(HTMLImportsController*);
importsController()961     HTMLImportsController* importsController() const { return m_importsController; }
962     HTMLImportLoader* importLoader() const;
963 
964     bool haveImportsLoaded() const;
965     void didLoadAllImports();
966 
967     void adjustFloatQuadsForScrollAndAbsoluteZoom(Vector<FloatQuad>&, RenderObject&);
968     void adjustFloatRectForScrollAndAbsoluteZoom(FloatRect&, RenderObject&);
969 
970     bool hasActiveParser();
activeParserCount()971     unsigned activeParserCount() { return m_activeParserCount; }
incrementActiveParserCount()972     void incrementActiveParserCount() { ++m_activeParserCount; }
973     void decrementActiveParserCount();
974 
975     void setContextFeatures(ContextFeatures&);
contextFeatures()976     ContextFeatures& contextFeatures() const { return *m_contextFeatures; }
977 
elementDataCache()978     ElementDataCache* elementDataCache() { return m_elementDataCache.get(); }
979 
980     void didLoadAllScriptBlockingResources();
981     void didRemoveAllPendingStylesheet();
982     void clearStyleResolver();
983 
inStyleRecalc()984     bool inStyleRecalc() const { return m_lifecycle.state() == DocumentLifecycle::InStyleRecalc; }
985 
986     // Return a Locale for the default locale if the argument is null or empty.
987     Locale& getCachedLocale(const AtomicString& locale = nullAtom);
988 
animationClock()989     AnimationClock& animationClock() { return m_animationClock; }
timeline()990     AnimationTimeline& timeline() const { return *m_timeline; }
compositorPendingAnimations()991     CompositorPendingAnimations& compositorPendingAnimations() { return m_compositorPendingAnimations; }
992 
993     void addToTopLayer(Element*, const Element* before = 0);
994     void removeFromTopLayer(Element*);
topLayerElements()995     const WillBeHeapVector<RefPtrWillBeMember<Element> >& topLayerElements() const { return m_topLayerElements; }
996     HTMLDialogElement* activeModalDialog() const;
997 
998     // A non-null m_templateDocumentHost implies that |this| was created by ensureTemplateDocument().
isTemplateDocument()999     bool isTemplateDocument() const { return !!m_templateDocumentHost; }
1000     Document& ensureTemplateDocument();
templateDocumentHost()1001     Document* templateDocumentHost() { return m_templateDocumentHost; }
1002 
1003     void didAssociateFormControl(Element*);
1004 
1005     virtual void addConsoleMessage(PassRefPtrWillBeRawPtr<ConsoleMessage>) OVERRIDE FINAL;
1006 
1007     virtual LocalDOMWindow* executingWindow() OVERRIDE FINAL;
1008     LocalFrame* executingFrame();
1009 
1010     DocumentLifecycleNotifier& lifecycleNotifier();
lifecycle()1011     DocumentLifecycle& lifecycle() { return m_lifecycle; }
isActive()1012     bool isActive() const { return m_lifecycle.isActive(); }
isStopped()1013     bool isStopped() const { return m_lifecycle.state() == DocumentLifecycle::Stopped; }
isDisposed()1014     bool isDisposed() const { return m_lifecycle.state() == DocumentLifecycle::Disposed; }
1015 
1016     enum HttpRefreshType {
1017         HttpRefreshFromHeader,
1018         HttpRefreshFromMetaTag
1019     };
1020     void maybeHandleHttpRefresh(const String&, HttpRefreshType);
1021 
1022     void updateSecurityOrigin(PassRefPtr<SecurityOrigin>);
1023     PassOwnPtr<LifecycleNotifier<Document> > createLifecycleNotifier();
1024 
setHasViewportUnits()1025     void setHasViewportUnits() { m_hasViewportUnits = true; }
hasViewportUnits()1026     bool hasViewportUnits() const { return m_hasViewportUnits; }
1027     void notifyResizeForViewportUnits();
1028 
1029     void registerVisibilityObserver(DocumentVisibilityObserver*);
1030     void unregisterVisibilityObserver(DocumentVisibilityObserver*);
1031 
1032     void updateStyleInvalidationIfNeeded();
1033 
1034     virtual void trace(Visitor*) OVERRIDE;
1035 
hasSVGFilterElementsRequiringLayerUpdate()1036     bool hasSVGFilterElementsRequiringLayerUpdate() const { return m_layerUpdateSVGFilterElements.size(); }
didRecalculateStyleForElement()1037     void didRecalculateStyleForElement() { ++m_styleRecalcElementCounter; }
1038 
1039     AtomicString convertLocalName(const AtomicString&);
1040 
1041     virtual v8::Handle<v8::Object> wrap(v8::Handle<v8::Object> creationContext, v8::Isolate*) OVERRIDE;
1042     virtual v8::Handle<v8::Object> associateWithWrapper(const WrapperTypeInfo*, v8::Handle<v8::Object> wrapper, v8::Isolate*) OVERRIDE;
1043 
1044 protected:
1045     Document(const DocumentInit&, DocumentClassFlags = DefaultDocumentClass);
1046 
1047     virtual void didUpdateSecurityOrigin() OVERRIDE FINAL;
1048 
clearXMLVersion()1049     void clearXMLVersion() { m_xmlVersion = String(); }
1050 
1051 #if !ENABLE(OILPAN)
1052     virtual void dispose() OVERRIDE;
1053 #endif
1054 
1055     virtual PassRefPtrWillBeRawPtr<Document> cloneDocumentWithoutChildren();
1056 
1057     bool importContainerNodeChildren(ContainerNode* oldContainerNode, PassRefPtrWillBeRawPtr<ContainerNode> newContainerNode, ExceptionState&);
lockCompatibilityMode()1058     void lockCompatibilityMode() { m_compatibilityModeLocked = true; }
1059 
1060 private:
1061     friend class Node;
1062     friend class IgnoreDestructiveWriteCountIncrementer;
1063 
1064     bool isDocumentFragment() const WTF_DELETED_FUNCTION; // This will catch anyone doing an unnecessary check.
1065     bool isDocumentNode() const WTF_DELETED_FUNCTION; // This will catch anyone doing an unnecessary check.
1066     bool isElementNode() const WTF_DELETED_FUNCTION; // This will catch anyone doing an unnecessary check.
1067 
1068     ScriptedAnimationController& ensureScriptedAnimationController();
securityContext()1069     virtual SecurityContext& securityContext() OVERRIDE FINAL { return *this; }
1070     virtual EventQueue* eventQueue() const OVERRIDE FINAL;
1071 
1072     // FIXME: Rename the StyleRecalc state to RenderTreeUpdate.
hasPendingStyleRecalc()1073     bool hasPendingStyleRecalc() const { return m_lifecycle.state() == DocumentLifecycle::VisualUpdatePending; }
1074 
1075     bool shouldScheduleRenderTreeUpdate() const;
1076     void scheduleRenderTreeUpdate();
1077 
1078     bool needsFullRenderTreeUpdate() const;
1079 
1080     void inheritHtmlAndBodyElementStyles(StyleRecalcChange);
1081 
1082     bool dirtyElementsForLayerUpdate();
1083     void updateDistributionIfNeeded();
1084     void updateUseShadowTreesIfNeeded();
1085     void evaluateMediaQueryListIfNeeded();
1086 
1087     void updateRenderTree(StyleRecalcChange);
1088     void updateStyle(StyleRecalcChange);
1089 
1090     void detachParser();
1091 
1092     void clearWeakMembers(Visitor*);
1093 
isDocument()1094     virtual bool isDocument() const OVERRIDE FINAL { return true; }
1095 
1096     virtual void childrenChanged(const ChildrenChange&) OVERRIDE;
1097 
1098     virtual String nodeName() const OVERRIDE FINAL;
1099     virtual NodeType nodeType() const OVERRIDE FINAL;
1100     virtual bool childTypeAllowed(NodeType) const OVERRIDE FINAL;
1101     virtual PassRefPtrWillBeRawPtr<Node> cloneNode(bool deep = true) OVERRIDE FINAL;
1102     void cloneDataFromDocument(const Document&);
1103 
1104 #if !ENABLE(OILPAN)
refExecutionContext()1105     virtual void refExecutionContext() OVERRIDE FINAL { ref(); }
derefExecutionContext()1106     virtual void derefExecutionContext() OVERRIDE FINAL { deref(); }
1107 #endif
1108 
1109     virtual const KURL& virtualURL() const OVERRIDE FINAL; // Same as url(), but needed for ExecutionContext to implement it without a performance loss for direct calls.
1110     virtual KURL virtualCompleteURL(const String&) const OVERRIDE FINAL; // Same as completeURL() for the same reason as above.
1111 
1112     virtual void reportBlockedScriptExecutionToInspector(const String& directiveText) OVERRIDE FINAL;
1113 
1114     virtual double timerAlignmentInterval() const OVERRIDE FINAL;
1115 
1116     void updateTitle(const String&);
1117     void updateFocusAppearanceTimerFired(Timer<Document>*);
1118     void updateBaseURL();
1119 
1120     void executeScriptsWaitingForResourcesTimerFired(Timer<Document>*);
1121 
1122     void loadEventDelayTimerFired(Timer<Document>*);
1123     void pluginLoadingTimerFired(Timer<Document>*);
1124 
1125     PageVisibilityState pageVisibilityState() const;
1126 
1127     // Note that dispatching a window load event may cause the LocalDOMWindow to be detached from
1128     // the LocalFrame, so callers should take a reference to the LocalDOMWindow (which owns us) to
1129     // prevent the Document from getting blown away from underneath them.
1130     void dispatchWindowLoadEvent();
1131 
addListenerType(ListenerType listenerType)1132     void addListenerType(ListenerType listenerType) { m_listenerTypes |= listenerType; }
1133     void addMutationEventListenerTypeIfEnabled(ListenerType);
1134 
1135     void didAssociateFormControlsTimerFired(Timer<Document>*);
1136 
1137     void clearFocusedElementSoon();
1138     void clearFocusedElementTimerFired(Timer<Document>*);
1139 
1140     void processHttpEquivDefaultStyle(const AtomicString& content);
1141     void processHttpEquivRefresh(const AtomicString& content);
1142     void processHttpEquivSetCookie(const AtomicString& content);
1143     void processHttpEquivXFrameOptions(const AtomicString& content);
1144     void processHttpEquivContentSecurityPolicy(const AtomicString& equiv, const AtomicString& content);
1145 
1146     bool haveStylesheetsLoaded() const;
1147 
1148     void setHoverNode(PassRefPtrWillBeRawPtr<Node>);
hoverNode()1149     Node* hoverNode() const { return m_hoverNode.get(); }
1150 
1151     typedef HashSet<OwnPtr<EventFactoryBase> > EventFactorySet;
1152     static EventFactorySet& eventFactories();
1153 
1154     DocumentLifecycle m_lifecycle;
1155 
1156     bool m_hasNodesWithPlaceholderStyle;
1157     bool m_evaluateMediaQueriesOnStyleRecalc;
1158 
1159     // If we do ignore the pending stylesheet count, then we need to add a boolean
1160     // to track that this happened so that we can do a full repaint when the stylesheets
1161     // do eventually load.
1162     PendingSheetLayout m_pendingSheetLayout;
1163 
1164     RawPtrWillBeMember<LocalFrame> m_frame;
1165     RawPtrWillBeMember<LocalDOMWindow> m_domWindow;
1166     // FIXME: oilpan: when we get rid of the transition types change the
1167     // HTMLImportsController to not be a DocumentSupplement since it is
1168     // redundant with oilpan.
1169     RawPtrWillBeMember<HTMLImportsController> m_importsController;
1170 
1171     RefPtrWillBeMember<ResourceFetcher> m_fetcher;
1172     RefPtrWillBeMember<DocumentParser> m_parser;
1173     unsigned m_activeParserCount;
1174     RefPtrWillBeMember<ContextFeatures> m_contextFeatures;
1175 
1176     bool m_wellFormed;
1177 
1178     // Document URLs.
1179     KURL m_url; // Document.URL: The URL from which this document was retrieved.
1180     KURL m_baseURL; // Node.baseURI: The URL to use when resolving relative URLs.
1181     KURL m_baseURLOverride; // An alternative base URL that takes precedence over m_baseURL (but not m_baseElementURL).
1182     KURL m_baseElementURL; // The URL set by the <base> element.
1183     KURL m_cookieURL; // The URL to use for cookie access.
1184 
1185     AtomicString m_baseTarget;
1186 
1187     // Mime-type of the document in case it was cloned or created by XHR.
1188     AtomicString m_mimeType;
1189 
1190     RefPtrWillBeMember<DocumentType> m_docType;
1191     OwnPtrWillBeMember<DOMImplementation> m_implementation;
1192 
1193     RefPtrWillBeMember<CSSStyleSheet> m_elemSheet;
1194 
1195     bool m_printing;
1196     bool m_paginatedForScreen;
1197 
1198     CompatibilityMode m_compatibilityMode;
1199     bool m_compatibilityModeLocked; // This is cheaper than making setCompatibilityMode virtual.
1200 
1201     Timer<Document> m_executeScriptsWaitingForResourcesTimer;
1202 
1203     bool m_hasAutofocused;
1204     Timer<Document> m_clearFocusedElementTimer;
1205     RefPtrWillBeMember<Element> m_autofocusElement;
1206     RefPtrWillBeMember<Element> m_focusedElement;
1207     RefPtrWillBeMember<Node> m_hoverNode;
1208     RefPtrWillBeMember<Element> m_activeHoverElement;
1209     RefPtrWillBeMember<Element> m_documentElement;
1210     UserActionElementSet m_userActionElements;
1211 
1212     uint64_t m_domTreeVersion;
1213     static uint64_t s_globalTreeVersion;
1214 
1215     WillBeHeapHashSet<RawPtrWillBeWeakMember<NodeIterator> > m_nodeIterators;
1216     typedef WillBeHeapHashSet<RawPtrWillBeWeakMember<Range> > AttachedRangeSet;
1217     AttachedRangeSet m_ranges;
1218 
1219     unsigned short m_listenerTypes;
1220 
1221     MutationObserverOptions m_mutationObserverTypes;
1222 
1223     OwnPtrWillBeMember<StyleEngine> m_styleEngine;
1224     RefPtrWillBeMember<StyleSheetList> m_styleSheetList;
1225 
1226     OwnPtrWillBeMember<FormController> m_formController;
1227 
1228     TextLinkColors m_textLinkColors;
1229     const OwnPtrWillBeMember<VisitedLinkState> m_visitedLinkState;
1230 
1231     bool m_visuallyOrdered;
1232     ReadyState m_readyState;
1233     bool m_isParsing;
1234 
1235     bool m_gotoAnchorNeededAfterStylesheetsLoad;
1236     bool m_isDNSPrefetchEnabled;
1237     bool m_haveExplicitlyDisabledDNSPrefetch;
1238     bool m_containsValidityStyleRules;
1239     bool m_updateFocusAppearanceRestoresSelection;
1240     bool m_containsPlugins;
1241 
1242     // http://www.whatwg.org/specs/web-apps/current-work/#ignore-destructive-writes-counter
1243     unsigned m_ignoreDestructiveWriteCount;
1244 
1245     String m_title;
1246     String m_rawTitle;
1247     RefPtrWillBeMember<Element> m_titleElement;
1248 
1249     OwnPtr<AXObjectCache> m_axObjectCache;
1250     OwnPtrWillBeMember<DocumentMarkerController> m_markers;
1251 
1252     Timer<Document> m_updateFocusAppearanceTimer;
1253 
1254     RawPtrWillBeMember<Element> m_cssTarget;
1255 
1256     LoadEventProgress m_loadEventProgress;
1257 
1258     double m_startTime;
1259 
1260     OwnPtrWillBeMember<ScriptRunner> m_scriptRunner;
1261 
1262     WillBeHeapVector<RefPtrWillBeMember<HTMLScriptElement> > m_currentScriptStack;
1263 
1264     OwnPtr<TransformSource> m_transformSource;
1265     RefPtrWillBeMember<Document> m_transformSourceDocument;
1266 
1267     String m_xmlEncoding;
1268     String m_xmlVersion;
1269     unsigned m_xmlStandalone : 2;
1270     unsigned m_hasXMLDeclaration : 1;
1271 
1272     AtomicString m_contentLanguage;
1273 
1274     DocumentEncodingData m_encodingData;
1275 
1276     InheritedBool m_designMode;
1277 
1278     WillBeHeapHashSet<RawPtrWillBeWeakMember<const LiveNodeListBase> > m_listsInvalidatedAtDocument;
1279 #if ENABLE(OILPAN)
1280     // Oilpan keeps track of all registered NodeLists.
1281     //
1282     // FIXME: Oilpan: improve - only need to know if a NodeList
1283     // is currently alive or not for the different types.
1284     HeapHashSet<WeakMember<const LiveNodeListBase> > m_nodeLists[numNodeListInvalidationTypes];
1285 #else
1286     unsigned m_nodeListCounts[numNodeListInvalidationTypes];
1287 #endif
1288 
1289     OwnPtrWillBeMember<SVGDocumentExtensions> m_svgExtensions;
1290 
1291     Vector<AnnotatedRegionValue> m_annotatedRegions;
1292     bool m_hasAnnotatedRegions;
1293     bool m_annotatedRegionsDirty;
1294 
1295     WillBeHeapHashMap<String, RefPtrWillBeMember<HTMLCanvasElement> > m_cssCanvasElements;
1296 
1297     OwnPtr<SelectorQueryCache> m_selectorQueryCache;
1298 
1299     bool m_useSecureKeyboardEntryWhenActive;
1300 
1301     DocumentClassFlags m_documentClasses;
1302 
1303     bool m_isViewSource;
1304     bool m_sawElementsInKnownNamespaces;
1305     bool m_isSrcdocDocument;
1306     bool m_isMobileDocument;
1307     bool m_isTransitionDocument;
1308 
1309     RenderView* m_renderView;
1310 
1311 #if !ENABLE(OILPAN)
1312     WeakPtrFactory<Document> m_weakFactory;
1313 #endif
1314     WeakPtrWillBeWeakMember<Document> m_contextDocument;
1315 
1316     bool m_hasFullscreenSupplement; // For early return in Fullscreen::fromIfExists()
1317 
1318     WillBeHeapVector<RefPtrWillBeMember<Element> > m_topLayerElements;
1319 
1320     int m_loadEventDelayCount;
1321     Timer<Document> m_loadEventDelayTimer;
1322     Timer<Document> m_pluginLoadingTimer;
1323 
1324     ViewportDescription m_viewportDescription;
1325     ViewportDescription m_legacyViewportDescription;
1326     Length m_viewportDefaultMinWidth;
1327 
1328     bool m_didSetReferrerPolicy;
1329     ReferrerPolicy m_referrerPolicy;
1330 
1331     bool m_directionSetOnDocumentElement;
1332     bool m_writingModeSetOnDocumentElement;
1333     DocumentTiming m_documentTiming;
1334     RefPtrWillBeMember<MediaQueryMatcher> m_mediaQueryMatcher;
1335     bool m_writeRecursionIsTooDeep;
1336     unsigned m_writeRecursionDepth;
1337 
1338     RefPtrWillBeMember<ScriptedAnimationController> m_scriptedAnimationController;
1339     OwnPtr<MainThreadTaskRunner> m_taskRunner;
1340     OwnPtrWillBeMember<TextAutosizer> m_textAutosizer;
1341 
1342     RefPtrWillBeMember<CustomElementRegistrationContext> m_registrationContext;
1343     RefPtrWillBeMember<CustomElementMicrotaskRunQueue> m_customElementMicrotaskRunQueue;
1344 
1345     void elementDataCacheClearTimerFired(Timer<Document>*);
1346     Timer<Document> m_elementDataCacheClearTimer;
1347 
1348     OwnPtrWillBeMember<ElementDataCache> m_elementDataCache;
1349 
1350     typedef HashMap<AtomicString, OwnPtr<Locale> > LocaleIdentifierToLocaleMap;
1351     LocaleIdentifierToLocaleMap m_localeCache;
1352 
1353     AnimationClock m_animationClock;
1354     RefPtrWillBeMember<AnimationTimeline> m_timeline;
1355     CompositorPendingAnimations m_compositorPendingAnimations;
1356 
1357     RefPtrWillBeMember<Document> m_templateDocument;
1358     // With Oilpan the templateDocument and the templateDocumentHost
1359     // live and die together. Without Oilpan, the templateDocumentHost
1360     // is a manually managed backpointer from m_templateDocument.
1361     RawPtrWillBeMember<Document> m_templateDocumentHost;
1362 
1363     Timer<Document> m_didAssociateFormControlsTimer;
1364     WillBeHeapHashSet<RefPtrWillBeMember<Element> > m_associatedFormControls;
1365 
1366     WillBeHeapHashSet<RawPtrWillBeMember<SVGUseElement> > m_useElementsNeedingUpdate;
1367     WillBeHeapHashSet<RawPtrWillBeMember<Element> > m_layerUpdateSVGFilterElements;
1368 
1369     bool m_hasViewportUnits;
1370 
1371     typedef WillBeHeapHashSet<RawPtrWillBeWeakMember<DocumentVisibilityObserver> > DocumentVisibilityObserverSet;
1372     DocumentVisibilityObserverSet m_visibilityObservers;
1373 
1374     int m_styleRecalcElementCounter;
1375 };
1376 
shouldOverrideLegacyDescription(ViewportDescription::Type origin)1377 inline bool Document::shouldOverrideLegacyDescription(ViewportDescription::Type origin)
1378 {
1379     // The different (legacy) meta tags have different priorities based on the type
1380     // regardless of which order they appear in the DOM. The priority is given by the
1381     // ViewportDescription::Type enum.
1382     return origin >= m_legacyViewportDescription.type;
1383 }
1384 
scheduleRenderTreeUpdateIfNeeded()1385 inline void Document::scheduleRenderTreeUpdateIfNeeded()
1386 {
1387     // Inline early out to avoid the function calls below.
1388     if (hasPendingStyleRecalc())
1389         return;
1390     if (shouldScheduleRenderTreeUpdate() && needsRenderTreeUpdate())
1391         scheduleRenderTreeUpdate();
1392 }
1393 
1394 DEFINE_TYPE_CASTS(Document, ExecutionContext, context, context->isDocument(), context.isDocument());
1395 DEFINE_NODE_TYPE_CASTS(Document, isDocumentNode());
1396 
1397 #define DEFINE_DOCUMENT_TYPE_CASTS(thisType) \
1398     DEFINE_TYPE_CASTS(thisType, Document, document, document->is##thisType(), document.is##thisType())
1399 
1400 // This is needed to avoid ambiguous overloads with the Node and TreeScope versions.
DEFINE_COMPARISON_OPERATORS_WITH_REFERENCES(Document)1401 DEFINE_COMPARISON_OPERATORS_WITH_REFERENCES(Document)
1402 
1403 // Put these methods here, because they require the Document definition, but we really want to inline them.
1404 
1405 inline bool Node::isDocumentNode() const
1406 {
1407     return this == document();
1408 }
1409 
1410 Node* eventTargetNodeForDocument(Document*);
1411 
1412 } // namespace blink
1413 
1414 #ifndef NDEBUG
1415 // Outside the WebCore namespace for ease of invocation from gdb.
1416 void showLiveDocumentInstances();
1417 #endif
1418 
1419 #endif // Document_h
1420