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.
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.
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.
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.
31 #include "bindings/v8/ExceptionStatePlaceholder.h"
32 #include "bindings/v8/ScriptValue.h"
33 #include "core/animation/CompositorPendingAnimations.h"
34 #include "core/dom/ContainerNode.h"
35 #include "core/dom/DocumentEncodingData.h"
36 #include "core/dom/DocumentInit.h"
37 #include "core/dom/DocumentLifecycle.h"
38 #include "core/dom/DocumentSupplementable.h"
39 #include "core/dom/DocumentTiming.h"
40 #include "core/dom/ExecutionContext.h"
41 #include "core/dom/IconURL.h"
42 #include "core/dom/MutationObserver.h"
43 #include "core/dom/QualifiedName.h"
44 #include "core/dom/TextLinkColors.h"
45 #include "core/dom/TreeScope.h"
46 #include "core/dom/UserActionElementSet.h"
47 #include "core/dom/ViewportDescription.h"
48 #include "core/dom/custom/CustomElement.h"
49 #include "core/html/CollectionType.h"
50 #include "core/page/FocusType.h"
51 #include "core/page/PageVisibilityState.h"
52 #include "core/rendering/HitTestRequest.h"
53 #include "platform/Length.h"
54 #include "platform/Timer.h"
55 #include "platform/heap/Handle.h"
56 #include "platform/weborigin/KURL.h"
57 #include "platform/weborigin/ReferrerPolicy.h"
58 #include "wtf/HashSet.h"
59 #include "wtf/OwnPtr.h"
60 #include "wtf/PassOwnPtr.h"
61 #include "wtf/PassRefPtr.h"
62 #include "wtf/WeakPtr.h"
70 class CSSFontSelector;
71 class CSSStyleDeclaration;
73 class CSSStyleSheetResource;
74 class CanvasRenderingContext2D;
78 class ContentSecurityPolicyResponseHeaders;
79 class ContextFeatures;
80 class CustomElementRegistrationContext;
81 class DOMImplementation;
86 class DocumentFragment;
87 class DocumentLifecycleNotifier;
88 class DocumentLifecycleObserver;
90 class DocumentMarkerController;
93 class DocumentTimeline;
96 class ElementDataCache;
100 class FastTextAutosizer;
104 class FormController;
108 class HTMLAllCollection;
109 class HTMLCanvasElement;
110 class HTMLCollection;
111 class HTMLDialogElement;
114 class HTMLFrameOwnerElement;
115 class HTMLHeadElement;
116 class HTMLIFrameElement;
118 class HTMLImportLoader;
119 class HTMLImportsController;
120 class HTMLMapElement;
121 class HTMLNameCollection;
122 class HTMLScriptElement;
123 class HitTestRequest;
129 class LiveNodeListBase;
132 class MainThreadTaskRunner;
133 class MediaQueryList;
134 class MediaQueryMatcher;
135 class MouseEventWithHitTestResults;
139 class PlatformMouseEvent;
140 class ProcessingInstruction;
142 class RegisteredEventListener;
144 class RequestAnimationFrameCallback;
145 class ResourceFetcher;
146 class SVGDocumentExtensions;
148 class ScriptElementData;
149 class ScriptResource;
151 class ScriptableDocumentParser;
152 class ScriptedAnimationController;
153 class SecurityOrigin;
154 class SegmentedString;
155 class SelectorQueryCache;
156 class SerializedScriptValue;
161 class StyleSheetContents;
162 class StyleSheetList;
167 class TransformSource;
169 class VisitedLinkState;
170 class WebGLRenderingContext;
171 class XMLHttpRequest;
173 struct AnnotatedRegionValue;
175 typedef int ExceptionCode;
177 enum RecalcStyleTime {
178 RecalcStyleImmediately, // synchronous
179 RecalcStyleDeferred // asynchronous
182 enum StyleResolverUpdateMode {
183 // Discards the StyleResolver and rebuilds it.
185 // Attempts to use StyleInvalidationAnalysis to avoid discarding the entire StyleResolver.
189 enum NodeListInvalidationType {
190 DoNotInvalidateOnAttributeChanges = 0,
191 InvalidateOnClassAttrChange,
192 InvalidateOnIdNameAttrChange,
193 InvalidateOnNameAttrChange,
194 InvalidateOnForAttrChange,
195 InvalidateForFormControls,
196 InvalidateOnHRefAttrChange,
197 InvalidateOnAnyAttrChange,
199 const int numNodeListInvalidationTypes = InvalidateOnAnyAttrChange + 1;
201 typedef HashCountedSet<Node*> TouchEventTargetSet;
204 DefaultDocumentClass = 0,
205 HTMLDocumentClass = 1,
206 XHTMLDocumentClass = 1 << 1,
207 ImageDocumentClass = 1 << 2,
208 PluginDocumentClass = 1 << 3,
209 MediaDocumentClass = 1 << 4,
210 SVGDocumentClass = 1 << 5,
211 XMLDocumentClass = 1 << 6,
214 typedef unsigned char DocumentClassFlags;
218 class DocumentVisibilityObserver : public WillBeGarbageCollectedMixin {
220 DocumentVisibilityObserver(Document&);
221 virtual ~DocumentVisibilityObserver();
223 virtual void didChangeVisibilityState(PageVisibilityState) = 0;
225 // Classes that inherit Node and DocumentVisibilityObserver must have a
226 // virtual override of Node::didMoveToNewDocument that calls
227 // DocumentVisibilityObserver::setDocument
228 void setObservedDocument(Document&);
231 void registerObserver(Document&);
232 void unregisterObserver();
233 Document* m_document;
236 class Document : public ContainerNode, public TreeScope, public SecurityContext, public ExecutionContext, public ExecutionContextClient
237 , public DocumentSupplementable, public LifecycleContext<Document> {
238 WILL_BE_USING_GARBAGE_COLLECTED_MIXIN(Document);
240 static PassRefPtr<Document> create(const DocumentInit& initializer = DocumentInit())
242 return adoptRef(new Document(initializer));
246 MediaQueryMatcher& mediaQueryMatcher();
248 void mediaQueryAffectingValueChanged();
250 using ContainerNode::ref;
251 using ContainerNode::deref;
252 using SecurityContext::securityOrigin;
253 using SecurityContext::contentSecurityPolicy;
254 using ExecutionContextClient::addConsoleMessage;
255 using TreeScope::getElementById;
257 virtual bool canContainRangeEndPoint() const OVERRIDE { return true; }
259 SelectorQueryCache& selectorQueryCache();
262 Element* activeElement() const;
263 bool hasFocus() const;
265 // DOM methods & attributes for Document
267 DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecopy);
268 DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecut);
269 DEFINE_ATTRIBUTE_EVENT_LISTENER(beforepaste);
270 DEFINE_ATTRIBUTE_EVENT_LISTENER(copy);
271 DEFINE_ATTRIBUTE_EVENT_LISTENER(cut);
272 DEFINE_ATTRIBUTE_EVENT_LISTENER(paste);
273 DEFINE_ATTRIBUTE_EVENT_LISTENER(pointerlockchange);
274 DEFINE_ATTRIBUTE_EVENT_LISTENER(pointerlockerror);
275 DEFINE_ATTRIBUTE_EVENT_LISTENER(readystatechange);
276 DEFINE_ATTRIBUTE_EVENT_LISTENER(search);
277 DEFINE_ATTRIBUTE_EVENT_LISTENER(securitypolicyviolation);
278 DEFINE_ATTRIBUTE_EVENT_LISTENER(selectionchange);
279 DEFINE_ATTRIBUTE_EVENT_LISTENER(selectstart);
280 DEFINE_ATTRIBUTE_EVENT_LISTENER(touchcancel);
281 DEFINE_ATTRIBUTE_EVENT_LISTENER(touchend);
282 DEFINE_ATTRIBUTE_EVENT_LISTENER(touchmove);
283 DEFINE_ATTRIBUTE_EVENT_LISTENER(touchstart);
284 DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitfullscreenchange);
285 DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitfullscreenerror);
286 DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitpointerlockchange);
287 DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitpointerlockerror);
288 DEFINE_ATTRIBUTE_EVENT_LISTENER(wheel);
290 bool shouldMergeWithLegacyDescription(ViewportDescription::Type);
291 bool shouldOverrideLegacyDescription(ViewportDescription::Type);
292 void setViewportDescription(const ViewportDescription&);
293 const ViewportDescription& viewportDescription() const { return m_viewportDescription; }
294 Length viewportDefaultMinWidth() const { return m_viewportDefaultMinWidth; }
297 bool didDispatchViewportPropertiesChanged() const { return m_didDispatchViewportPropertiesChanged; }
299 bool hasLegacyViewportTag() const { return m_legacyViewportDescription.isLegacyViewportType(); }
301 void setReferrerPolicy(ReferrerPolicy);
302 ReferrerPolicy referrerPolicy() const { return m_referrerPolicy; }
304 String outgoingReferrer();
305 String outgoingOrigin() const;
307 void setDoctype(PassRefPtr<DocumentType>);
308 DocumentType* doctype() const { return m_docType.get(); }
310 DOMImplementation& implementation();
312 Element* documentElement() const
314 return m_documentElement.get();
317 bool hasManifest() const;
319 Location* location() const;
321 PassRefPtr<Element> createElement(const AtomicString& name, ExceptionState&);
322 PassRefPtr<DocumentFragment> createDocumentFragment();
323 PassRefPtr<Text> createTextNode(const String& data);
324 PassRefPtr<Comment> createComment(const String& data);
325 PassRefPtr<CDATASection> createCDATASection(const String& data, ExceptionState&);
326 PassRefPtr<ProcessingInstruction> createProcessingInstruction(const String& target, const String& data, ExceptionState&);
327 PassRefPtr<Attr> createAttribute(const AtomicString& name, ExceptionState&);
328 PassRefPtr<Attr> createAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState&, bool shouldIgnoreNamespaceChecks = false);
329 PassRefPtr<Node> importNode(Node* importedNode, ExceptionState&);
330 PassRefPtr<Node> importNode(Node* importedNode, bool deep, ExceptionState&);
331 PassRefPtr<Element> createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState&);
332 PassRefPtr<Element> createElement(const QualifiedName&, bool createdByParser);
334 bool regionBasedColumnsEnabled() const;
337 * Retrieve all nodes that intersect a rect in the window's document, until it is fully enclosed by
338 * the boundaries of a node.
340 * @param centerX x reference for the rectangle in CSS pixels
341 * @param centerY y reference for the rectangle in CSS pixels
342 * @param topPadding How much to expand the top of the rectangle
343 * @param rightPadding How much to expand the right of the rectangle
344 * @param bottomPadding How much to expand the bottom of the rectangle
345 * @param leftPadding How much to expand the left of the rectangle
347 PassRefPtr<NodeList> nodesFromRect(int centerX, int centerY,
348 unsigned topPadding, unsigned rightPadding, unsigned bottomPadding, unsigned leftPadding,
349 HitTestRequest::HitTestRequestType hitType = HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent) const;
350 Element* elementFromPoint(int x, int y) const;
351 PassRefPtrWillBeRawPtr<Range> caretRangeFromPoint(int x, int y);
353 String readyState() const;
355 String defaultCharset() const;
357 AtomicString inputEncoding() const { return Document::encodingName(); }
358 AtomicString charset() const { return Document::encodingName(); }
359 AtomicString characterSet() const { return Document::encodingName(); }
361 AtomicString encodingName() const;
363 void setCharset(const String&);
365 void setContent(const String&);
367 String suggestedMIMEType() const;
368 void setMimeType(const AtomicString&);
369 AtomicString contentType() const; // DOM 4 document.contentType
371 const AtomicString& contentLanguage() const { return m_contentLanguage; }
372 void setContentLanguage(const AtomicString&);
374 String xmlEncoding() const { return m_xmlEncoding; }
375 String xmlVersion() const { return m_xmlVersion; }
376 enum StandaloneStatus { StandaloneUnspecified, Standalone, NotStandalone };
377 bool xmlStandalone() const { return m_xmlStandalone == Standalone; }
378 StandaloneStatus xmlStandaloneStatus() const { return static_cast<StandaloneStatus>(m_xmlStandalone); }
379 bool hasXMLDeclaration() const { return m_hasXMLDeclaration; }
381 void setXMLEncoding(const String& encoding) { m_xmlEncoding = encoding; } // read-only property, only to be set from XMLDocumentParser
382 void setXMLVersion(const String&, ExceptionState&);
383 void setXMLStandalone(bool, ExceptionState&);
384 void setHasXMLDeclaration(bool hasXMLDeclaration) { m_hasXMLDeclaration = hasXMLDeclaration ? 1 : 0; }
386 virtual KURL baseURI() const OVERRIDE FINAL;
388 String visibilityState() const;
390 void didChangeVisibilityState();
392 PassRefPtr<Node> adoptNode(PassRefPtr<Node> source, ExceptionState&);
394 PassRefPtr<HTMLCollection> images();
395 PassRefPtr<HTMLCollection> embeds();
396 PassRefPtr<HTMLCollection> applets();
397 PassRefPtr<HTMLCollection> links();
398 PassRefPtr<HTMLCollection> forms();
399 PassRefPtr<HTMLCollection> anchors();
400 PassRefPtr<HTMLCollection> scripts();
401 PassRefPtr<HTMLAllCollection> allForBinding();
402 PassRefPtr<HTMLAllCollection> all();
404 PassRefPtr<HTMLCollection> windowNamedItems(const AtomicString& name);
405 PassRefPtr<HTMLCollection> documentNamedItems(const AtomicString& name);
407 bool isHTMLDocument() const { return m_documentClasses & HTMLDocumentClass; }
408 bool isXHTMLDocument() const { return m_documentClasses & XHTMLDocumentClass; }
409 bool isXMLDocument() const { return m_documentClasses & XMLDocumentClass; }
410 bool isImageDocument() const { return m_documentClasses & ImageDocumentClass; }
411 bool isSVGDocument() const { return m_documentClasses & SVGDocumentClass; }
412 bool isPluginDocument() const { return m_documentClasses & PluginDocumentClass; }
413 bool isMediaDocument() const { return m_documentClasses & MediaDocumentClass; }
415 bool hasSVGRootNode() const;
417 bool isFrameSet() const;
419 bool isSrcdocDocument() const { return m_isSrcdocDocument; }
420 bool isMobileDocument() const { return m_isMobileDocument; }
422 StyleResolver* styleResolver() const;
423 StyleResolver& ensureStyleResolver() const;
425 bool isViewSource() const { return m_isViewSource; }
426 void setIsViewSource(bool);
428 bool sawElementsInKnownNamespaces() const { return m_sawElementsInKnownNamespaces; }
430 void notifyRemovePendingSheetIfNeeded();
432 bool isRenderingReady() const { return haveImportsLoaded() && haveStylesheetsLoaded(); }
433 bool isScriptExecutionReady() const { return isRenderingReady(); }
435 // This is a DOM function.
436 StyleSheetList* styleSheets();
438 StyleEngine* styleEngine() { return m_styleEngine.get(); }
440 bool gotoAnchorNeededAfterStylesheetsLoad() { return m_gotoAnchorNeededAfterStylesheetsLoad; }
441 void setGotoAnchorNeededAfterStylesheetsLoad(bool b) { m_gotoAnchorNeededAfterStylesheetsLoad = b; }
443 // Called when one or more stylesheets in the document may have been added, removed, or changed.
444 void styleResolverChanged(RecalcStyleTime, StyleResolverUpdateMode = FullStyleUpdate);
445 void styleResolverMayHaveChanged();
447 // FIXME: Switch all callers of styleResolverChanged to these or better ones and then make them
448 // do something smarter.
449 void removedStyleSheet(StyleSheet*, RecalcStyleTime when = RecalcStyleDeferred, StyleResolverUpdateMode = FullStyleUpdate);
450 void addedStyleSheet(StyleSheet*, RecalcStyleTime when = RecalcStyleDeferred) { styleResolverChanged(when); }
451 void modifiedStyleSheet(StyleSheet*, RecalcStyleTime when = RecalcStyleDeferred, StyleResolverUpdateMode = FullStyleUpdate);
452 void changedSelectorWatch() { styleResolverChanged(RecalcStyleDeferred); }
454 void scheduleUseShadowTreeUpdate(SVGUseElement&);
455 void unscheduleUseShadowTreeUpdate(SVGUseElement&);
457 // FIXME: This should be eliminated and elements that use it should be made to
458 // always have a layer so they don't need to go about creating one from reasons
459 // external to style.
460 void scheduleLayerUpdate(Element&);
461 void unscheduleLayerUpdate(Element&);
463 void evaluateMediaQueryList();
465 FormController& formController();
466 DocumentState* formElementsState() const;
467 void setStateForNewFormElements(const Vector<String>&);
469 FrameView* view() const; // can be null
470 LocalFrame* frame() const { return m_frame; } // can be null
471 FrameHost* frameHost() const; // can be null
472 Page* page() const; // can be null
473 Settings* settings() const; // can be null
475 float devicePixelRatio() const;
477 PassRefPtrWillBeRawPtr<Range> createRange();
479 PassRefPtr<NodeIterator> createNodeIterator(Node* root, ExceptionState&);
480 PassRefPtr<NodeIterator> createNodeIterator(Node* root, unsigned whatToShow, ExceptionState&);
481 PassRefPtr<NodeIterator> createNodeIterator(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter>, ExceptionState&);
483 PassRefPtr<TreeWalker> createTreeWalker(Node* root, ExceptionState&);
484 PassRefPtr<TreeWalker> createTreeWalker(Node* root, unsigned whatToShow, ExceptionState&);
485 PassRefPtr<TreeWalker> createTreeWalker(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter>, ExceptionState&);
487 // Special support for editing
488 PassRefPtr<Text> createEditingTextNode(const String&);
490 void setupFontBuilder(RenderStyle* documentStyle);
492 void updateRenderTreeIfNeeded() { updateRenderTree(NoChange); }
493 void updateRenderTreeForNodeIfNeeded(Node*);
495 enum RunPostLayoutTasks {
496 RunPostLayoutTasksAsyhnchronously,
497 RunPostLayoutTasksSynchronously,
499 void updateLayoutIgnorePendingStylesheets(RunPostLayoutTasks = RunPostLayoutTasksAsyhnchronously);
500 PassRefPtr<RenderStyle> styleForElementIgnoringPendingStylesheets(Element*);
501 PassRefPtr<RenderStyle> styleForPage(int pageIndex);
503 void updateDistributionForNodeIfNeeded(Node*);
505 // Returns true if page box (margin boxes and page borders) is visible.
506 bool isPageBoxVisible(int pageIndex);
508 // Returns the preferred page size and margins in pixels, assuming 96
509 // pixels per inch. pageSize, marginTop, marginRight, marginBottom,
510 // marginLeft must be initialized to the default values that are used if
511 // auto is specified.
512 void pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft);
514 ResourceFetcher* fetcher() { return m_fetcher.get(); }
516 virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
517 virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
518 void prepareForDestruction();
520 RenderView* renderView() const { return m_renderView; }
522 AXObjectCache* existingAXObjectCache() const;
523 AXObjectCache* axObjectCache() const;
524 void clearAXObjectCache();
526 // to get visually ordered hebrew and arabic pages right
527 bool visuallyOrdered() const { return m_visuallyOrdered; }
529 DocumentLoader* loader() const;
531 void open(Document* ownerDocument = 0, ExceptionState& = ASSERT_NO_EXCEPTION);
532 PassRefPtr<DocumentParser> implicitOpen();
534 // close() is the DOM API document.close()
535 void close(ExceptionState& = ASSERT_NO_EXCEPTION);
536 // In some situations (see the code), we ignore document.close().
537 // explicitClose() bypass these checks and actually tries to close the
539 void explicitClose();
540 // implicitClose() actually does the work of closing the input stream.
541 void implicitClose();
543 bool dispatchBeforeUnloadEvent(Chrome&, bool&);
544 void dispatchUnloadEvents();
546 enum PageDismissalType {
548 BeforeUnloadDismissal = 1,
549 PageHideDismissal = 2,
552 PageDismissalType pageDismissalEventBeingDispatched() const;
554 void cancelParsing();
556 void write(const SegmentedString& text, Document* ownerDocument = 0, ExceptionState& = ASSERT_NO_EXCEPTION);
557 void write(const String& text, Document* ownerDocument = 0, ExceptionState& = ASSERT_NO_EXCEPTION);
558 void writeln(const String& text, Document* ownerDocument = 0, ExceptionState& = ASSERT_NO_EXCEPTION);
560 bool wellFormed() const { return m_wellFormed; }
562 const KURL& url() const { return m_url; }
563 void setURL(const KURL&);
565 // To understand how these concepts relate to one another, please see the
566 // comments surrounding their declaration.
567 const KURL& baseURL() const { return m_baseURL; }
568 void setBaseURLOverride(const KURL&);
569 const KURL& baseURLOverride() const { return m_baseURLOverride; }
570 const KURL& baseElementURL() const { return m_baseElementURL; }
571 const AtomicString& baseTarget() const { return m_baseTarget; }
572 void processBaseElement();
574 KURL completeURL(const String&) const;
575 KURL completeURLWithOverride(const String&, const KURL& baseURLOverride) const;
577 virtual String userAgent(const KURL&) const OVERRIDE FINAL;
578 virtual void disableEval(const String& errorMessage) OVERRIDE FINAL;
580 bool canNavigate(LocalFrame* targetFrame);
581 LocalFrame* findUnsafeParentScrollPropagationBoundary();
583 CSSStyleSheet& elementSheet();
585 virtual PassRefPtr<DocumentParser> createParser();
586 DocumentParser* parser() const { return m_parser.get(); }
587 ScriptableDocumentParser* scriptableDocumentParser() const;
589 bool printing() const { return m_printing; }
590 void setPrinting(bool p) { m_printing = p; }
592 bool paginatedForScreen() const { return m_paginatedForScreen; }
593 void setPaginatedForScreen(bool p) { m_paginatedForScreen = p; }
595 bool paginated() const { return printing() || paginatedForScreen(); }
597 enum CompatibilityMode { QuirksMode, LimitedQuirksMode, NoQuirksMode };
599 void setCompatibilityMode(CompatibilityMode m);
600 CompatibilityMode compatibilityMode() const { return m_compatibilityMode; }
602 String compatMode() const;
604 bool inQuirksMode() const { return m_compatibilityMode == QuirksMode; }
605 bool inLimitedQuirksMode() const { return m_compatibilityMode == LimitedQuirksMode; }
606 bool inNoQuirksMode() const { return m_compatibilityMode == NoQuirksMode; }
613 void setReadyState(ReadyState);
614 bool isLoadCompleted();
616 void setParsing(bool);
617 bool parsing() const { return m_isParsing; }
619 bool shouldScheduleLayout() const;
620 int elapsedTime() const;
622 TextLinkColors& textLinkColors() { return m_textLinkColors; }
623 VisitedLinkState& visitedLinkState() const { return *m_visitedLinkState; }
625 MouseEventWithHitTestResults prepareMouseEvent(const HitTestRequest&, const LayoutPoint&, const PlatformMouseEvent&);
627 /* Newly proposed CSS3 mechanism for selecting alternate
628 stylesheets using the DOM. May be subject to change as
631 String preferredStylesheetSet() const;
632 String selectedStylesheetSet() const;
633 void setSelectedStylesheetSet(const String&);
635 bool setFocusedElement(PassRefPtr<Element>, FocusType = FocusTypeNone);
636 Element* focusedElement() const { return m_focusedElement.get(); }
637 UserActionElementSet& userActionElements() { return m_userActionElements; }
638 const UserActionElementSet& userActionElements() const { return m_userActionElements; }
639 void setNeedsFocusedElementCheck();
640 void setAutofocusElement(Element*);
641 Element* autofocusElement() const { return m_autofocusElement.get(); }
643 void setHoverNode(PassRefPtr<Node>);
644 Node* hoverNode() const { return m_hoverNode.get(); }
646 void setActiveHoverElement(PassRefPtr<Element>);
647 Element* activeHoverElement() const { return m_activeHoverElement.get(); }
649 void removeFocusedElementOfSubtree(Node*, bool amongChildrenOnly = false);
650 void hoveredNodeDetached(Node*);
651 void activeChainNodeDetached(Node*);
653 void updateHoverActiveState(const HitTestRequest&, Element*, const PlatformMouseEvent* = 0);
655 // Updates for :target (CSS3 selector).
656 void setCSSTarget(Element*);
657 Element* cssTarget() const { return m_cssTarget; }
659 void scheduleRenderTreeUpdateIfNeeded();
660 bool hasPendingForcedStyleRecalc() const;
662 void registerNodeList(LiveNodeListBase*);
663 void unregisterNodeList(LiveNodeListBase*);
664 void incrementNodeListWithIdNameCacheCount();
665 void decrementNodeListWithIdNameCacheCount();
666 bool shouldInvalidateNodeListCaches(const QualifiedName* attrName = 0) const;
667 void invalidateNodeListCaches(const QualifiedName* attrName);
669 void attachNodeIterator(NodeIterator*);
670 void detachNodeIterator(NodeIterator*);
671 void moveNodeIteratorsToNewDocument(Node&, Document&);
673 void attachRange(Range*);
674 void detachRange(Range*);
676 void updateRangesAfterChildrenChanged(ContainerNode*);
677 // nodeChildrenWillBeRemoved is used when removing all node children at once.
678 void nodeChildrenWillBeRemoved(ContainerNode&);
679 // nodeWillBeRemoved is only safe when removing one node at a time.
680 void nodeWillBeRemoved(Node&);
681 bool canReplaceChild(const Node& newChild, const Node& oldChild) const;
683 void didInsertText(Node*, unsigned offset, unsigned length);
684 void didRemoveText(Node*, unsigned offset, unsigned length);
685 void didMergeTextNodes(Text& oldNode, unsigned offset);
686 void didSplitTextNode(Text& oldNode);
688 void clearDOMWindow() { m_domWindow = 0; }
689 DOMWindow* domWindow() const { return m_domWindow; }
691 // Helper functions for forwarding DOMWindow event related tasks to the DOMWindow if it exists.
692 void setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener>);
693 EventListener* getWindowAttributeEventListener(const AtomicString& eventType);
695 PassRefPtrWillBeRawPtr<Event> createEvent(const String& eventType, ExceptionState&);
697 // keep track of what types of event listeners are registered, so we don't
698 // dispatch events unnecessarily
700 DOMSUBTREEMODIFIED_LISTENER = 1,
701 DOMNODEINSERTED_LISTENER = 1 << 1,
702 DOMNODEREMOVED_LISTENER = 1 << 2,
703 DOMNODEREMOVEDFROMDOCUMENT_LISTENER = 1 << 3,
704 DOMNODEINSERTEDINTODOCUMENT_LISTENER = 1 << 4,
705 DOMCHARACTERDATAMODIFIED_LISTENER = 1 << 5,
706 OVERFLOWCHANGED_LISTENER = 1 << 6,
707 ANIMATIONEND_LISTENER = 1 << 7,
708 ANIMATIONSTART_LISTENER = 1 << 8,
709 ANIMATIONITERATION_LISTENER = 1 << 9,
710 TRANSITIONEND_LISTENER = 1 << 10,
711 SCROLL_LISTENER = 1 << 12
715 bool hasListenerType(ListenerType listenerType) const { return (m_listenerTypes & listenerType); }
716 void addListenerTypeIfNeeded(const AtomicString& eventType);
718 bool hasMutationObserversOfType(MutationObserver::MutationType type) const
720 return m_mutationObserverTypes & type;
722 bool hasMutationObservers() const { return m_mutationObserverTypes; }
723 void addMutationObserverTypes(MutationObserverOptions types) { m_mutationObserverTypes |= types; }
725 CSSStyleDeclaration* getOverrideStyle(Element*, const String& pseudoElt);
728 * Handles a HTTP header equivalent set by a meta tag using <meta http-equiv="..." content="...">. This is called
729 * when a meta tag is encountered during document parsing, and also when a script dynamically changes or adds a meta
730 * tag. This enables scripts to use meta tags to perform refreshes and set expiry dates in addition to them being
731 * specified in a HTML file.
733 * @param equiv The http header name (value of the meta tag's "equiv" attribute)
734 * @param content The header value (value of the meta tag's "content" attribute)
735 * @param inDocumentHeadElement Is the element in the document's <head> element?
737 void processHttpEquiv(const AtomicString& equiv, const AtomicString& content, bool inDocumentHeadElement);
738 void updateViewportDescription();
739 void processReferrerPolicy(const String& policy);
741 // Returns the owning element in the parent document.
742 // Returns 0 if this is the top level document.
743 HTMLFrameOwnerElement* ownerElement() const;
745 String title() const { return m_title; }
746 void setTitle(const String&);
748 Element* titleElement() const { return m_titleElement.get(); }
749 void setTitleElement(const String& title, Element* titleElement);
750 void removeTitle(Element* titleElement);
752 const AtomicString& dir();
753 void setDir(const AtomicString&);
755 String cookie(ExceptionState&) const;
756 void setCookie(const String&, ExceptionState&);
758 const AtomicString& referrer() const;
760 String domain() const;
761 void setDomain(const String& newDomain, ExceptionState&);
763 String lastModified() const;
765 // The cookieURL is used to query the cookie database for this document's
766 // cookies. For example, if the cookie URL is http://example.com, we'll
767 // use the non-Secure cookies for example.com when computing
770 // Q: How is the cookieURL different from the document's URL?
771 // A: The two URLs are the same almost all the time. However, if one
772 // document inherits the security context of another document, it
773 // inherits its cookieURL but not its URL.
775 const KURL& cookieURL() const { return m_cookieURL; }
776 void setCookieURL(const KURL& url) { m_cookieURL = url; }
778 const KURL& firstPartyForCookies() const;
780 // The following implements the rule from HTML 4 for what valid names are.
781 // To get this right for all the XML cases, we probably have to improve this or move it
782 // and make it sensitive to the type of document.
783 static bool isValidName(const String&);
785 // The following breaks a qualified name into a prefix and a local name.
786 // It also does a validity check, and returns false if the qualified name
787 // is invalid. It also sets ExceptionCode when name is invalid.
788 static bool parseQualifiedName(const AtomicString& qualifiedName, AtomicString& prefix, AtomicString& localName, ExceptionState&);
790 // Checks to make sure prefix and namespace do not conflict (per DOM Core 3)
791 static bool hasValidNamespaceForElements(const QualifiedName&);
792 static bool hasValidNamespaceForAttributes(const QualifiedName&);
794 HTMLElement* body() const;
795 void setBody(PassRefPtr<HTMLElement>, ExceptionState&);
797 HTMLHeadElement* head();
799 // Decide which element is to define the viewport's overflow policy. If |rootStyle| is set, use
800 // that as the style for the root element, rather than obtaining it on our own. The reason for
801 // this is that style may not have been associated with the elements yet - in which case it may
802 // have been calculated on the fly (without associating it with the actual element) somewhere.
803 Element* viewportDefiningElement(RenderStyle* rootStyle = 0) const;
805 DocumentMarkerController& markers() const { return *m_markers; }
807 bool directionSetOnDocumentElement() const { return m_directionSetOnDocumentElement; }
808 bool writingModeSetOnDocumentElement() const { return m_writingModeSetOnDocumentElement; }
809 void setDirectionSetOnDocumentElement(bool b) { m_directionSetOnDocumentElement = b; }
810 void setWritingModeSetOnDocumentElement(bool b) { m_writingModeSetOnDocumentElement = b; }
812 bool execCommand(const String& command, bool userInterface = false, const String& value = String());
813 bool queryCommandEnabled(const String& command);
814 bool queryCommandIndeterm(const String& command);
815 bool queryCommandState(const String& command);
816 bool queryCommandSupported(const String& command);
817 String queryCommandValue(const String& command);
819 KURL openSearchDescriptionURL();
821 // designMode support
822 enum InheritedBool { off = false, on = true, inherit };
823 void setDesignMode(InheritedBool value);
824 InheritedBool getDesignMode() const;
825 bool inDesignMode() const;
826 String designMode() const;
827 void setDesignMode(const String&);
829 Document* parentDocument() const;
830 Document& topDocument() const;
831 WeakPtr<Document> contextDocument();
833 ScriptRunner* scriptRunner() { return m_scriptRunner.get(); }
835 HTMLScriptElement* currentScript() const { return !m_currentScriptStack.isEmpty() ? m_currentScriptStack.last().get() : 0; }
836 void pushCurrentScript(PassRefPtr<HTMLScriptElement>);
837 void popCurrentScript();
839 void applyXSLTransform(ProcessingInstruction* pi);
840 PassRefPtrWillBeRawPtr<Document> transformSourceDocument() { return m_transformSourceDocument; }
841 void setTransformSourceDocument(Document* doc) { m_transformSourceDocument = doc; }
843 void setTransformSource(PassOwnPtr<TransformSource>);
844 TransformSource* transformSource() const { return m_transformSource.get(); }
846 void incDOMTreeVersion() { ASSERT(m_lifecycle.stateAllowsTreeMutations()); m_domTreeVersion = ++s_globalTreeVersion; }
847 uint64_t domTreeVersion() const { return m_domTreeVersion; }
849 enum PendingSheetLayout { NoLayoutWithPendingSheets, DidLayoutWithPendingSheets, IgnoreLayoutWithPendingSheets };
851 bool didLayoutWithPendingStylesheets() const { return m_pendingSheetLayout == DidLayoutWithPendingSheets; }
853 bool hasNodesWithPlaceholderStyle() const { return m_hasNodesWithPlaceholderStyle; }
854 void setHasNodesWithPlaceholderStyle() { m_hasNodesWithPlaceholderStyle = true; }
856 Vector<IconURL> iconURLs(int iconTypesMask);
858 void setUseSecureKeyboardEntryWhenActive(bool);
859 bool useSecureKeyboardEntryWhenActive() const;
861 void updateFocusAppearanceSoon(bool restorePreviousSelection);
862 void cancelFocusAppearanceUpdate();
864 // Extension for manipulating canvas drawing contexts for use in CSS
865 void getCSSCanvasContext(const String& type, const String& name, int width, int height, bool&, RefPtrWillBeRawPtr<CanvasRenderingContext2D>&, bool&, RefPtrWillBeRawPtr<WebGLRenderingContext>&);
866 HTMLCanvasElement& getCSSCanvasElement(const String& name);
868 bool isDNSPrefetchEnabled() const { return m_isDNSPrefetchEnabled; }
869 void parseDNSPrefetchControlHeader(const String&);
871 // FIXME(crbug.com/305497): This should be removed once DOMWindow is an ExecutionContext.
872 virtual void postTask(PassOwnPtr<ExecutionContextTask>) OVERRIDE; // Executes the task on context's thread asynchronously.
874 virtual void tasksWereSuspended() OVERRIDE FINAL;
875 virtual void tasksWereResumed() OVERRIDE FINAL;
876 virtual void suspendScheduledTasks() OVERRIDE FINAL;
877 virtual void resumeScheduledTasks() OVERRIDE FINAL;
878 virtual bool tasksNeedSuspension() OVERRIDE FINAL;
880 void finishedParsing();
882 void setEncodingData(const DocumentEncodingData& newData);
883 const WTF::TextEncoding& encoding() const { return m_encodingData.encoding(); }
885 bool encodingWasDetectedHeuristically() const { return m_encodingData.wasDetectedHeuristically(); }
886 bool sawDecodingError() const { return m_encodingData.sawDecodingError(); }
888 void setAnnotatedRegionsDirty(bool f) { m_annotatedRegionsDirty = f; }
889 bool annotatedRegionsDirty() const { return m_annotatedRegionsDirty; }
890 bool hasAnnotatedRegions () const { return m_hasAnnotatedRegions; }
891 void setHasAnnotatedRegions(bool f) { m_hasAnnotatedRegions = f; }
892 const Vector<AnnotatedRegionValue>& annotatedRegions() const;
893 void setAnnotatedRegions(const Vector<AnnotatedRegionValue>&);
895 virtual void removeAllEventListeners() OVERRIDE FINAL;
897 const SVGDocumentExtensions* svgExtensions();
898 SVGDocumentExtensions& accessSVGExtensions();
900 void initSecurityContext();
901 void initSecurityContext(const DocumentInit&);
902 void initContentSecurityPolicy(const ContentSecurityPolicyResponseHeaders&);
904 bool allowInlineEventHandlers(Node*, EventListener*, const String& contextURL, const WTF::OrdinalNumber& contextLine);
905 bool allowExecutingScripts(Node*);
907 void statePopped(PassRefPtr<SerializedScriptValue>);
909 enum LoadEventProgress {
914 BeforeUnloadEventInProgress,
915 BeforeUnloadEventCompleted,
917 UnloadEventInProgress,
920 bool loadEventStillNeeded() const { return m_loadEventProgress == LoadEventNotRun; }
921 bool processingLoadEvent() const { return m_loadEventProgress == LoadEventInProgress; }
922 bool loadEventFinished() const { return m_loadEventProgress >= LoadEventCompleted; }
923 bool unloadStarted() const { return m_loadEventProgress >= PageHideInProgress; }
925 void setContainsPlugins() { m_containsPlugins = true; }
926 bool containsPlugins() const { return m_containsPlugins; }
928 virtual bool isContextThread() const OVERRIDE FINAL;
929 virtual bool isJSExecutionForbidden() const OVERRIDE FINAL { return false; }
931 bool containsValidityStyleRules() const { return m_containsValidityStyleRules; }
932 void setContainsValidityStyleRules() { m_containsValidityStyleRules = true; }
934 void enqueueResizeEvent();
935 void enqueueScrollEventForNode(Node*);
936 void enqueueAnimationFrameEvent(PassRefPtrWillBeRawPtr<Event>);
938 bool hasFullscreenElementStack() const { return m_hasFullscreenElementStack; }
939 void setHasFullscreenElementStack() { m_hasFullscreenElementStack = true; }
941 void webkitExitPointerLock();
942 Element* webkitPointerLockElement() const;
944 // Used to allow element that loads data without going through a FrameLoader to delay the 'load' event.
945 void incrementLoadEventDelayCount() { ++m_loadEventDelayCount; }
946 void decrementLoadEventDelayCount();
947 void checkLoadEventSoon();
948 bool isDelayingLoadEvent();
949 void loadPluginsSoon();
951 PassRefPtrWillBeRawPtr<Touch> createTouch(DOMWindow*, EventTarget*, int identifier, int pageX, int pageY, int screenX, int screenY, int radiusX, int radiusY, float rotationAngle, float force) const;
952 PassRefPtrWillBeRawPtr<TouchList> createTouchList(WillBeHeapVector<RefPtrWillBeMember<Touch> >&) const;
954 const DocumentTiming& timing() const { return m_documentTiming; }
956 int requestAnimationFrame(PassOwnPtr<RequestAnimationFrameCallback>);
957 void cancelAnimationFrame(int id);
958 void serviceScriptedAnimations(double monotonicAnimationStartTime);
960 virtual EventTarget* errorEventTarget() OVERRIDE FINAL;
961 virtual void logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack>) OVERRIDE FINAL;
963 void initDNSPrefetch();
965 bool hasTouchEventHandlers() const { return (m_touchEventTargets.get()) ? m_touchEventTargets->size() : false; }
967 // Called when a single touch event handler has been added or removed for a node.
968 // The Node should always be in this Document, except for child Documents which report
969 // themselves to their parent exactly once if they have any touch handlers.
970 // Handlers added/removed from the DOMWindow are reported as the Document.
971 void didAddTouchEventHandler(Node*);
972 void didRemoveTouchEventHandler(Node* handler) { didRemoveTouchEventHandler(handler, false); }
974 // Called whenever all touch event handlers have been removed for a node (such as when the
975 // node itself is being removed from the document).
976 void didClearTouchEventHandlers(Node* handler) { didRemoveTouchEventHandler(handler, true); }
978 const TouchEventTargetSet* touchEventTargets() const { return m_touchEventTargets.get(); }
980 bool isInDocumentWrite() { return m_writeRecursionDepth > 0; }
982 IntSize initialViewportSize() const;
984 // There are currently two parallel autosizing implementations: TextAutosizer and FastTextAutosizer.
985 // See http://tinyurl.com/chromium-fast-autosizer for more details.
986 TextAutosizer* textAutosizer();
987 FastTextAutosizer* fastTextAutosizer();
989 PassRefPtr<Element> createElement(const AtomicString& localName, const AtomicString& typeExtension, ExceptionState&);
990 PassRefPtr<Element> createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& typeExtension, ExceptionState&);
991 ScriptValue registerElement(WebCore::ScriptState*, const AtomicString& name, ExceptionState&);
992 ScriptValue registerElement(WebCore::ScriptState*, const AtomicString& name, const Dictionary& options, ExceptionState&, CustomElement::NameSet validNames = CustomElement::StandardNames);
993 CustomElementRegistrationContext* registrationContext() { return m_registrationContext.get(); }
995 void setImportsController(HTMLImportsController*);
996 HTMLImportsController* importsController() const { return m_importsController; }
997 HTMLImportLoader* importLoader() const;
999 bool haveImportsLoaded() const;
1000 void didLoadAllImports();
1002 void adjustFloatQuadsForScrollAndAbsoluteZoom(Vector<FloatQuad>&, RenderObject&);
1003 void adjustFloatRectForScrollAndAbsoluteZoom(FloatRect&, RenderObject&);
1005 bool hasActiveParser();
1006 unsigned activeParserCount() { return m_activeParserCount; }
1007 void incrementActiveParserCount() { ++m_activeParserCount; }
1008 void decrementActiveParserCount();
1010 void setContextFeatures(ContextFeatures&);
1011 ContextFeatures& contextFeatures() const { return *m_contextFeatures; }
1013 ElementDataCache* elementDataCache() { return m_elementDataCache.get(); }
1015 void didLoadAllScriptBlockingResources();
1016 void didRemoveAllPendingStylesheet();
1017 void setNeedsNotifyRemoveAllPendingStylesheet() { m_needsNotifyRemoveAllPendingStylesheet = true; }
1018 void clearStyleResolver();
1020 bool inStyleRecalc() const { return m_lifecycle.state() == DocumentLifecycle::InStyleRecalc; }
1022 // Return a Locale for the default locale if the argument is null or empty.
1023 Locale& getCachedLocale(const AtomicString& locale = nullAtom);
1025 AnimationClock& animationClock() { return *m_animationClock; }
1026 DocumentTimeline& timeline() const { return *m_timeline; }
1027 DocumentTimeline& transitionTimeline() const { return *m_transitionTimeline; }
1028 CompositorPendingAnimations& compositorPendingAnimations() { return m_compositorPendingAnimations; }
1030 void addToTopLayer(Element*, const Element* before = 0);
1031 void removeFromTopLayer(Element*);
1032 const WillBeHeapVector<RefPtrWillBeMember<Element> >& topLayerElements() const { return m_topLayerElements; }
1033 HTMLDialogElement* activeModalDialog() const;
1035 // A non-null m_templateDocumentHost implies that |this| was created by ensureTemplateDocument().
1036 bool isTemplateDocument() const { return !!m_templateDocumentHost; }
1037 Document& ensureTemplateDocument();
1038 Document* templateDocumentHost() { return m_templateDocumentHost; }
1040 void didAssociateFormControl(Element*);
1042 void addConsoleMessageWithRequestIdentifier(MessageSource, MessageLevel, const String& message, unsigned long requestIdentifier);
1044 virtual DOMWindow* executingWindow() OVERRIDE FINAL;
1045 LocalFrame* executingFrame();
1047 DocumentLifecycleNotifier& lifecycleNotifier();
1048 DocumentLifecycle& lifecycle() { return m_lifecycle; }
1049 bool isActive() const { return m_lifecycle.isActive(); }
1050 bool isStopped() const { return m_lifecycle.state() == DocumentLifecycle::Stopped; }
1051 bool isDisposed() const { return m_lifecycle.state() == DocumentLifecycle::Disposed; }
1053 enum HttpRefreshType {
1054 HttpRefreshFromHeader,
1055 HttpRefreshFromMetaTag
1057 void maybeHandleHttpRefresh(const String&, HttpRefreshType);
1059 void updateSecurityOrigin(PassRefPtr<SecurityOrigin>);
1060 PassOwnPtr<LifecycleNotifier<Document> > createLifecycleNotifier();
1062 void setHasViewportUnits() { m_hasViewportUnits = true; }
1063 bool hasViewportUnits() const { return m_hasViewportUnits; }
1064 void notifyResizeForViewportUnits();
1066 void registerVisibilityObserver(DocumentVisibilityObserver*);
1067 void unregisterVisibilityObserver(DocumentVisibilityObserver*);
1069 void updateStyleInvalidationIfNeeded();
1071 virtual void trace(Visitor*) OVERRIDE;
1073 bool hasElementsRequiringLayerUpdate() const { return m_layerUpdateElements.size(); }
1074 void didRecalculateStyleForElement() { ++m_styleRecalcElementCounter; }
1077 Document(const DocumentInit&, DocumentClassFlags = DefaultDocumentClass);
1079 virtual void didUpdateSecurityOrigin() OVERRIDE FINAL;
1081 void clearXMLVersion() { m_xmlVersion = String(); }
1083 virtual void dispose() OVERRIDE;
1085 virtual PassRefPtr<Document> cloneDocumentWithoutChildren();
1087 bool importContainerNodeChildren(ContainerNode* oldContainerNode, PassRefPtr<ContainerNode> newContainerNode, ExceptionState&);
1088 void lockCompatibilityMode() { m_compatibilityModeLocked = true; }
1092 friend class IgnoreDestructiveWriteCountIncrementer;
1094 ScriptedAnimationController& ensureScriptedAnimationController();
1095 virtual SecurityContext& securityContext() OVERRIDE FINAL { return *this; }
1096 virtual EventQueue* eventQueue() const OVERRIDE FINAL;
1098 // FIXME: Rename the StyleRecalc state to RenderTreeUpdate.
1099 bool hasPendingStyleRecalc() const { return m_lifecycle.state() == DocumentLifecycle::VisualUpdatePending; }
1101 bool shouldScheduleRenderTreeUpdate() const;
1102 void scheduleRenderTreeUpdate();
1104 bool needsFullRenderTreeUpdate() const;
1105 bool needsRenderTreeUpdate() const;
1107 void inheritHtmlAndBodyElementStyles(StyleRecalcChange);
1109 bool dirtyElementsForLayerUpdate();
1110 void updateDistributionIfNeeded();
1111 void updateUseShadowTreesIfNeeded();
1112 void evaluateMediaQueryListIfNeeded();
1114 void updateRenderTree(StyleRecalcChange);
1115 void updateStyle(StyleRecalcChange);
1117 void detachParser();
1119 void clearWeakMembers(Visitor*);
1121 virtual bool isDocument() const OVERRIDE FINAL { return true; }
1123 virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
1125 virtual String nodeName() const OVERRIDE FINAL;
1126 virtual NodeType nodeType() const OVERRIDE FINAL;
1127 virtual bool childTypeAllowed(NodeType) const OVERRIDE FINAL;
1128 virtual PassRefPtr<Node> cloneNode(bool deep = true) OVERRIDE FINAL;
1129 void cloneDataFromDocument(const Document&);
1131 virtual void refExecutionContext() OVERRIDE FINAL { ref(); }
1132 virtual void derefExecutionContext() OVERRIDE FINAL { deref(); }
1134 virtual const KURL& virtualURL() const OVERRIDE FINAL; // Same as url(), but needed for ExecutionContext to implement it without a performance loss for direct calls.
1135 virtual KURL virtualCompleteURL(const String&) const OVERRIDE FINAL; // Same as completeURL() for the same reason as above.
1137 virtual void reportBlockedScriptExecutionToInspector(const String& directiveText) OVERRIDE FINAL;
1138 virtual void addMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState*) OVERRIDE FINAL;
1139 void internalAddMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack>, ScriptState*);
1141 virtual double timerAlignmentInterval() const OVERRIDE FINAL;
1143 void updateTitle(const String&);
1144 void updateFocusAppearanceTimerFired(Timer<Document>*);
1145 void updateBaseURL();
1147 void executeScriptsWaitingForResourcesIfNeeded();
1149 PassRefPtr<NodeList> handleZeroPadding(const HitTestRequest&, HitTestResult&) const;
1151 void loadEventDelayTimerFired(Timer<Document>*);
1152 void pluginLoadingTimerFired(Timer<Document>*);
1154 PageVisibilityState pageVisibilityState() const;
1156 PassRefPtr<HTMLCollection> ensureCachedCollection(CollectionType);
1158 // Note that dispatching a window load event may cause the DOMWindow to be detached from
1159 // the LocalFrame, so callers should take a reference to the DOMWindow (which owns us) to
1160 // prevent the Document from getting blown away from underneath them.
1161 void dispatchWindowLoadEvent();
1163 void addListenerType(ListenerType listenerType) { m_listenerTypes |= listenerType; }
1164 void addMutationEventListenerTypeIfEnabled(ListenerType);
1166 void didAssociateFormControlsTimerFired(Timer<Document>*);
1168 void clearFocusedElementSoon();
1169 void clearFocusedElementTimerFired(Timer<Document>*);
1171 void processHttpEquivDefaultStyle(const AtomicString& content);
1172 void processHttpEquivRefresh(const AtomicString& content);
1173 void processHttpEquivSetCookie(const AtomicString& content);
1174 void processHttpEquivXFrameOptions(const AtomicString& content);
1175 void processHttpEquivContentSecurityPolicy(const AtomicString& equiv, const AtomicString& content);
1177 void didRemoveTouchEventHandler(Node*, bool clearAll);
1179 bool haveStylesheetsLoaded() const;
1181 DocumentLifecycle m_lifecycle;
1183 bool m_hasNodesWithPlaceholderStyle;
1184 bool m_needsNotifyRemoveAllPendingStylesheet;
1185 bool m_evaluateMediaQueriesOnStyleRecalc;
1187 // If we do ignore the pending stylesheet count, then we need to add a boolean
1188 // to track that this happened so that we can do a full repaint when the stylesheets
1189 // do eventually load.
1190 PendingSheetLayout m_pendingSheetLayout;
1192 LocalFrame* m_frame;
1193 DOMWindow* m_domWindow;
1194 HTMLImportsController* m_importsController;
1196 RefPtrWillBeMember<ResourceFetcher> m_fetcher;
1197 RefPtr<DocumentParser> m_parser;
1198 unsigned m_activeParserCount;
1199 RefPtrWillBeMember<ContextFeatures> m_contextFeatures;
1204 KURL m_url; // Document.URL: The URL from which this document was retrieved.
1205 KURL m_baseURL; // Node.baseURI: The URL to use when resolving relative URLs.
1206 KURL m_baseURLOverride; // An alternative base URL that takes precedence over m_baseURL (but not m_baseElementURL).
1207 KURL m_baseElementURL; // The URL set by the <base> element.
1208 KURL m_cookieURL; // The URL to use for cookie access.
1210 AtomicString m_baseTarget;
1212 // Mime-type of the document in case it was cloned or created by XHR.
1213 AtomicString m_mimeType;
1215 RefPtrWillBeMember<DocumentType> m_docType;
1216 OwnPtrWillBeMember<DOMImplementation> m_implementation;
1218 RefPtrWillBeMember<CSSStyleSheet> m_elemSheet;
1221 bool m_paginatedForScreen;
1223 CompatibilityMode m_compatibilityMode;
1224 bool m_compatibilityModeLocked; // This is cheaper than making setCompatibilityMode virtual.
1226 bool m_hasAutofocused;
1227 Timer<Document> m_clearFocusedElementTimer;
1228 RefPtrWillBeMember<Element> m_autofocusElement;
1229 RefPtrWillBeMember<Element> m_focusedElement;
1230 RefPtrWillBeMember<Node> m_hoverNode;
1231 RefPtrWillBeMember<Element> m_activeHoverElement;
1232 RefPtrWillBeMember<Element> m_documentElement;
1233 UserActionElementSet m_userActionElements;
1235 uint64_t m_domTreeVersion;
1236 static uint64_t s_globalTreeVersion;
1238 HashSet<NodeIterator*> m_nodeIterators;
1239 HashSet<Range*> m_ranges;
1241 unsigned short m_listenerTypes;
1243 MutationObserverOptions m_mutationObserverTypes;
1245 OwnPtrWillBeMember<StyleEngine> m_styleEngine;
1246 RefPtrWillBeMember<StyleSheetList> m_styleSheetList;
1248 OwnPtrWillBeMember<FormController> m_formController;
1250 TextLinkColors m_textLinkColors;
1251 const OwnPtr<VisitedLinkState> m_visitedLinkState;
1253 bool m_visuallyOrdered;
1254 ReadyState m_readyState;
1257 bool m_gotoAnchorNeededAfterStylesheetsLoad;
1258 bool m_isDNSPrefetchEnabled;
1259 bool m_haveExplicitlyDisabledDNSPrefetch;
1260 bool m_containsValidityStyleRules;
1261 bool m_updateFocusAppearanceRestoresSelection;
1262 bool m_containsPlugins;
1264 // http://www.whatwg.org/specs/web-apps/current-work/#ignore-destructive-writes-counter
1265 unsigned m_ignoreDestructiveWriteCount;
1269 bool m_titleSetExplicitly;
1270 RefPtrWillBeMember<Element> m_titleElement;
1272 OwnPtr<AXObjectCache> m_axObjectCache;
1273 OwnPtr<DocumentMarkerController> m_markers;
1275 Timer<Document> m_updateFocusAppearanceTimer;
1277 Element* m_cssTarget;
1279 LoadEventProgress m_loadEventProgress;
1283 OwnPtr<ScriptRunner> m_scriptRunner;
1285 WillBeHeapVector<RefPtrWillBeMember<HTMLScriptElement> > m_currentScriptStack;
1287 OwnPtr<TransformSource> m_transformSource;
1288 RefPtrWillBeMember<Document> m_transformSourceDocument;
1290 String m_xmlEncoding;
1291 String m_xmlVersion;
1292 unsigned m_xmlStandalone : 2;
1293 unsigned m_hasXMLDeclaration : 1;
1295 AtomicString m_contentLanguage;
1297 DocumentEncodingData m_encodingData;
1299 InheritedBool m_designMode;
1301 HashSet<LiveNodeListBase*> m_listsInvalidatedAtDocument;
1302 unsigned m_nodeListCounts[numNodeListInvalidationTypes];
1304 OwnPtr<SVGDocumentExtensions> m_svgExtensions;
1306 Vector<AnnotatedRegionValue> m_annotatedRegions;
1307 bool m_hasAnnotatedRegions;
1308 bool m_annotatedRegionsDirty;
1310 WillBeHeapHashMap<String, RefPtrWillBeMember<HTMLCanvasElement> > m_cssCanvasElements;
1312 OwnPtr<SelectorQueryCache> m_selectorQueryCache;
1314 bool m_useSecureKeyboardEntryWhenActive;
1316 DocumentClassFlags m_documentClasses;
1318 bool m_isViewSource;
1319 bool m_sawElementsInKnownNamespaces;
1320 bool m_isSrcdocDocument;
1321 bool m_isMobileDocument;
1323 RenderView* m_renderView;
1325 // FIXME: Oilpan: We should use a real weak pointer here.
1326 WeakPtrFactory<Document> m_weakFactory;
1327 WeakPtr<Document> m_contextDocument;
1329 bool m_hasFullscreenElementStack; // For early return in FullscreenElementStack::fromIfExists()
1331 WillBeHeapVector<RefPtrWillBeMember<Element> > m_topLayerElements;
1333 int m_loadEventDelayCount;
1334 Timer<Document> m_loadEventDelayTimer;
1335 Timer<Document> m_pluginLoadingTimer;
1337 ViewportDescription m_viewportDescription;
1338 ViewportDescription m_legacyViewportDescription;
1339 Length m_viewportDefaultMinWidth;
1341 bool m_didSetReferrerPolicy;
1342 ReferrerPolicy m_referrerPolicy;
1344 bool m_directionSetOnDocumentElement;
1345 bool m_writingModeSetOnDocumentElement;
1346 DocumentTiming m_documentTiming;
1347 RefPtrWillBeMember<MediaQueryMatcher> m_mediaQueryMatcher;
1348 bool m_writeRecursionIsTooDeep;
1349 unsigned m_writeRecursionDepth;
1351 OwnPtr<TouchEventTargetSet> m_touchEventTargets;
1353 RefPtr<ScriptedAnimationController> m_scriptedAnimationController;
1354 OwnPtr<MainThreadTaskRunner> m_taskRunner;
1355 OwnPtr<TextAutosizer> m_textAutosizer;
1356 OwnPtr<FastTextAutosizer> m_fastTextAutosizer;
1358 RefPtr<CustomElementRegistrationContext> m_registrationContext;
1360 void elementDataCacheClearTimerFired(Timer<Document>*);
1361 Timer<Document> m_elementDataCacheClearTimer;
1363 OwnPtr<ElementDataCache> m_elementDataCache;
1366 bool m_didDispatchViewportPropertiesChanged;
1369 typedef HashMap<AtomicString, OwnPtr<Locale> > LocaleIdentifierToLocaleMap;
1370 LocaleIdentifierToLocaleMap m_localeCache;
1372 OwnPtr<AnimationClock> m_animationClock;
1373 RefPtr<DocumentTimeline> m_timeline;
1374 RefPtr<DocumentTimeline> m_transitionTimeline;
1375 CompositorPendingAnimations m_compositorPendingAnimations;
1377 RefPtrWillBeMember<Document> m_templateDocument;
1378 // With Oilpan the templateDocument and the templateDocumentHost
1379 // live and die together. Without Oilpan, the templateDocumentHost
1380 // is a manually managed backpointer from m_templateDocument.
1381 RawPtrWillBeMember<Document> m_templateDocumentHost;
1383 Timer<Document> m_didAssociateFormControlsTimer;
1384 WillBeHeapHashSet<RefPtrWillBeMember<Element> > m_associatedFormControls;
1386 HashSet<SVGUseElement*> m_useElementsNeedingUpdate;
1387 HashSet<Element*> m_layerUpdateElements;
1389 bool m_hasViewportUnits;
1391 typedef WillBeHeapHashSet<RawPtrWillBeWeakMember<DocumentVisibilityObserver> > DocumentVisibilityObserverSet;
1392 DocumentVisibilityObserverSet m_visibilityObservers;
1394 int m_styleRecalcElementCounter;
1397 inline void Document::notifyRemovePendingSheetIfNeeded()
1399 if (m_needsNotifyRemoveAllPendingStylesheet)
1400 didRemoveAllPendingStylesheet();
1403 inline bool Document::shouldOverrideLegacyDescription(ViewportDescription::Type origin)
1405 // The different (legacy) meta tags have different priorities based on the type
1406 // regardless of which order they appear in the DOM. The priority is given by the
1407 // ViewportDescription::Type enum.
1408 return origin >= m_legacyViewportDescription.type;
1411 inline void Document::incrementNodeListWithIdNameCacheCount()
1413 m_nodeListCounts[InvalidateOnIdNameAttrChange]++;
1416 inline void Document::decrementNodeListWithIdNameCacheCount()
1418 ASSERT(m_nodeListCounts[InvalidateOnIdNameAttrChange] > 0);
1419 m_nodeListCounts[InvalidateOnIdNameAttrChange]--;
1422 inline void Document::scheduleRenderTreeUpdateIfNeeded()
1424 // Inline early out to avoid the function calls below.
1425 if (hasPendingStyleRecalc())
1427 if (shouldScheduleRenderTreeUpdate() && needsRenderTreeUpdate())
1428 scheduleRenderTreeUpdate();
1431 DEFINE_TYPE_CASTS(Document, ExecutionContextClient, client, client->isDocument(), client.isDocument());
1432 DEFINE_TYPE_CASTS(Document, ExecutionContext, context, context->isDocument(), context.isDocument());
1433 DEFINE_NODE_TYPE_CASTS(Document, isDocumentNode());
1435 #define DEFINE_DOCUMENT_TYPE_CASTS(thisType) \
1436 DEFINE_TYPE_CASTS(thisType, Document, document, document->is##thisType(), document.is##thisType())
1438 // All these varations are needed to avoid ambiguous overloads with the Node and TreeScope versions.
1439 inline bool operator==(const Document& a, const Document& b) { return &a == &b; }
1440 inline bool operator==(const Document& a, const Document* b) { return &a == b; }
1441 inline bool operator==(const Document* a, const Document& b) { return a == &b; }
1442 inline bool operator!=(const Document& a, const Document& b) { return !(a == b); }
1443 inline bool operator!=(const Document& a, const Document* b) { return !(a == b); }
1444 inline bool operator!=(const Document* a, const Document& b) { return !(a == b); }
1446 // Put these methods here, because they require the Document definition, but we really want to inline them.
1448 inline bool Node::isDocumentNode() const
1450 return this == document();
1453 Node* eventTargetNodeForDocument(Document*);
1455 } // namespace WebCore
1457 #endif // Document_h