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/ScriptValue.h"
32 #include "core/animation/css/CSSPendingAnimations.h"
33 #include "core/dom/ContainerNode.h"
34 #include "core/dom/DOMTimeStamp.h"
35 #include "core/dom/DocumentEncodingData.h"
36 #include "core/dom/DocumentInit.h"
37 #include "core/dom/DocumentLifecycle.h"
38 #include "core/dom/DocumentSupplementable.h"
39 #include "core/dom/DocumentTiming.h"
40 #include "core/dom/ExecutionContext.h"
41 #include "core/dom/IconURL.h"
42 #include "core/dom/MutationObserver.h"
43 #include "core/dom/QualifiedName.h"
44 #include "core/dom/TextLinkColors.h"
45 #include "core/dom/TreeScope.h"
46 #include "core/dom/UserActionElementSet.h"
47 #include "core/dom/ViewportDescription.h"
48 #include "core/dom/custom/CustomElement.h"
49 #include "core/html/CollectionType.h"
50 #include "core/page/FocusType.h"
51 #include "core/page/PageVisibilityState.h"
52 #include "core/rendering/HitTestRequest.h"
53 #include "platform/Timer.h"
54 #include "platform/weborigin/KURL.h"
55 #include "platform/weborigin/ReferrerPolicy.h"
56 #include "wtf/HashSet.h"
57 #include "wtf/OwnPtr.h"
58 #include "wtf/PassOwnPtr.h"
59 #include "wtf/PassRefPtr.h"
60 #include "wtf/WeakPtr.h"
68 class CSSFontSelector;
69 class CSSStyleDeclaration;
71 class CSSStyleSheetResource;
72 class CanvasRenderingContext;
76 class ContentSecurityPolicyResponseHeaders;
77 class ContextFeatures;
78 class CustomElementRegistrationContext;
79 class DOMImplementation;
84 class DocumentFragment;
85 class DocumentLifecycleNotifier;
86 class DocumentLifecycleObserver;
88 class DocumentMarkerController;
90 class DocumentTimeline;
93 class ElementDataCache;
97 class FastTextAutosizer;
101 class FormController;
105 class HTMLAllCollection;
106 class HTMLCanvasElement;
107 class HTMLCollection;
108 class HTMLDialogElement;
111 class HTMLFrameOwnerElement;
112 class HTMLHeadElement;
113 class HTMLIFrameElement;
115 class HTMLMapElement;
116 class HTMLNameCollection;
117 class HTMLScriptElement;
118 class HitTestRequest;
124 class LiveNodeListBase;
127 class MainThreadTaskRunner;
128 class MediaQueryList;
129 class MediaQueryMatcher;
130 class MouseEventWithHitTestResults;
134 class PlatformMouseEvent;
135 class ProcessingInstruction;
137 class RegisteredEventListener;
139 class RequestAnimationFrameCallback;
140 class ResourceFetcher;
141 class SVGDocumentExtensions;
143 class ScriptElementData;
144 class ScriptResource;
146 class ScriptableDocumentParser;
147 class ScriptedAnimationController;
148 class SecurityOrigin;
149 class SegmentedString;
150 class SelectorQueryCache;
151 class SerializedScriptValue;
156 class StyleSheetContents;
157 class StyleSheetList;
162 class TransformSource;
164 class VisitedLinkState;
165 class XMLHttpRequest;
167 struct AnnotatedRegionValue;
169 typedef int ExceptionCode;
171 enum RecalcStyleTime {
172 RecalcStyleImmediately, // synchronous
173 RecalcStyleDeferred // asynchronous
176 enum StyleResolverUpdateMode {
177 // Discards the StyleResolver and rebuilds it.
179 // Attempts to use StyleInvalidationAnalysis to avoid discarding the entire StyleResolver.
183 enum NodeListInvalidationType {
184 DoNotInvalidateOnAttributeChanges = 0,
185 InvalidateOnClassAttrChange,
186 InvalidateOnIdNameAttrChange,
187 InvalidateOnNameAttrChange,
188 InvalidateOnForAttrChange,
189 InvalidateForFormControls,
190 InvalidateOnHRefAttrChange,
191 InvalidateOnAnyAttrChange,
193 const int numNodeListInvalidationTypes = InvalidateOnAnyAttrChange + 1;
195 typedef HashCountedSet<Node*> TouchEventTargetSet;
198 DefaultDocumentClass = 0,
199 HTMLDocumentClass = 1,
200 XHTMLDocumentClass = 1 << 1,
201 ImageDocumentClass = 1 << 2,
202 PluginDocumentClass = 1 << 3,
203 MediaDocumentClass = 1 << 4,
204 SVGDocumentClass = 1 << 5,
205 XMLDocumentClass = 1 << 6,
208 typedef unsigned char DocumentClassFlags;
212 class DocumentVisibilityObserver {
214 DocumentVisibilityObserver(Document&);
215 virtual ~DocumentVisibilityObserver();
217 virtual void didChangeVisibilityState(PageVisibilityState) = 0;
219 // Classes that inherit Node and DocumentVisibilityObserver must have a
220 // virtual override of Node::didMoveToNewDocument that calls
221 // DocumentVisibilityObserver::setDocument
222 void setObservedDocument(Document&);
225 void registerObserver(Document&);
226 void unregisterObserver();
227 Document* m_document;
230 class Document : public ContainerNode, public TreeScope, public SecurityContext, public ExecutionContext, public ExecutionContextClient
231 , public DocumentSupplementable, public LifecycleContext<Document> {
233 static PassRefPtr<Document> create(const DocumentInit& initializer = DocumentInit())
235 return adoptRef(new Document(initializer));
239 MediaQueryMatcher& mediaQueryMatcher();
241 void mediaQueryAffectingValueChanged();
243 using ContainerNode::ref;
244 using ContainerNode::deref;
245 using SecurityContext::securityOrigin;
246 using SecurityContext::contentSecurityPolicy;
247 using ExecutionContextClient::addConsoleMessage;
249 virtual bool canContainRangeEndPoint() const OVERRIDE { return true; }
251 SelectorQueryCache& selectorQueryCache();
254 Element* activeElement() const;
255 bool hasFocus() const;
257 // DOM methods & attributes for Document
259 DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecopy);
260 DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecut);
261 DEFINE_ATTRIBUTE_EVENT_LISTENER(beforepaste);
262 DEFINE_ATTRIBUTE_EVENT_LISTENER(copy);
263 DEFINE_ATTRIBUTE_EVENT_LISTENER(cut);
264 DEFINE_ATTRIBUTE_EVENT_LISTENER(paste);
265 DEFINE_ATTRIBUTE_EVENT_LISTENER(readystatechange);
266 DEFINE_ATTRIBUTE_EVENT_LISTENER(search);
267 DEFINE_ATTRIBUTE_EVENT_LISTENER(securitypolicyviolation);
268 DEFINE_ATTRIBUTE_EVENT_LISTENER(selectionchange);
269 DEFINE_ATTRIBUTE_EVENT_LISTENER(selectstart);
270 DEFINE_ATTRIBUTE_EVENT_LISTENER(touchcancel);
271 DEFINE_ATTRIBUTE_EVENT_LISTENER(touchend);
272 DEFINE_ATTRIBUTE_EVENT_LISTENER(touchmove);
273 DEFINE_ATTRIBUTE_EVENT_LISTENER(touchstart);
274 DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitfullscreenchange);
275 DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitfullscreenerror);
276 DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitpointerlockchange);
277 DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitpointerlockerror);
278 DEFINE_ATTRIBUTE_EVENT_LISTENER(wheel);
280 bool shouldMergeWithLegacyDescription(ViewportDescription::Type);
281 bool shouldOverrideLegacyDescription(ViewportDescription::Type);
282 void setViewportDescription(const ViewportDescription&);
283 const ViewportDescription& viewportDescription() const { return m_viewportDescription; }
285 bool didDispatchViewportPropertiesChanged() const { return m_didDispatchViewportPropertiesChanged; }
287 bool hasLegacyViewportTag() const { return m_legacyViewportDescription.isLegacyViewportType(); }
289 void setReferrerPolicy(ReferrerPolicy);
290 ReferrerPolicy referrerPolicy() const { return m_referrerPolicy; }
292 String outgoingReferrer();
293 String outgoingOrigin() const;
295 void setDoctype(PassRefPtr<DocumentType>);
296 DocumentType* doctype() const { return m_docType.get(); }
298 DOMImplementation* implementation();
300 Element* documentElement() const
302 return m_documentElement.get();
305 bool hasManifest() const;
307 Location* location() const;
309 PassRefPtr<Element> createElement(const AtomicString& name, ExceptionState&);
310 PassRefPtr<DocumentFragment> createDocumentFragment();
311 PassRefPtr<Text> createTextNode(const String& data);
312 PassRefPtr<Comment> createComment(const String& data);
313 PassRefPtr<CDATASection> createCDATASection(const String& data, ExceptionState&);
314 PassRefPtr<ProcessingInstruction> createProcessingInstruction(const String& target, const String& data, ExceptionState&);
315 PassRefPtr<Attr> createAttribute(const AtomicString& name, ExceptionState&);
316 PassRefPtr<Node> importNode(Node* importedNode, ExceptionState& ec) { return importNode(importedNode, true, ec); }
317 PassRefPtr<Node> importNode(Node* importedNode, bool deep, ExceptionState&);
318 PassRefPtr<Element> createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState&);
319 PassRefPtr<Element> createElement(const QualifiedName&, bool createdByParser);
321 bool regionBasedColumnsEnabled() const;
324 * Retrieve all nodes that intersect a rect in the window's document, until it is fully enclosed by
325 * the boundaries of a node.
327 * @param centerX x reference for the rectangle in CSS pixels
328 * @param centerY y reference for the rectangle in CSS pixels
329 * @param topPadding How much to expand the top of the rectangle
330 * @param rightPadding How much to expand the right of the rectangle
331 * @param bottomPadding How much to expand the bottom of the rectangle
332 * @param leftPadding How much to expand the left of the rectangle
334 PassRefPtr<NodeList> nodesFromRect(int centerX, int centerY,
335 unsigned topPadding, unsigned rightPadding, unsigned bottomPadding, unsigned leftPadding,
336 HitTestRequest::HitTestRequestType hitType = HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent) const;
337 Element* elementFromPoint(int x, int y) const;
338 PassRefPtr<Range> caretRangeFromPoint(int x, int y);
340 String readyState() const;
342 String defaultCharset() const;
344 AtomicString inputEncoding() const { return Document::encodingName(); }
345 AtomicString charset() const { return Document::encodingName(); }
346 AtomicString characterSet() const { return Document::encodingName(); }
348 AtomicString encodingName() const;
350 void setCharset(const String&);
352 void setContent(const String&);
354 String suggestedMIMEType() const;
356 const AtomicString& contentLanguage() const { return m_contentLanguage; }
357 void setContentLanguage(const AtomicString&);
359 String xmlEncoding() const { return m_xmlEncoding; }
360 String xmlVersion() const { return m_xmlVersion; }
361 enum StandaloneStatus { StandaloneUnspecified, Standalone, NotStandalone };
362 bool xmlStandalone() const { return m_xmlStandalone == Standalone; }
363 StandaloneStatus xmlStandaloneStatus() const { return static_cast<StandaloneStatus>(m_xmlStandalone); }
364 bool hasXMLDeclaration() const { return m_hasXMLDeclaration; }
366 void setXMLEncoding(const String& encoding) { m_xmlEncoding = encoding; } // read-only property, only to be set from XMLDocumentParser
367 void setXMLVersion(const String&, ExceptionState&);
368 void setXMLStandalone(bool, ExceptionState&);
369 void setHasXMLDeclaration(bool hasXMLDeclaration) { m_hasXMLDeclaration = hasXMLDeclaration ? 1 : 0; }
371 virtual KURL baseURI() const OVERRIDE FINAL;
373 String visibilityState() const;
375 void didChangeVisibilityState();
377 PassRefPtr<Node> adoptNode(PassRefPtr<Node> source, ExceptionState&);
379 PassRefPtr<HTMLCollection> images();
380 PassRefPtr<HTMLCollection> embeds();
381 PassRefPtr<HTMLCollection> applets();
382 PassRefPtr<HTMLCollection> links();
383 PassRefPtr<HTMLCollection> forms();
384 PassRefPtr<HTMLCollection> anchors();
385 PassRefPtr<HTMLCollection> scripts();
386 PassRefPtr<HTMLCollection> allForBinding();
387 PassRefPtr<HTMLCollection> all();
389 PassRefPtr<HTMLCollection> windowNamedItems(const AtomicString& name);
390 PassRefPtr<HTMLCollection> documentNamedItems(const AtomicString& name);
392 bool isHTMLDocument() const { return m_documentClasses & HTMLDocumentClass; }
393 bool isXHTMLDocument() const { return m_documentClasses & XHTMLDocumentClass; }
394 bool isXMLDocument() const { return m_documentClasses & XMLDocumentClass; }
395 bool isImageDocument() const { return m_documentClasses & ImageDocumentClass; }
396 bool isSVGDocument() const { return m_documentClasses & SVGDocumentClass; }
397 bool isPluginDocument() const { return m_documentClasses & PluginDocumentClass; }
398 bool isMediaDocument() const { return m_documentClasses & MediaDocumentClass; }
400 bool hasSVGRootNode() const;
402 bool isFrameSet() const;
404 bool isSrcdocDocument() const { return m_isSrcdocDocument; }
405 bool isMobileDocument() const { return m_isMobileDocument; }
407 StyleResolver* styleResolver() const;
408 StyleResolver& ensureStyleResolver() const;
410 bool isViewSource() const { return m_isViewSource; }
411 void setIsViewSource(bool);
413 bool sawElementsInKnownNamespaces() const { return m_sawElementsInKnownNamespaces; }
415 void notifyRemovePendingSheetIfNeeded();
417 bool haveStylesheetsLoaded() const;
418 bool haveStylesheetsAndImportsLoaded() const { return haveImportsLoaded() && haveStylesheetsLoaded(); }
420 // This is a DOM function.
421 StyleSheetList* styleSheets();
423 StyleEngine* styleEngine() { return m_styleEngine.get(); }
425 bool gotoAnchorNeededAfterStylesheetsLoad() { return m_gotoAnchorNeededAfterStylesheetsLoad; }
426 void setGotoAnchorNeededAfterStylesheetsLoad(bool b) { m_gotoAnchorNeededAfterStylesheetsLoad = b; }
428 // Called when one or more stylesheets in the document may have been added, removed, or changed.
429 void styleResolverChanged(RecalcStyleTime, StyleResolverUpdateMode = FullStyleUpdate);
431 // FIXME: Switch all callers of styleResolverChanged to these or better ones and then make them
432 // do something smarter.
433 void removedStyleSheet(StyleSheet*, RecalcStyleTime when = RecalcStyleDeferred, StyleResolverUpdateMode = FullStyleUpdate);
434 void addedStyleSheet(StyleSheet*, RecalcStyleTime when = RecalcStyleDeferred) { styleResolverChanged(when); }
435 void modifiedStyleSheet(StyleSheet*, RecalcStyleTime when = RecalcStyleDeferred, StyleResolverUpdateMode = FullStyleUpdate);
436 void changedSelectorWatch() { styleResolverChanged(RecalcStyleDeferred); }
438 void scheduleUseShadowTreeUpdate(SVGUseElement&);
439 void unscheduleUseShadowTreeUpdate(SVGUseElement&);
441 void evaluateMediaQueryList();
444 FormController* formController();
445 Vector<String> formElementsState() const;
446 void setStateForNewFormElements(const Vector<String>&);
448 FrameView* view() const; // can be null
449 Frame* frame() const { return m_frame; } // can be null
450 FrameHost* frameHost() const; // can be null
451 Page* page() const; // can be null
452 Settings* settings() const; // can be null
454 float devicePixelRatio() const;
456 PassRefPtr<Range> createRange();
458 PassRefPtr<NodeIterator> createNodeIterator(Node* root, ExceptionState&);
459 PassRefPtr<NodeIterator> createNodeIterator(Node* root, unsigned whatToShow, ExceptionState&);
460 PassRefPtr<NodeIterator> createNodeIterator(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter>, ExceptionState&);
462 PassRefPtr<TreeWalker> createTreeWalker(Node* root, ExceptionState&);
463 PassRefPtr<TreeWalker> createTreeWalker(Node* root, unsigned whatToShow, ExceptionState&);
464 PassRefPtr<TreeWalker> createTreeWalker(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter>, ExceptionState&);
466 // Special support for editing
467 PassRefPtr<Text> createEditingTextNode(const String&);
469 void setupFontBuilder(RenderStyle* documentStyle);
471 void updateStyleIfNeeded();
472 void updateStyleForNodeIfNeeded(Node*);
474 enum RunPostLayoutTasks {
475 RunPostLayoutTasksAsyhnchronously,
476 RunPostLayoutTasksSynchronously,
478 void updateLayoutIgnorePendingStylesheets(RunPostLayoutTasks = RunPostLayoutTasksAsyhnchronously);
479 void partialUpdateLayoutIgnorePendingStylesheets(Node*);
480 PassRefPtr<RenderStyle> styleForElementIgnoringPendingStylesheets(Element*);
481 PassRefPtr<RenderStyle> styleForPage(int pageIndex);
483 void updateDistributionForNodeIfNeeded(Node*);
485 // Returns true if page box (margin boxes and page borders) is visible.
486 bool isPageBoxVisible(int pageIndex);
488 // Returns the preferred page size and margins in pixels, assuming 96
489 // pixels per inch. pageSize, marginTop, marginRight, marginBottom,
490 // marginLeft must be initialized to the default values that are used if
491 // auto is specified.
492 void pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft);
494 ResourceFetcher* fetcher() { return m_fetcher.get(); }
496 virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
497 virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
498 void prepareForDestruction();
500 RenderView* renderView() const { return m_renderView; }
502 AXObjectCache* existingAXObjectCache() const;
503 AXObjectCache* axObjectCache() const;
504 void clearAXObjectCache();
506 // to get visually ordered hebrew and arabic pages right
507 bool visuallyOrdered() const { return m_visuallyOrdered; }
509 DocumentLoader* loader() const;
511 void open(Document* ownerDocument = 0);
512 PassRefPtr<DocumentParser> implicitOpen();
514 // close() is the DOM API document.close()
516 // In some situations (see the code), we ignore document.close().
517 // explicitClose() bypass these checks and actually tries to close the
519 void explicitClose();
520 // implicitClose() actually does the work of closing the input stream.
521 void implicitClose();
523 bool dispatchBeforeUnloadEvent(Chrome&, bool&);
524 void dispatchUnloadEvents();
526 enum PageDismissalType {
528 BeforeUnloadDismissal = 1,
529 PageHideDismissal = 2,
532 PageDismissalType pageDismissalEventBeingDispatched() const;
534 void cancelParsing();
536 void write(const SegmentedString& text, Document* ownerDocument = 0);
537 void write(const String& text, Document* ownerDocument = 0);
538 void writeln(const String& text, Document* ownerDocument = 0);
540 bool wellFormed() const { return m_wellFormed; }
542 const KURL& url() const { return m_url; }
543 void setURL(const KURL&);
545 // To understand how these concepts relate to one another, please see the
546 // comments surrounding their declaration.
547 const KURL& baseURL() const { return m_baseURL; }
548 void setBaseURLOverride(const KURL&);
549 const KURL& baseURLOverride() const { return m_baseURLOverride; }
550 const KURL& baseElementURL() const { return m_baseElementURL; }
551 const AtomicString& baseTarget() const { return m_baseTarget; }
552 void processBaseElement();
554 KURL completeURL(const String&) const;
555 KURL completeURLWithOverride(const String&, const KURL& baseURLOverride) const;
557 virtual String userAgent(const KURL&) const OVERRIDE FINAL;
558 virtual void disableEval(const String& errorMessage) OVERRIDE FINAL;
560 bool canNavigate(Frame* targetFrame);
561 Frame* findUnsafeParentScrollPropagationBoundary();
563 CSSStyleSheet* elementSheet();
565 virtual PassRefPtr<DocumentParser> createParser();
566 DocumentParser* parser() const { return m_parser.get(); }
567 ScriptableDocumentParser* scriptableDocumentParser() const;
569 bool printing() const { return m_printing; }
570 void setPrinting(bool p) { m_printing = p; }
572 bool paginatedForScreen() const { return m_paginatedForScreen; }
573 void setPaginatedForScreen(bool p) { m_paginatedForScreen = p; }
575 bool paginated() const { return printing() || paginatedForScreen(); }
577 enum CompatibilityMode { QuirksMode, LimitedQuirksMode, NoQuirksMode };
579 void setCompatibilityMode(CompatibilityMode m);
580 void lockCompatibilityMode() { m_compatibilityModeLocked = true; }
581 CompatibilityMode compatibilityMode() const { return m_compatibilityMode; }
583 String compatMode() const;
585 bool inQuirksMode() const { return m_compatibilityMode == QuirksMode; }
586 bool inLimitedQuirksMode() const { return m_compatibilityMode == LimitedQuirksMode; }
587 bool inNoQuirksMode() const { return m_compatibilityMode == NoQuirksMode; }
594 void setReadyState(ReadyState);
595 bool isLoadCompleted();
597 void setParsing(bool);
598 bool parsing() const { return m_isParsing; }
600 bool shouldScheduleLayout();
601 bool shouldParserYieldAgressivelyBeforeScriptExecution();
602 int elapsedTime() const;
604 TextLinkColors& textLinkColors() { return m_textLinkColors; }
605 VisitedLinkState& visitedLinkState() const { return *m_visitedLinkState; }
607 MouseEventWithHitTestResults prepareMouseEvent(const HitTestRequest&, const LayoutPoint&, const PlatformMouseEvent&);
609 /* Newly proposed CSS3 mechanism for selecting alternate
610 stylesheets using the DOM. May be subject to change as
613 String preferredStylesheetSet() const;
614 String selectedStylesheetSet() const;
615 void setSelectedStylesheetSet(const String&);
617 bool setFocusedElement(PassRefPtr<Element>, FocusType = FocusTypeNone);
618 Element* focusedElement() const { return m_focusedElement.get(); }
619 UserActionElementSet& userActionElements() { return m_userActionElements; }
620 const UserActionElementSet& userActionElements() const { return m_userActionElements; }
621 void setNeedsFocusedElementCheck();
622 void setAutofocusElement(Element*);
623 Element* autofocusElement() const { return m_autofocusElement.get(); }
625 void setHoverNode(PassRefPtr<Node>);
626 Node* hoverNode() const { return m_hoverNode.get(); }
628 void setActiveHoverElement(PassRefPtr<Element>);
629 Element* activeHoverElement() const { return m_activeHoverElement.get(); }
631 void removeFocusedElementOfSubtree(Node*, bool amongChildrenOnly = false);
632 void hoveredNodeDetached(Node*);
633 void activeChainNodeDetached(Node*);
635 void updateHoverActiveState(const HitTestRequest&, Element*, const PlatformMouseEvent* = 0);
637 // Updates for :target (CSS3 selector).
638 void setCSSTarget(Element*);
639 Element* cssTarget() const { return m_cssTarget; }
641 void scheduleStyleRecalc();
642 bool hasPendingForcedStyleRecalc() const;
644 void registerNodeList(LiveNodeListBase*);
645 void unregisterNodeList(LiveNodeListBase*);
646 void incrementNodeListWithIdNameCacheCount();
647 void decrementNodeListWithIdNameCacheCount();
648 bool shouldInvalidateNodeListCaches(const QualifiedName* attrName = 0) const;
649 void invalidateNodeListCaches(const QualifiedName* attrName);
651 void attachNodeIterator(NodeIterator*);
652 void detachNodeIterator(NodeIterator*);
653 void moveNodeIteratorsToNewDocument(Node&, Document&);
655 void attachRange(Range*);
656 void detachRange(Range*);
658 void updateRangesAfterChildrenChanged(ContainerNode*);
659 // nodeChildrenWillBeRemoved is used when removing all node children at once.
660 void nodeChildrenWillBeRemoved(ContainerNode*);
661 // nodeWillBeRemoved is only safe when removing one node at a time.
662 void nodeWillBeRemoved(Node&);
663 bool canReplaceChild(const Node& newChild, const Node& oldChild) const;
665 void didInsertText(Node*, unsigned offset, unsigned length);
666 void didRemoveText(Node*, unsigned offset, unsigned length);
667 void didMergeTextNodes(Text* oldNode, unsigned offset);
668 void didSplitTextNode(Text* oldNode);
670 void clearDOMWindow() { m_domWindow = 0; }
671 DOMWindow* domWindow() const { return m_domWindow; }
673 // Helper functions for forwarding DOMWindow event related tasks to the DOMWindow if it exists.
674 void setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener>);
675 EventListener* getWindowAttributeEventListener(const AtomicString& eventType);
677 PassRefPtr<Event> createEvent(const String& eventType, ExceptionState&);
678 PassRefPtr<Event> createEvent(ExceptionState&);
680 // keep track of what types of event listeners are registered, so we don't
681 // dispatch events unnecessarily
683 DOMSUBTREEMODIFIED_LISTENER = 1,
684 DOMNODEINSERTED_LISTENER = 1 << 1,
685 DOMNODEREMOVED_LISTENER = 1 << 2,
686 DOMNODEREMOVEDFROMDOCUMENT_LISTENER = 1 << 3,
687 DOMNODEINSERTEDINTODOCUMENT_LISTENER = 1 << 4,
688 DOMCHARACTERDATAMODIFIED_LISTENER = 1 << 5,
689 OVERFLOWCHANGED_LISTENER = 1 << 6,
690 ANIMATIONEND_LISTENER = 1 << 7,
691 ANIMATIONSTART_LISTENER = 1 << 8,
692 ANIMATIONITERATION_LISTENER = 1 << 9,
693 TRANSITIONEND_LISTENER = 1 << 10,
694 BEFORELOAD_LISTENER = 1 << 11,
695 SCROLL_LISTENER = 1 << 12
699 bool hasListenerType(ListenerType listenerType) const { return (m_listenerTypes & listenerType); }
700 void addListenerTypeIfNeeded(const AtomicString& eventType);
702 bool hasMutationObserversOfType(MutationObserver::MutationType type) const
704 return m_mutationObserverTypes & type;
706 bool hasMutationObservers() const { return m_mutationObserverTypes; }
707 void addMutationObserverTypes(MutationObserverOptions types) { m_mutationObserverTypes |= types; }
709 CSSStyleDeclaration* getOverrideStyle(Element*, const String& pseudoElt);
712 * Handles a HTTP header equivalent set by a meta tag using <meta http-equiv="..." content="...">. This is called
713 * when a meta tag is encountered during document parsing, and also when a script dynamically changes or adds a meta
714 * tag. This enables scripts to use meta tags to perform refreshes and set expiry dates in addition to them being
715 * specified in a HTML file.
717 * @param equiv The http header name (value of the meta tag's "equiv" attribute)
718 * @param content The header value (value of the meta tag's "content" attribute)
719 * @param inDocumentHeadElement Is the element in the document's <head> element?
721 void processHttpEquiv(const AtomicString& equiv, const AtomicString& content, bool inDocumentHeadElement);
722 void updateViewportDescription();
723 void processReferrerPolicy(const String& policy);
725 // Returns the owning element in the parent document.
726 // Returns 0 if this is the top level document.
727 HTMLFrameOwnerElement* ownerElement() const;
729 String title() const { return m_title; }
730 void setTitle(const String&);
732 Element* titleElement() const { return m_titleElement.get(); }
733 void setTitleElement(const String& title, Element* titleElement);
734 void removeTitle(Element* titleElement);
736 String cookie(ExceptionState&) const;
737 void setCookie(const String&, ExceptionState&);
739 const AtomicString& referrer() const;
741 String domain() const;
742 void setDomain(const String& newDomain, ExceptionState&);
744 String lastModified() const;
746 // The cookieURL is used to query the cookie database for this document's
747 // cookies. For example, if the cookie URL is http://example.com, we'll
748 // use the non-Secure cookies for example.com when computing
751 // Q: How is the cookieURL different from the document's URL?
752 // A: The two URLs are the same almost all the time. However, if one
753 // document inherits the security context of another document, it
754 // inherits its cookieURL but not its URL.
756 const KURL& cookieURL() const { return m_cookieURL; }
757 void setCookieURL(const KURL& url) { m_cookieURL = url; }
759 const KURL& firstPartyForCookies() const;
761 // The following implements the rule from HTML 4 for what valid names are.
762 // To get this right for all the XML cases, we probably have to improve this or move it
763 // and make it sensitive to the type of document.
764 static bool isValidName(const String&);
766 // The following breaks a qualified name into a prefix and a local name.
767 // It also does a validity check, and returns false if the qualified name
768 // is invalid. It also sets ExceptionCode when name is invalid.
769 static bool parseQualifiedName(const AtomicString& qualifiedName, AtomicString& prefix, AtomicString& localName, ExceptionState&);
771 // Checks to make sure prefix and namespace do not conflict (per DOM Core 3)
772 static bool hasValidNamespaceForElements(const QualifiedName&);
773 static bool hasValidNamespaceForAttributes(const QualifiedName&);
775 HTMLElement* body() const;
776 void setBody(PassRefPtr<HTMLElement>, ExceptionState&);
778 HTMLHeadElement* head();
780 // Decide which element is to define the viewport's overflow policy. If |rootStyle| is set, use
781 // that as the style for the root element, rather than obtaining it on our own. The reason for
782 // this is that style may not have been associated with the elements yet - in which case it may
783 // have been calculated on the fly (without associating it with the actual element) somewhere.
784 Element* viewportDefiningElement(RenderStyle* rootStyle = 0) const;
786 DocumentMarkerController* markers() const { return m_markers.get(); }
788 bool directionSetOnDocumentElement() const { return m_directionSetOnDocumentElement; }
789 bool writingModeSetOnDocumentElement() const { return m_writingModeSetOnDocumentElement; }
790 void setDirectionSetOnDocumentElement(bool b) { m_directionSetOnDocumentElement = b; }
791 void setWritingModeSetOnDocumentElement(bool b) { m_writingModeSetOnDocumentElement = b; }
793 bool execCommand(const String& command, bool userInterface = false, const String& value = String());
794 bool queryCommandEnabled(const String& command);
795 bool queryCommandIndeterm(const String& command);
796 bool queryCommandState(const String& command);
797 bool queryCommandSupported(const String& command);
798 String queryCommandValue(const String& command);
800 KURL openSearchDescriptionURL();
802 // designMode support
803 enum InheritedBool { off = false, on = true, inherit };
804 void setDesignMode(InheritedBool value);
805 InheritedBool getDesignMode() const;
806 bool inDesignMode() const;
808 Document* parentDocument() const;
809 Document* topDocument() const;
810 WeakPtr<Document> contextDocument();
812 ScriptRunner* scriptRunner() { return m_scriptRunner.get(); }
814 HTMLScriptElement* currentScript() const { return !m_currentScriptStack.isEmpty() ? m_currentScriptStack.last().get() : 0; }
815 void pushCurrentScript(PassRefPtr<HTMLScriptElement>);
816 void popCurrentScript();
818 void applyXSLTransform(ProcessingInstruction* pi);
819 PassRefPtr<Document> transformSourceDocument() { return m_transformSourceDocument; }
820 void setTransformSourceDocument(Document* doc) { m_transformSourceDocument = doc; }
822 void setTransformSource(PassOwnPtr<TransformSource>);
823 TransformSource* transformSource() const { return m_transformSource.get(); }
825 void incDOMTreeVersion() { ASSERT(!inStyleRecalc()); m_domTreeVersion = ++s_globalTreeVersion; }
826 uint64_t domTreeVersion() const { return m_domTreeVersion; }
828 enum PendingSheetLayout { NoLayoutWithPendingSheets, DidLayoutWithPendingSheets, IgnoreLayoutWithPendingSheets };
830 bool didLayoutWithPendingStylesheets() const { return m_pendingSheetLayout == DidLayoutWithPendingSheets; }
832 bool hasNodesWithPlaceholderStyle() const { return m_hasNodesWithPlaceholderStyle; }
833 void setHasNodesWithPlaceholderStyle() { m_hasNodesWithPlaceholderStyle = true; }
835 Vector<IconURL> iconURLs(int iconTypesMask);
837 void setUseSecureKeyboardEntryWhenActive(bool);
838 bool useSecureKeyboardEntryWhenActive() const;
840 void updateFocusAppearanceSoon(bool restorePreviousSelection);
841 void cancelFocusAppearanceUpdate();
843 // Extension for manipulating canvas drawing contexts for use in CSS
844 CanvasRenderingContext* getCSSCanvasContext(const String& type, const String& name, int width, int height);
845 HTMLCanvasElement* getCSSCanvasElement(const String& name);
847 bool isDNSPrefetchEnabled() const { return m_isDNSPrefetchEnabled; }
848 void parseDNSPrefetchControlHeader(const String&);
850 // FIXME(crbug.com/305497): This should be removed once DOMWindow is an ExecutionContext.
851 virtual void postTask(PassOwnPtr<ExecutionContextTask>) OVERRIDE; // Executes the task on context's thread asynchronously.
853 virtual void tasksWereSuspended() OVERRIDE FINAL;
854 virtual void tasksWereResumed() OVERRIDE FINAL;
855 virtual void suspendScheduledTasks() OVERRIDE FINAL;
856 virtual void resumeScheduledTasks() OVERRIDE FINAL;
857 virtual bool tasksNeedSuspension() OVERRIDE FINAL;
859 void finishedParsing();
861 void setEncodingData(const DocumentEncodingData& newData);
862 const WTF::TextEncoding& encoding() const { return m_encodingData.encoding(); }
864 bool encodingWasDetectedHeuristically() const { return m_encodingData.wasDetectedHeuristically(); }
865 bool sawDecodingError() const { return m_encodingData.sawDecodingError(); }
867 void setAnnotatedRegionsDirty(bool f) { m_annotatedRegionsDirty = f; }
868 bool annotatedRegionsDirty() const { return m_annotatedRegionsDirty; }
869 bool hasAnnotatedRegions () const { return m_hasAnnotatedRegions; }
870 void setHasAnnotatedRegions(bool f) { m_hasAnnotatedRegions = f; }
871 const Vector<AnnotatedRegionValue>& annotatedRegions() const;
872 void setAnnotatedRegions(const Vector<AnnotatedRegionValue>&);
874 virtual void removeAllEventListeners() OVERRIDE FINAL;
876 const SVGDocumentExtensions* svgExtensions();
877 SVGDocumentExtensions* accessSVGExtensions();
879 void initSecurityContext();
880 void initSecurityContext(const DocumentInit&);
881 void initContentSecurityPolicy(const ContentSecurityPolicyResponseHeaders&);
883 bool allowInlineEventHandlers(Node*, EventListener*, const String& contextURL, const WTF::OrdinalNumber& contextLine);
884 bool allowExecutingScripts(Node*);
886 void statePopped(PassRefPtr<SerializedScriptValue>);
888 enum LoadEventProgress {
893 BeforeUnloadEventInProgress,
894 BeforeUnloadEventCompleted,
896 UnloadEventInProgress,
899 bool loadEventStillNeeded() const { return m_loadEventProgress == LoadEventNotRun; }
900 bool processingLoadEvent() const { return m_loadEventProgress == LoadEventInProgress; }
901 bool loadEventFinished() const { return m_loadEventProgress >= LoadEventCompleted; }
902 bool unloadStarted() const { return m_loadEventProgress >= PageHideInProgress; }
904 void setContainsPlugins() { m_containsPlugins = true; }
905 bool containsPlugins() const { return m_containsPlugins; }
907 virtual bool isContextThread() const OVERRIDE FINAL;
908 virtual bool isJSExecutionForbidden() const OVERRIDE FINAL { return false; }
910 bool containsValidityStyleRules() const { return m_containsValidityStyleRules; }
911 void setContainsValidityStyleRules() { m_containsValidityStyleRules = true; }
913 void enqueueResizeEvent();
914 void enqueueScrollEventForNode(Node*);
915 void enqueueAnimationFrameEvent(PassRefPtr<Event>);
917 bool hasFullscreenElementStack() const { return m_hasFullscreenElementStack; }
918 void setHasFullscreenElementStack() { m_hasFullscreenElementStack = true; }
920 void webkitExitPointerLock();
921 Element* webkitPointerLockElement() const;
923 // Used to allow element that loads data without going through a FrameLoader to delay the 'load' event.
924 void incrementLoadEventDelayCount() { ++m_loadEventDelayCount; }
925 void decrementLoadEventDelayCount();
926 bool isDelayingLoadEvent() const { return m_loadEventDelayCount; }
927 void loadPluginsSoon();
929 PassRefPtr<Touch> createTouch(DOMWindow*, EventTarget*, int identifier, int pageX, int pageY, int screenX, int screenY, int radiusX, int radiusY, float rotationAngle, float force) const;
930 PassRefPtr<TouchList> createTouchList(Vector<RefPtr<Touch> >&) const;
932 const DocumentTiming* timing() const { return &m_documentTiming; }
934 int requestAnimationFrame(PassOwnPtr<RequestAnimationFrameCallback>);
935 void cancelAnimationFrame(int id);
936 void serviceScriptedAnimations(double monotonicAnimationStartTime);
938 virtual EventTarget* errorEventTarget() OVERRIDE FINAL;
939 virtual void logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack>) OVERRIDE FINAL;
941 void initDNSPrefetch();
943 double lastHandledUserGestureTimestamp() const { return m_lastHandledUserGestureTimestamp; }
944 void resetLastHandledUserGestureTimestamp();
946 bool hasTouchEventHandlers() const { return (m_touchEventTargets.get()) ? m_touchEventTargets->size() : false; }
948 // Called when a single touch event handler has been added or removed for a node.
949 // The Node should always be in this Document, except for child Documents which report
950 // themselves to their parent exactly once if they have any touch handlers.
951 // Handlers added/removed from the DOMWindow are reported as the Document.
952 void didAddTouchEventHandler(Node*);
953 void didRemoveTouchEventHandler(Node* handler) { didRemoveTouchEventHandler(handler, false); }
955 // Called whenever all touch event handlers have been removed for a node (such as when the
956 // node itself is being removed from the document).
957 void didClearTouchEventHandlers(Node* handler) { didRemoveTouchEventHandler(handler, true); }
959 const TouchEventTargetSet* touchEventTargets() const { return m_touchEventTargets.get(); }
961 bool isInDocumentWrite() { return m_writeRecursionDepth > 0; }
963 IntSize initialViewportSize() const;
965 // There are currently two parallel autosizing implementations: TextAutosizer and FastTextAutosizer.
966 // See http://tinyurl.com/chromium-fast-autosizer for more details.
967 TextAutosizer* textAutosizer();
968 FastTextAutosizer* fastTextAutosizer();
970 PassRefPtr<Element> createElement(const AtomicString& localName, const AtomicString& typeExtension, ExceptionState&);
971 PassRefPtr<Element> createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& typeExtension, ExceptionState&);
972 ScriptValue registerElement(WebCore::ScriptState*, const AtomicString& name, ExceptionState&);
973 ScriptValue registerElement(WebCore::ScriptState*, const AtomicString& name, const Dictionary& options, ExceptionState&, CustomElement::NameSet validNames = CustomElement::StandardNames);
974 CustomElementRegistrationContext* registrationContext() { return m_registrationContext.get(); }
976 void setImport(HTMLImport*);
977 HTMLImport* import() const { return m_import; }
978 bool haveImportsLoaded() const;
979 void didLoadAllImports();
981 void adjustFloatQuadsForScrollAndAbsoluteZoom(Vector<FloatQuad>&, RenderObject&);
982 void adjustFloatRectForScrollAndAbsoluteZoom(FloatRect&, RenderObject&);
984 bool hasActiveParser();
985 unsigned activeParserCount() { return m_activeParserCount; }
986 void incrementActiveParserCount() { ++m_activeParserCount; }
987 void decrementActiveParserCount();
989 void setContextFeatures(PassRefPtr<ContextFeatures>);
990 ContextFeatures* contextFeatures() const { return m_contextFeatures.get(); }
992 ElementDataCache* elementDataCache() { return m_elementDataCache.get(); }
994 void didRemoveAllPendingStylesheet();
995 void setNeedsNotifyRemoveAllPendingStylesheet() { m_needsNotifyRemoveAllPendingStylesheet = true; }
996 void clearStyleResolver();
998 bool inStyleRecalc() const { return m_lifecycle.state() == DocumentLifecycle::InStyleRecalc; }
1000 // Return a Locale for the default locale if the argument is null or empty.
1001 Locale& getCachedLocale(const AtomicString& locale = nullAtom);
1003 AnimationClock& animationClock() { return *m_animationClock; }
1004 DocumentTimeline* timeline() const { return m_timeline.get(); }
1005 DocumentTimeline* transitionTimeline() const { return m_transitionTimeline.get(); }
1006 CSSPendingAnimations& cssPendingAnimations() { return m_cssPendingAnimations; }
1008 void addToTopLayer(Element*, const Element* before = 0);
1009 void removeFromTopLayer(Element*);
1010 const Vector<RefPtr<Element> >& topLayerElements() const { return m_topLayerElements; }
1011 HTMLDialogElement* activeModalDialog() const;
1013 // A non-null m_templateDocumentHost implies that |this| was created by ensureTemplateDocument().
1014 bool isTemplateDocument() const { return !!m_templateDocumentHost; }
1015 Document& ensureTemplateDocument();
1016 Document* templateDocumentHost() { return m_templateDocumentHost; }
1018 void didAssociateFormControl(Element*);
1020 void addConsoleMessageWithRequestIdentifier(MessageSource, MessageLevel, const String& message, unsigned long requestIdentifier);
1022 virtual DOMWindow* executingWindow() OVERRIDE FINAL;
1023 virtual void userEventWasHandled() OVERRIDE FINAL { resetLastHandledUserGestureTimestamp(); }
1024 Frame* executingFrame();
1026 DocumentLifecycleNotifier& lifecycleNotifier();
1027 DocumentLifecycle& lifecycle() { return m_lifecycle; }
1028 bool isActive() const { return m_lifecycle.isActive(); }
1029 bool isStopped() const { return m_lifecycle.state() == DocumentLifecycle::Stopped; }
1031 enum HttpRefreshType {
1032 HttpRefreshFromHeader,
1033 HttpRefreshFromMetaTag
1035 void maybeHandleHttpRefresh(const String&, HttpRefreshType);
1037 void updateSecurityOrigin(PassRefPtr<SecurityOrigin>);
1038 PassOwnPtr<LifecycleNotifier<Document> > createLifecycleNotifier();
1040 void setHasViewportUnits() { m_hasViewportUnits = true; }
1041 bool hasViewportUnits() const { return m_hasViewportUnits; }
1042 void notifyResizeForViewportUnits();
1044 void registerVisibilityObserver(DocumentVisibilityObserver*);
1045 void unregisterVisibilityObserver(DocumentVisibilityObserver*);
1047 // FIXME: Remove this method once we have input routing in the browser
1048 // process. See http://crbug.com/339659.
1049 virtual void defaultEventHandler(Event*) OVERRIDE;
1052 Document(const DocumentInit&, DocumentClassFlags = DefaultDocumentClass);
1054 virtual void didUpdateSecurityOrigin() OVERRIDE FINAL;
1056 void clearXMLVersion() { m_xmlVersion = String(); }
1058 virtual void dispose() OVERRIDE;
1060 virtual PassRefPtr<Document> cloneDocumentWithoutChildren();
1064 friend class IgnoreDestructiveWriteCountIncrementer;
1066 ScriptedAnimationController& ensureScriptedAnimationController();
1067 virtual SecurityContext& securityContext() OVERRIDE FINAL { return *this; }
1068 virtual EventQueue* eventQueue() const OVERRIDE FINAL;
1070 void inheritHtmlAndBodyElementStyles(StyleRecalcChange);
1072 void updateDistributionIfNeeded();
1073 void updateStyleInvalidationIfNeeded();
1074 void updateUseShadowTreesIfNeeded();
1076 void updateStyle(StyleRecalcChange);
1078 void detachParser();
1080 virtual bool isDocument() const OVERRIDE FINAL { return true; }
1082 virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
1084 virtual String nodeName() const OVERRIDE FINAL;
1085 virtual NodeType nodeType() const OVERRIDE FINAL;
1086 virtual bool childTypeAllowed(NodeType) const OVERRIDE FINAL;
1087 virtual PassRefPtr<Node> cloneNode(bool deep = true) OVERRIDE FINAL;
1088 void cloneDataFromDocument(const Document&);
1090 virtual void refExecutionContext() OVERRIDE FINAL { ref(); }
1091 virtual void derefExecutionContext() OVERRIDE FINAL { deref(); }
1093 virtual const KURL& virtualURL() const OVERRIDE FINAL; // Same as url(), but needed for ExecutionContext to implement it without a performance loss for direct calls.
1094 virtual KURL virtualCompleteURL(const String&) const OVERRIDE FINAL; // Same as completeURL() for the same reason as above.
1096 virtual void reportBlockedScriptExecutionToInspector(const String& directiveText) OVERRIDE FINAL;
1097 virtual void addMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState*) OVERRIDE FINAL;
1098 void internalAddMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack>, ScriptState*);
1100 virtual double timerAlignmentInterval() const OVERRIDE FINAL;
1102 void updateTitle(const String&);
1103 void updateFocusAppearanceTimerFired(Timer<Document>*);
1104 void updateBaseURL();
1106 bool hasPendingStyleRecalc() const { return m_lifecycle.state() == DocumentLifecycle::StyleRecalcPending; }
1108 void executeScriptsWaitingForResourcesIfNeeded();
1110 void recalcStyleForLayoutIgnoringPendingStylesheets();
1112 PassRefPtr<NodeList> handleZeroPadding(const HitTestRequest&, HitTestResult&) const;
1114 void loadEventDelayTimerFired(Timer<Document>*);
1115 void pluginLoadingTimerFired(Timer<Document>*);
1117 PageVisibilityState pageVisibilityState() const;
1119 PassRefPtr<HTMLCollection> ensureCachedCollection(CollectionType);
1121 // Note that dispatching a window load event may cause the DOMWindow to be detached from
1122 // the Frame, so callers should take a reference to the DOMWindow (which owns us) to
1123 // prevent the Document from getting blown away from underneath them.
1124 void dispatchWindowLoadEvent();
1126 void addListenerType(ListenerType listenerType) { m_listenerTypes |= listenerType; }
1127 void addMutationEventListenerTypeIfEnabled(ListenerType);
1129 void didAssociateFormControlsTimerFired(Timer<Document>*);
1131 void clearFocusedElementSoon();
1132 void clearFocusedElementTimerFired(Timer<Document>*);
1134 void processHttpEquivDefaultStyle(const AtomicString& content);
1135 void processHttpEquivRefresh(const AtomicString& content);
1136 void processHttpEquivSetCookie(const AtomicString& content);
1137 void processHttpEquivXFrameOptions(const AtomicString& content);
1138 void processHttpEquivContentSecurityPolicy(const AtomicString& equiv, const AtomicString& content);
1140 void didRemoveTouchEventHandler(Node*, bool clearAll);
1142 // Returns true if Document::recalcStyle() needs to be run.
1143 bool shouldCallRecalcStyleForDocument();
1144 bool shouldScheduleStyleRecalc();
1146 DocumentLifecycle m_lifecycle;
1148 bool m_hasNodesWithPlaceholderStyle;
1149 bool m_needsNotifyRemoveAllPendingStylesheet;
1150 bool m_evaluateMediaQueriesOnStyleRecalc;
1152 // If we do ignore the pending stylesheet count, then we need to add a boolean
1153 // to track that this happened so that we can do a full repaint when the stylesheets
1154 // do eventually load.
1155 PendingSheetLayout m_pendingSheetLayout;
1158 DOMWindow* m_domWindow;
1159 HTMLImport* m_import;
1161 RefPtr<ResourceFetcher> m_fetcher;
1162 RefPtr<DocumentParser> m_parser;
1163 unsigned m_activeParserCount;
1164 RefPtr<ContextFeatures> m_contextFeatures;
1169 KURL m_url; // Document.URL: The URL from which this document was retrieved.
1170 KURL m_baseURL; // Node.baseURI: The URL to use when resolving relative URLs.
1171 KURL m_baseURLOverride; // An alternative base URL that takes precedence over m_baseURL (but not m_baseElementURL).
1172 KURL m_baseElementURL; // The URL set by the <base> element.
1173 KURL m_cookieURL; // The URL to use for cookie access.
1175 AtomicString m_baseTarget;
1177 RefPtr<DocumentType> m_docType;
1178 OwnPtr<DOMImplementation> m_implementation;
1180 RefPtr<CSSStyleSheet> m_elemSheet;
1183 bool m_paginatedForScreen;
1185 CompatibilityMode m_compatibilityMode;
1186 bool m_compatibilityModeLocked; // This is cheaper than making setCompatibilityMode virtual.
1188 bool m_hasAutofocused;
1189 Timer<Document> m_clearFocusedElementTimer;
1190 RefPtr<Element> m_autofocusElement;
1191 RefPtr<Element> m_focusedElement;
1192 RefPtr<Node> m_hoverNode;
1193 RefPtr<Element> m_activeHoverElement;
1194 RefPtr<Element> m_documentElement;
1195 UserActionElementSet m_userActionElements;
1197 uint64_t m_domTreeVersion;
1198 static uint64_t s_globalTreeVersion;
1200 HashSet<NodeIterator*> m_nodeIterators;
1201 HashSet<Range*> m_ranges;
1203 unsigned short m_listenerTypes;
1205 MutationObserverOptions m_mutationObserverTypes;
1207 OwnPtr<StyleEngine> m_styleEngine;
1208 RefPtr<StyleSheetList> m_styleSheetList;
1210 OwnPtr<FormController> m_formController;
1212 TextLinkColors m_textLinkColors;
1213 const OwnPtr<VisitedLinkState> m_visitedLinkState;
1215 bool m_visuallyOrdered;
1216 ReadyState m_readyState;
1219 bool m_gotoAnchorNeededAfterStylesheetsLoad;
1220 bool m_isDNSPrefetchEnabled;
1221 bool m_haveExplicitlyDisabledDNSPrefetch;
1222 bool m_containsValidityStyleRules;
1223 bool m_updateFocusAppearanceRestoresSelection;
1224 bool m_containsPlugins;
1226 // http://www.whatwg.org/specs/web-apps/current-work/#ignore-destructive-writes-counter
1227 unsigned m_ignoreDestructiveWriteCount;
1231 bool m_titleSetExplicitly;
1232 RefPtr<Element> m_titleElement;
1234 OwnPtr<AXObjectCache> m_axObjectCache;
1235 OwnPtr<DocumentMarkerController> m_markers;
1237 Timer<Document> m_updateFocusAppearanceTimer;
1239 Element* m_cssTarget;
1241 LoadEventProgress m_loadEventProgress;
1245 OwnPtr<ScriptRunner> m_scriptRunner;
1247 Vector<RefPtr<HTMLScriptElement> > m_currentScriptStack;
1249 OwnPtr<TransformSource> m_transformSource;
1250 RefPtr<Document> m_transformSourceDocument;
1252 String m_xmlEncoding;
1253 String m_xmlVersion;
1254 unsigned m_xmlStandalone : 2;
1255 unsigned m_hasXMLDeclaration : 1;
1257 AtomicString m_contentLanguage;
1259 DocumentEncodingData m_encodingData;
1261 InheritedBool m_designMode;
1263 HashSet<LiveNodeListBase*> m_listsInvalidatedAtDocument;
1264 unsigned m_nodeListCounts[numNodeListInvalidationTypes];
1266 OwnPtr<SVGDocumentExtensions> m_svgExtensions;
1268 Vector<AnnotatedRegionValue> m_annotatedRegions;
1269 bool m_hasAnnotatedRegions;
1270 bool m_annotatedRegionsDirty;
1272 HashMap<String, RefPtr<HTMLCanvasElement> > m_cssCanvasElements;
1274 OwnPtr<SelectorQueryCache> m_selectorQueryCache;
1276 bool m_useSecureKeyboardEntryWhenActive;
1278 DocumentClassFlags m_documentClasses;
1280 bool m_isViewSource;
1281 bool m_sawElementsInKnownNamespaces;
1282 bool m_isSrcdocDocument;
1283 bool m_isMobileDocument;
1285 RenderView* m_renderView;
1287 WeakPtrFactory<Document> m_weakFactory;
1288 WeakPtr<Document> m_contextDocument;
1290 bool m_hasFullscreenElementStack; // For early return in FullscreenElementStack::fromIfExists()
1292 Vector<RefPtr<Element> > m_topLayerElements;
1294 int m_loadEventDelayCount;
1295 Timer<Document> m_loadEventDelayTimer;
1296 Timer<Document> m_pluginLoadingTimer;
1298 ViewportDescription m_viewportDescription;
1299 ViewportDescription m_legacyViewportDescription;
1301 bool m_didSetReferrerPolicy;
1302 ReferrerPolicy m_referrerPolicy;
1304 bool m_directionSetOnDocumentElement;
1305 bool m_writingModeSetOnDocumentElement;
1306 DocumentTiming m_documentTiming;
1307 RefPtr<MediaQueryMatcher> m_mediaQueryMatcher;
1308 bool m_writeRecursionIsTooDeep;
1309 unsigned m_writeRecursionDepth;
1311 OwnPtr<TouchEventTargetSet> m_touchEventTargets;
1313 double m_lastHandledUserGestureTimestamp;
1315 RefPtr<ScriptedAnimationController> m_scriptedAnimationController;
1316 OwnPtr<MainThreadTaskRunner> m_taskRunner;
1317 OwnPtr<TextAutosizer> m_textAutosizer;
1318 OwnPtr<FastTextAutosizer> m_fastTextAutosizer;
1320 RefPtr<CustomElementRegistrationContext> m_registrationContext;
1322 void elementDataCacheClearTimerFired(Timer<Document>*);
1323 Timer<Document> m_elementDataCacheClearTimer;
1325 OwnPtr<ElementDataCache> m_elementDataCache;
1328 bool m_didDispatchViewportPropertiesChanged;
1331 typedef HashMap<AtomicString, OwnPtr<Locale> > LocaleIdentifierToLocaleMap;
1332 LocaleIdentifierToLocaleMap m_localeCache;
1334 OwnPtr<AnimationClock> m_animationClock;
1335 RefPtr<DocumentTimeline> m_timeline;
1336 RefPtr<DocumentTimeline> m_transitionTimeline;
1337 CSSPendingAnimations m_cssPendingAnimations;
1339 RefPtr<Document> m_templateDocument;
1340 Document* m_templateDocumentHost; // Manually managed weakref (backpointer from m_templateDocument).
1342 Timer<Document> m_didAssociateFormControlsTimer;
1343 HashSet<RefPtr<Element> > m_associatedFormControls;
1345 HashSet<SVGUseElement*> m_useElementsNeedingUpdate;
1347 bool m_hasViewportUnits;
1349 HashSet<DocumentVisibilityObserver*> m_visibilityObservers;
1352 inline void Document::notifyRemovePendingSheetIfNeeded()
1354 if (m_needsNotifyRemoveAllPendingStylesheet)
1355 didRemoveAllPendingStylesheet();
1358 inline bool Document::shouldOverrideLegacyDescription(ViewportDescription::Type origin)
1360 // The different (legacy) meta tags have different priorities based on the type
1361 // regardless of which order they appear in the DOM. The priority is given by the
1362 // ViewportDescription::Type enum.
1363 return origin >= m_legacyViewportDescription.type;
1366 inline void Document::incrementNodeListWithIdNameCacheCount()
1368 m_nodeListCounts[InvalidateOnIdNameAttrChange]++;
1371 inline void Document::decrementNodeListWithIdNameCacheCount()
1373 ASSERT(m_nodeListCounts[InvalidateOnIdNameAttrChange] > 0);
1374 m_nodeListCounts[InvalidateOnIdNameAttrChange]--;
1377 DEFINE_TYPE_CASTS(Document, ExecutionContextClient, client, client->isDocument(), client.isDocument());
1378 DEFINE_TYPE_CASTS(Document, ExecutionContext, context, context->isDocument(), context.isDocument());
1379 DEFINE_NODE_TYPE_CASTS(Document, isDocumentNode());
1381 #define DEFINE_DOCUMENT_TYPE_CASTS(thisType) \
1382 DEFINE_TYPE_CASTS(thisType, Document, document, document->is##thisType(), document.is##thisType())
1384 // All these varations are needed to avoid ambiguous overloads with the Node and TreeScope versions.
1385 inline bool operator==(const Document& a, const Document& b) { return &a == &b; }
1386 inline bool operator==(const Document& a, const Document* b) { return &a == b; }
1387 inline bool operator==(const Document* a, const Document& b) { return a == &b; }
1388 inline bool operator!=(const Document& a, const Document& b) { return !(a == b); }
1389 inline bool operator!=(const Document& a, const Document* b) { return !(a == b); }
1390 inline bool operator!=(const Document* a, const Document& b) { return !(a == b); }
1392 // Put these methods here, because they require the Document definition, but we really want to inline them.
1394 inline bool Node::isDocumentNode() const
1396 return this == document();
1399 Node* eventTargetNodeForDocument(Document*);
1401 } // namespace WebCore
1403 #endif // Document_h