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, 2013 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 "CollectionType.h"
33 #include "ContainerNode.h"
34 #include "DocumentEventQueue.h"
35 #include "DocumentStyleSheetCollection.h"
36 #include "DocumentTiming.h"
37 #include "FocusDirection.h"
38 #include "FontSelector.h"
39 #include "MediaProducer.h"
40 #include "MutationObserver.h"
41 #include "PageVisibilityState.h"
42 #include "PlatformEvent.h"
43 #include "PlatformScreen.h"
44 #include "ReferrerPolicy.h"
46 #include "RenderPtr.h"
47 #include "ScriptExecutionContext.h"
48 #include "StringWithDirection.h"
49 #include "StyleResolveTree.h"
51 #include "TreeScope.h"
52 #include "UserActionElementSet.h"
53 #include "ViewportArguments.h"
56 #include <wtf/Deque.h>
57 #include <wtf/HashSet.h>
58 #include <wtf/PassRefPtr.h>
59 #include <wtf/WeakPtr.h>
63 #if ENABLE(WEB_REPLAY)
73 class CSSFontSelector;
74 class CSSStyleDeclaration;
76 class CachedCSSStyleSheet;
77 class CachedResourceLoader;
79 class CanvasRenderingContext;
82 class DOMImplementation;
83 class DOMNamedFlowCollection;
86 class DOMWrapperWorld;
89 class DocumentFragment;
91 class DocumentMarkerController;
93 class DocumentSharedObjectPool;
96 class EntityReference;
101 class FormController;
104 class HTMLAllCollection;
105 class HTMLBodyElement;
106 class HTMLCanvasElement;
107 class HTMLCollection;
110 class HTMLFrameOwnerElement;
111 class HTMLHeadElement;
112 class HTMLIFrameElement;
113 class HTMLImageElement;
114 class HTMLMapElement;
115 class HTMLMediaElement;
116 class HTMLNameCollection;
117 class HTMLScriptElement;
118 class HitTestRequest;
126 class MediaCanStartListener;
127 class MediaPlaybackTarget;
128 class MediaPlaybackTargetClient;
129 class MediaQueryList;
130 class MediaQueryMatcher;
131 class MouseEventWithHitTestResults;
132 class NamedFlowCollection;
136 class PlatformMouseEvent;
137 class ProcessingInstruction;
140 class RegisteredEventListener;
142 class RenderFullScreen;
143 class ScriptableDocumentParser;
144 class ScriptElementData;
146 class SecurityOrigin;
148 class SelectorQueryCache;
149 class SerializedScriptValue;
150 class SegmentedString;
154 class StyleSheetContents;
155 class StyleSheetList;
156 class SVGDocumentExtensions;
158 class TextResourceDecoder;
160 class VisitedLinkState;
161 class WebKitNamedFlow;
162 class XMLHttpRequest;
163 class XPathEvaluator;
164 class XPathExpression;
165 class XPathNSResolver;
169 class TransformSource;
172 #if ENABLE(DASHBOARD_SUPPORT)
173 struct AnnotatedRegionValue;
176 #if ENABLE(IOS_TOUCH_EVENTS)
177 #include <WebKitAdditions/DocumentIOSForward.h>
180 #if ENABLE(TOUCH_EVENTS) || ENABLE(IOS_TOUCH_EVENTS)
185 #if ENABLE(REQUEST_ANIMATION_FRAME)
186 class RequestAnimationFrameCallback;
187 class ScriptedAnimationController;
190 #if ENABLE(TEXT_AUTOSIZING)
195 class DOMSecurityPolicy;
198 #if ENABLE(FONT_LOAD_EVENTS)
202 typedef int ExceptionCode;
205 class DeviceMotionClient;
206 class DeviceMotionController;
207 class DeviceOrientationClient;
208 class DeviceOrientationController;
211 #if ENABLE(IOS_TEXT_AUTOSIZING)
212 struct TextAutoSizingHash;
213 class TextAutoSizingKey;
214 class TextAutoSizingValue;
216 struct TextAutoSizingTraits : WTF::GenericHashTraits<TextAutoSizingKey> {
217 static const bool emptyValueIsZero = true;
218 static void constructDeletedValue(TextAutoSizingKey& slot);
219 static bool isDeletedValue(const TextAutoSizingKey& value);
223 enum PageshowEventPersistence {
224 PageshowEventNotPersisted = 0,
225 PageshowEventPersisted = 1
228 enum StyleResolverUpdateFlag { RecalcStyleImmediately, DeferRecalcStyle, RecalcStyleIfNeeded, DeferRecalcStyleIfNeeded };
230 enum NodeListInvalidationType {
231 DoNotInvalidateOnAttributeChanges = 0,
232 InvalidateOnClassAttrChange,
233 InvalidateOnIdNameAttrChange,
234 InvalidateOnNameAttrChange,
235 InvalidateOnForAttrChange,
236 InvalidateForFormControls,
237 InvalidateOnHRefAttrChange,
238 InvalidateOnAnyAttrChange,
240 const int numNodeListInvalidationTypes = InvalidateOnAnyAttrChange + 1;
242 enum class EventHandlerRemoval { One, All };
243 typedef HashCountedSet<Node*> EventTargetSet;
246 DefaultDocumentClass = 0,
247 HTMLDocumentClass = 1,
248 XHTMLDocumentClass = 1 << 1,
249 ImageDocumentClass = 1 << 2,
250 PluginDocumentClass = 1 << 3,
251 MediaDocumentClass = 1 << 4,
252 SVGDocumentClass = 1 << 5,
253 TextDocumentClass = 1 << 6
256 typedef unsigned char DocumentClassFlags;
258 enum class DocumentCompatibilityMode : unsigned char {
261 LimitedQuirksMode = 1 << 2
264 enum DimensionsCheck { WidthDimensionsCheck = 1 << 0, HeightDimensionsCheck = 1 << 1, AllDimensionsCheck = 1 << 2 };
266 class Document : public ContainerNode, public TreeScope, public ScriptExecutionContext, public FontSelectorClient {
268 static Ref<Document> create(Frame* frame, const URL& url)
270 return adoptRef(*new Document(frame, url));
272 static Ref<Document> createXHTML(Frame* frame, const URL& url)
274 return adoptRef(*new Document(frame, url, XHTMLDocumentClass));
276 static Ref<Document> createNonRenderedPlaceholder(Frame* frame, const URL& url)
278 return adoptRef(*new Document(frame, url, DefaultDocumentClass, NonRenderedPlaceholder));
280 static Ref<Document> create(ScriptExecutionContext&);
284 // Nodes belonging to this document increase referencingNodeCount -
285 // these are enough to keep the document from being destroyed, but
286 // not enough to keep it from removing its children. This allows a
287 // node that outlives its document to still have a valid document
288 // pointer without introducing reference cycles.
289 void incrementReferencingNodeCount()
291 ASSERT(!m_deletionHasBegun);
292 ++m_referencingNodeCount;
295 void decrementReferencingNodeCount()
297 ASSERT(!m_deletionHasBegun || !m_referencingNodeCount);
298 --m_referencingNodeCount;
299 if (!m_referencingNodeCount && !refCount()) {
301 m_deletionHasBegun = true;
307 unsigned referencingNodeCount() const { return m_referencingNodeCount; }
309 void removedLastRef();
311 WEBCORE_EXPORT static HashSet<Document*>& allDocuments();
313 MediaQueryMatcher& mediaQueryMatcher();
315 using ContainerNode::ref;
316 using ContainerNode::deref;
318 virtual bool canContainRangeEndPoint() const override final { return true; }
320 Element* getElementByAccessKey(const String& key);
321 void invalidateAccessKeyMap();
323 void addImageElementByLowercasedUsemap(const AtomicStringImpl&, HTMLImageElement&);
324 void removeImageElementByLowercasedUsemap(const AtomicStringImpl&, HTMLImageElement&);
325 HTMLImageElement* imageElementByLowercasedUsemap(const AtomicStringImpl&) const;
327 SelectorQuery* selectorQueryForString(const String&, ExceptionCode&);
328 void clearSelectorQueryCache();
330 // DOM methods & attributes for Document
332 void setViewportArguments(const ViewportArguments& viewportArguments) { m_viewportArguments = viewportArguments; }
333 ViewportArguments viewportArguments() const { return m_viewportArguments; }
335 bool didDispatchViewportPropertiesChanged() const { return m_didDispatchViewportPropertiesChanged; }
338 void setReferrerPolicy(ReferrerPolicy referrerPolicy) { m_referrerPolicy = referrerPolicy; }
339 ReferrerPolicy referrerPolicy() const { return m_referrerPolicy; }
341 DocumentType* doctype() const;
343 DOMImplementation& implementation();
345 Element* documentElement() const
347 return m_documentElement.get();
349 static ptrdiff_t documentElementMemoryOffset() { return OBJECT_OFFSETOF(Document, m_documentElement); }
351 Element* activeElement();
352 bool hasFocus() const;
354 bool hasManifest() const;
356 virtual RefPtr<Element> createElement(const AtomicString& tagName, ExceptionCode&);
357 WEBCORE_EXPORT Ref<DocumentFragment> createDocumentFragment();
358 WEBCORE_EXPORT Ref<Text> createTextNode(const String& data);
359 Ref<Comment> createComment(const String& data);
360 RefPtr<CDATASection> createCDATASection(const String& data, ExceptionCode&);
361 RefPtr<ProcessingInstruction> createProcessingInstruction(const String& target, const String& data, ExceptionCode&);
362 RefPtr<Attr> createAttribute(const String& name, ExceptionCode&);
363 RefPtr<Attr> createAttributeNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode&, bool shouldIgnoreNamespaceChecks = false);
364 RefPtr<EntityReference> createEntityReference(const String& name, ExceptionCode&);
365 RefPtr<Node> importNode(Node* importedNode, ExceptionCode& ec) { return importNode(importedNode, true, ec); }
366 RefPtr<Node> importNode(Node* importedNode, bool deep, ExceptionCode&);
367 WEBCORE_EXPORT RefPtr<Element> createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionCode&);
368 WEBCORE_EXPORT Ref<Element> createElement(const QualifiedName&, bool createdByParser);
370 bool cssRegionsEnabled() const;
371 bool cssCompositingEnabled() const;
372 #if ENABLE(CSS_REGIONS)
373 RefPtr<DOMNamedFlowCollection> webkitGetNamedFlows();
376 NamedFlowCollection& namedFlows();
378 Element* elementFromPoint(int x, int y) { return elementFromPoint(LayoutPoint(x, y)); }
379 Element* elementFromPoint(const LayoutPoint& clientPoint);
381 RefPtr<Range> caretRangeFromPoint(int x, int y);
382 RefPtr<Range> caretRangeFromPoint(const LayoutPoint& clientPoint);
384 Element* scrollingElement();
386 String readyState() const;
388 String defaultCharset() const;
390 String inputEncoding() const { return Document::encoding(); }
391 String charset() const { return Document::encoding(); }
392 String characterSet() const { return Document::encoding(); }
394 AtomicString encoding() const;
396 void setCharset(const String&);
398 void setContent(const String&);
400 String suggestedMIMEType() const;
402 void overrideMIMEType(const String&);
403 String contentType() const;
405 String contentLanguage() const { return m_contentLanguage; }
406 void setContentLanguage(const String&);
408 String xmlEncoding() const { return m_xmlEncoding; }
409 String xmlVersion() const { return m_xmlVersion; }
410 enum StandaloneStatus { StandaloneUnspecified, Standalone, NotStandalone };
411 bool xmlStandalone() const { return m_xmlStandalone == Standalone; }
412 StandaloneStatus xmlStandaloneStatus() const { return static_cast<StandaloneStatus>(m_xmlStandalone); }
413 bool hasXMLDeclaration() const { return m_hasXMLDeclaration; }
415 void setXMLEncoding(const String& encoding) { m_xmlEncoding = encoding; } // read-only property, only to be set from XMLDocumentParser
416 void setXMLVersion(const String&, ExceptionCode&);
417 void setXMLStandalone(bool, ExceptionCode&);
418 void setHasXMLDeclaration(bool hasXMLDeclaration) { m_hasXMLDeclaration = hasXMLDeclaration ? 1 : 0; }
420 String documentURI() const { return m_documentURI; }
421 void setDocumentURI(const String&);
423 virtual URL baseURI() const override final;
425 #if ENABLE(WEB_REPLAY)
426 JSC::InputCursor& inputCursor() const { return *m_inputCursor; }
427 void setInputCursor(PassRefPtr<JSC::InputCursor>);
430 void visibilityStateChanged();
431 String visibilityState() const;
435 DOMSecurityPolicy& securityPolicy();
438 RefPtr<Node> adoptNode(PassRefPtr<Node> source, ExceptionCode&);
440 Ref<HTMLCollection> images();
441 Ref<HTMLCollection> embeds();
442 Ref<HTMLCollection> plugins(); // an alias for embeds() required for the JS DOM bindings.
443 Ref<HTMLCollection> applets();
444 Ref<HTMLCollection> links();
445 Ref<HTMLCollection> forms();
446 Ref<HTMLCollection> anchors();
447 Ref<HTMLCollection> scripts();
448 Ref<HTMLCollection> all();
450 Ref<HTMLCollection> windowNamedItems(const AtomicString& name);
451 Ref<HTMLCollection> documentNamedItems(const AtomicString& name);
453 // Other methods (not part of DOM)
454 bool isSynthesized() const { return m_isSynthesized; }
455 bool isHTMLDocument() const { return m_documentClasses & HTMLDocumentClass; }
456 bool isXHTMLDocument() const { return m_documentClasses & XHTMLDocumentClass; }
457 bool isImageDocument() const { return m_documentClasses & ImageDocumentClass; }
458 bool isSVGDocument() const { return m_documentClasses & SVGDocumentClass; }
459 bool isPluginDocument() const { return m_documentClasses & PluginDocumentClass; }
460 bool isMediaDocument() const { return m_documentClasses & MediaDocumentClass; }
461 bool isTextDocument() const { return m_documentClasses & TextDocumentClass; }
462 bool hasSVGRootNode() const;
463 virtual bool isFrameSet() const { return false; }
465 static ptrdiff_t documentClassesMemoryOffset() { return OBJECT_OFFSETOF(Document, m_documentClasses); }
466 static uint32_t isHTMLDocumentClassFlag() { return HTMLDocumentClass; }
468 bool isSrcdocDocument() const { return m_isSrcdocDocument; }
470 StyleResolver* styleResolverIfExists() const { return m_styleResolver.get(); }
472 bool sawElementsInKnownNamespaces() const { return m_sawElementsInKnownNamespaces; }
474 StyleResolver& ensureStyleResolver()
476 if (!m_styleResolver)
477 createStyleResolver();
478 return *m_styleResolver;
481 CSSFontSelector& fontSelector();
483 void notifyRemovePendingSheetIfNeeded();
485 bool haveStylesheetsLoaded() const;
487 // This is a DOM function.
488 StyleSheetList& styleSheets();
490 DocumentStyleSheetCollection& styleSheetCollection() { return m_styleSheetCollection; }
492 bool gotoAnchorNeededAfterStylesheetsLoad() { return m_gotoAnchorNeededAfterStylesheetsLoad; }
493 void setGotoAnchorNeededAfterStylesheetsLoad(bool b) { m_gotoAnchorNeededAfterStylesheetsLoad = b; }
496 * Called when one or more stylesheets in the document may have been added, removed or changed.
498 * Creates a new style resolver and assign it to this document. This is done by iterating through all nodes in
499 * document (or those before <BODY> in a HTML document), searching for stylesheets. Stylesheets can be contained in
500 * <LINK>, <STYLE> or <BODY> elements, as well as processing instructions (XML documents only). A list is
501 * constructed from these which is used to create the a new style selector which collates all of the stylesheets
502 * found and is used to calculate the derived styles for all rendering objects.
504 WEBCORE_EXPORT void styleResolverChanged(StyleResolverUpdateFlag);
506 void scheduleOptimizedStyleSheetUpdate();
508 void evaluateMediaQueryList();
510 FormController& formController();
511 Vector<String> formElementsState() const;
512 void setStateForNewFormElements(const Vector<String>&);
514 WEBCORE_EXPORT FrameView* view() const; // can be NULL
515 Frame* frame() const { return m_frame; } // can be NULL
516 WEBCORE_EXPORT Page* page() const; // can be NULL
517 WEBCORE_EXPORT Settings* settings() const; // can be NULL
519 float deviceScaleFactor() const;
521 WEBCORE_EXPORT Ref<Range> createRange();
523 RefPtr<NodeIterator> createNodeIterator(Node* root, unsigned whatToShow,
524 PassRefPtr<NodeFilter>, bool expandEntityReferences, ExceptionCode&);
526 RefPtr<TreeWalker> createTreeWalker(Node* root, unsigned whatToShow,
527 PassRefPtr<NodeFilter>, bool expandEntityReferences, ExceptionCode&);
529 // Special support for editing
530 Ref<CSSStyleDeclaration> createCSSStyleDeclaration();
531 Ref<Text> createEditingTextNode(const String&);
533 void recalcStyle(Style::Change = Style::NoChange);
534 WEBCORE_EXPORT void updateStyleIfNeeded();
535 bool needsStyleRecalc() const { return !inPageCache() && (m_pendingStyleRecalcShouldForce || childNeedsStyleRecalc() || m_optimizedStyleSheetUpdateTimer.isActive()); }
537 WEBCORE_EXPORT void updateLayout();
539 // updateLayoutIgnorePendingStylesheets() forces layout even if we are waiting for pending stylesheet loads,
540 // so calling this may cause a flash of unstyled content (FOUC).
541 enum class RunPostLayoutTasks {
545 WEBCORE_EXPORT void updateLayoutIgnorePendingStylesheets(RunPostLayoutTasks = RunPostLayoutTasks::Asynchronously);
547 Ref<RenderStyle> styleForElementIgnoringPendingStylesheets(Element*);
549 // Returns true if page box (margin boxes and page borders) is visible.
550 WEBCORE_EXPORT bool isPageBoxVisible(int pageIndex);
552 // Returns the preferred page size and margins in pixels, assuming 96
553 // pixels per inch. pageSize, marginTop, marginRight, marginBottom,
554 // marginLeft must be initialized to the default values that are used if
555 // auto is specified.
556 WEBCORE_EXPORT void pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft);
558 CachedResourceLoader& cachedResourceLoader() { return m_cachedResourceLoader; }
560 void didBecomeCurrentDocumentInFrame();
561 void destroyRenderTree();
562 void disconnectFromFrame();
563 void prepareForDestruction();
565 // Override ScriptExecutionContext methods to do additional work
566 virtual void suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension) override final;
567 virtual void resumeActiveDOMObjects(ActiveDOMObject::ReasonForSuspension) override final;
568 virtual void stopActiveDOMObjects() override final;
570 RenderView* renderView() const { return m_renderView.get(); }
572 bool renderTreeBeingDestroyed() const { return m_renderTreeBeingDestroyed; }
573 bool hasLivingRenderTree() const { return renderView() && !renderTreeBeingDestroyed(); }
575 bool updateLayoutIfDimensionsOutOfDate(Element&, DimensionsCheck = AllDimensionsCheck);
577 AXObjectCache* existingAXObjectCache() const;
578 WEBCORE_EXPORT AXObjectCache* axObjectCache() const;
579 void clearAXObjectCache();
581 // to get visually ordered hebrew and arabic pages right
582 void setVisuallyOrdered();
583 bool visuallyOrdered() const { return m_visuallyOrdered; }
585 WEBCORE_EXPORT DocumentLoader* loader() const;
587 void open(Document* ownerDocument = 0);
590 // close() is the DOM API document.close()
592 // In some situations (see the code), we ignore document.close().
593 // explicitClose() bypass these checks and actually tries to close the
595 void explicitClose();
596 // implicitClose() actually does the work of closing the input stream.
597 void implicitClose();
599 void cancelParsing();
601 void write(const SegmentedString& text, Document* ownerDocument = 0);
602 void write(const String& text, Document* ownerDocument = 0);
603 void writeln(const String& text, Document* ownerDocument = 0);
605 bool wellFormed() const { return m_wellFormed; }
607 virtual const URL& url() const override final { return m_url; }
608 void setURL(const URL&);
610 // To understand how these concepts relate to one another, please see the
611 // comments surrounding their declaration.
612 const URL& baseURL() const { return m_baseURL; }
613 void setBaseURLOverride(const URL&);
614 const URL& baseURLOverride() const { return m_baseURLOverride; }
615 const URL& baseElementURL() const { return m_baseElementURL; }
616 const String& baseTarget() const { return m_baseTarget; }
617 void processBaseElement();
619 WEBCORE_EXPORT virtual URL completeURL(const String&) const override final;
620 URL completeURL(const String&, const URL& baseURLOverride) const;
622 virtual String userAgent(const URL&) const override final;
624 virtual void disableEval(const String& errorMessage) override final;
626 bool canNavigate(Frame* targetFrame);
627 Frame* findUnsafeParentScrollPropagationBoundary();
629 CSSStyleSheet& elementSheet();
630 bool usesStyleBasedEditability() const;
632 virtual Ref<DocumentParser> createParser();
633 DocumentParser* parser() const { return m_parser.get(); }
634 ScriptableDocumentParser* scriptableDocumentParser() const;
636 bool printing() const { return m_printing; }
637 void setPrinting(bool p) { m_printing = p; }
639 bool paginatedForScreen() const { return m_paginatedForScreen; }
640 void setPaginatedForScreen(bool p) { m_paginatedForScreen = p; }
642 bool paginated() const { return printing() || paginatedForScreen(); }
644 void setCompatibilityMode(DocumentCompatibilityMode);
645 void lockCompatibilityMode() { m_compatibilityModeLocked = true; }
646 static ptrdiff_t compatibilityModeMemoryOffset() { return OBJECT_OFFSETOF(Document, m_compatibilityMode); }
648 String compatMode() const;
650 bool inQuirksMode() const { return m_compatibilityMode == DocumentCompatibilityMode::QuirksMode; }
651 bool inLimitedQuirksMode() const { return m_compatibilityMode == DocumentCompatibilityMode::LimitedQuirksMode; }
652 bool inNoQuirksMode() const { return m_compatibilityMode == DocumentCompatibilityMode::NoQuirksMode; }
659 void setReadyState(ReadyState);
660 void setParsing(bool);
661 bool parsing() const { return m_bParsing; }
662 std::chrono::milliseconds minimumLayoutDelay();
664 bool shouldScheduleLayout();
665 bool isLayoutTimerActive();
666 std::chrono::milliseconds elapsedTime() const;
668 void setTextColor(const Color& color) { m_textColor = color; }
669 Color textColor() const { return m_textColor; }
671 const Color& linkColor() const { return m_linkColor; }
672 const Color& visitedLinkColor() const { return m_visitedLinkColor; }
673 const Color& activeLinkColor() const { return m_activeLinkColor; }
674 void setLinkColor(const Color& c) { m_linkColor = c; }
675 void setVisitedLinkColor(const Color& c) { m_visitedLinkColor = c; }
676 void setActiveLinkColor(const Color& c) { m_activeLinkColor = c; }
677 void resetLinkColor();
678 void resetVisitedLinkColor();
679 void resetActiveLinkColor();
680 VisitedLinkState& visitedLinkState() const { return *m_visitedLinkState; }
682 MouseEventWithHitTestResults prepareMouseEvent(const HitTestRequest&, const LayoutPoint&, const PlatformMouseEvent&);
684 /* Newly proposed CSS3 mechanism for selecting alternate
685 stylesheets using the DOM. May be subject to change as
688 String preferredStylesheetSet() const;
689 String selectedStylesheetSet() const;
690 void setSelectedStylesheetSet(const String&);
692 WEBCORE_EXPORT bool setFocusedElement(PassRefPtr<Element>, FocusDirection = FocusDirectionNone);
693 Element* focusedElement() const { return m_focusedElement.get(); }
694 UserActionElementSet& userActionElements() { return m_userActionElements; }
695 const UserActionElementSet& userActionElements() const { return m_userActionElements; }
697 void removeFocusedNodeOfSubtree(Node*, bool amongChildrenOnly = false);
698 void hoveredElementDidDetach(Element*);
699 void elementInActiveChainDidDetach(Element*);
701 void updateHoverActiveState(const HitTestRequest&, Element*, StyleResolverUpdateFlag = RecalcStyleIfNeeded);
703 // Updates for :target (CSS3 selector).
704 void setCSSTarget(Element*);
705 Element* cssTarget() const { return m_cssTarget; }
706 static ptrdiff_t cssTargetMemoryOffset() { return OBJECT_OFFSETOF(Document, m_cssTarget); }
708 WEBCORE_EXPORT void scheduleForcedStyleRecalc();
709 void scheduleStyleRecalc();
710 void unscheduleStyleRecalc();
711 bool hasPendingStyleRecalc() const;
712 bool hasPendingForcedStyleRecalc() const;
713 void styleRecalcTimerFired();
714 void optimizedStyleSheetUpdateTimerFired();
716 void registerNodeListForInvalidation(LiveNodeList&);
717 void unregisterNodeListForInvalidation(LiveNodeList&);
718 void registerCollection(HTMLCollection&);
719 void unregisterCollection(HTMLCollection&);
720 void collectionCachedIdNameMap(const HTMLCollection&);
721 void collectionWillClearIdNameMap(const HTMLCollection&);
722 bool shouldInvalidateNodeListAndCollectionCaches(const QualifiedName* attrName = nullptr) const;
723 void invalidateNodeListAndCollectionCaches(const QualifiedName* attrName);
725 void attachNodeIterator(NodeIterator*);
726 void detachNodeIterator(NodeIterator*);
727 void moveNodeIteratorsToNewDocument(Node*, Document*);
729 void attachRange(Range*);
730 void detachRange(Range*);
732 void updateRangesAfterChildrenChanged(ContainerNode&);
733 // nodeChildrenWillBeRemoved is used when removing all node children at once.
734 void nodeChildrenWillBeRemoved(ContainerNode&);
735 // nodeWillBeRemoved is only safe when removing one node at a time.
736 void nodeWillBeRemoved(Node&);
737 bool canReplaceChild(Node* newChild, Node* oldChild);
739 void textInserted(Node*, unsigned offset, unsigned length);
740 void textRemoved(Node*, unsigned offset, unsigned length);
741 void textNodesMerged(Text* oldNode, unsigned offset);
742 void textNodeSplit(Text* oldNode);
744 void createDOMWindow();
745 void takeDOMWindowFrom(Document*);
747 DOMWindow* domWindow() const { return m_domWindow.get(); }
748 // In DOM Level 2, the Document's DOMWindow is called the defaultView.
749 DOMWindow* defaultView() const { return domWindow(); }
751 // Helper functions for forwarding DOMWindow event related tasks to the DOMWindow if it exists.
752 void setWindowAttributeEventListener(const AtomicString& eventType, const QualifiedName& attributeName, const AtomicString& value);
753 void setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener>);
754 EventListener* getWindowAttributeEventListener(const AtomicString& eventType);
755 WEBCORE_EXPORT void dispatchWindowEvent(PassRefPtr<Event>, PassRefPtr<EventTarget> = 0);
756 void dispatchWindowLoadEvent();
758 RefPtr<Event> createEvent(const String& eventType, ExceptionCode&);
760 // keep track of what types of event listeners are registered, so we don't
761 // dispatch events unnecessarily
763 DOMSUBTREEMODIFIED_LISTENER = 1,
764 DOMNODEINSERTED_LISTENER = 1 << 1,
765 DOMNODEREMOVED_LISTENER = 1 << 2,
766 DOMNODEREMOVEDFROMDOCUMENT_LISTENER = 1 << 3,
767 DOMNODEINSERTEDINTODOCUMENT_LISTENER = 1 << 4,
768 DOMCHARACTERDATAMODIFIED_LISTENER = 1 << 5,
769 OVERFLOWCHANGED_LISTENER = 1 << 6,
770 ANIMATIONEND_LISTENER = 1 << 7,
771 ANIMATIONSTART_LISTENER = 1 << 8,
772 ANIMATIONITERATION_LISTENER = 1 << 9,
773 TRANSITIONEND_LISTENER = 1 << 10,
774 BEFORELOAD_LISTENER = 1 << 11,
775 SCROLL_LISTENER = 1 << 12,
776 FORCEWILLBEGIN_LISTENER = 1 << 13,
777 FORCECHANGED_LISTENER = 1 << 14,
778 FORCEDOWN_LISTENER = 1 << 15,
779 FORCEUP_LISTENER = 1 << 16
782 bool hasListenerType(ListenerType listenerType) const { return (m_listenerTypes & listenerType); }
783 bool hasListenerTypeForEventType(PlatformEvent::Type) const;
784 void addListenerTypeIfNeeded(const AtomicString& eventType);
786 bool hasMutationObserversOfType(MutationObserver::MutationType type) const
788 return m_mutationObserverTypes & type;
790 bool hasMutationObservers() const { return m_mutationObserverTypes; }
791 void addMutationObserverTypes(MutationObserverOptions types) { m_mutationObserverTypes |= types; }
793 CSSStyleDeclaration* getOverrideStyle(Element*, const String& pseudoElt);
796 * Handles a HTTP header equivalent set by a meta tag using <meta http-equiv="..." content="...">. This is called
797 * when a meta tag is encountered during document parsing, and also when a script dynamically changes or adds a meta
798 * tag. This enables scripts to use meta tags to perform refreshes and set expiry dates in addition to them being
799 * specified in a HTML file.
801 * @param equiv The http header name (value of the meta tag's "equiv" attribute)
802 * @param content The header value (value of the meta tag's "content" attribute)
804 void processHttpEquiv(const String& equiv, const String& content);
807 void processFormatDetection(const String&);
809 // Called when <meta name="apple-mobile-web-app-orientations"> changes.
810 void processWebAppOrientations();
813 void processViewport(const String& features, ViewportArguments::Type origin);
814 void updateViewportArguments();
815 void processReferrerPolicy(const String& policy);
817 // Returns the owning element in the parent document.
818 // Returns 0 if this is the top level document.
819 HTMLFrameOwnerElement* ownerElement() const;
821 // Used by DOM bindings; no direction known.
822 String title() const { return m_title.string(); }
823 void setTitle(const String&);
825 void setTitleElement(const StringWithDirection&, Element* titleElement);
826 void removeTitle(Element* titleElement);
828 String cookie(ExceptionCode&);
829 void setCookie(const String&, ExceptionCode&);
831 String referrer() const;
833 String origin() const;
835 WEBCORE_EXPORT String domain() const;
836 void setDomain(const String& newDomain, ExceptionCode&);
838 String lastModified() const;
840 // The cookieURL is used to query the cookie database for this document's
841 // cookies. For example, if the cookie URL is http://example.com, we'll
842 // use the non-Secure cookies for example.com when computing
845 // Q: How is the cookieURL different from the document's URL?
846 // A: The two URLs are the same almost all the time. However, if one
847 // document inherits the security context of another document, it
848 // inherits its cookieURL but not its URL.
850 const URL& cookieURL() const { return m_cookieURL; }
851 void setCookieURL(const URL&);
853 // The firstPartyForCookies is used to compute whether this document
854 // appears in a "third-party" context for the purpose of third-party
855 // cookie blocking. The document is in a third-party context if the
856 // cookieURL and the firstPartyForCookies are from different hosts.
858 // Note: Some ports (including possibly Apple's) only consider the
859 // document in a third-party context if the cookieURL and the
860 // firstPartyForCookies have a different registry-controlled
863 const URL& firstPartyForCookies() const { return m_firstPartyForCookies; }
864 void setFirstPartyForCookies(const URL& url) { m_firstPartyForCookies = url; }
866 // The following implements the rule from HTML 4 for what valid names are.
867 // To get this right for all the XML cases, we probably have to improve this or move it
868 // and make it sensitive to the type of document.
869 static bool isValidName(const String&);
871 // The following breaks a qualified name into a prefix and a local name.
872 // It also does a validity check, and returns false if the qualified name
873 // is invalid. It also sets ExceptionCode when name is invalid.
874 static bool parseQualifiedName(const String& qualifiedName, String& prefix, String& localName, ExceptionCode&);
876 // Checks to make sure prefix and namespace do not conflict (per DOM Core 3)
877 static bool hasValidNamespaceForElements(const QualifiedName&);
878 static bool hasValidNamespaceForAttributes(const QualifiedName&);
880 HTMLBodyElement* body() const;
881 WEBCORE_EXPORT HTMLElement* bodyOrFrameset() const;
882 void setBodyOrFrameset(PassRefPtr<HTMLElement>, ExceptionCode&);
884 WEBCORE_EXPORT HTMLHeadElement* head();
886 DocumentMarkerController& markers() const { return *m_markers; }
888 bool directionSetOnDocumentElement() const { return m_directionSetOnDocumentElement; }
889 bool writingModeSetOnDocumentElement() const { return m_writingModeSetOnDocumentElement; }
890 void setDirectionSetOnDocumentElement(bool b) { m_directionSetOnDocumentElement = b; }
891 void setWritingModeSetOnDocumentElement(bool b) { m_writingModeSetOnDocumentElement = b; }
893 bool execCommand(const String& command, bool userInterface = false, const String& value = String());
894 bool queryCommandEnabled(const String& command);
895 bool queryCommandIndeterm(const String& command);
896 bool queryCommandState(const String& command);
897 bool queryCommandSupported(const String& command);
898 String queryCommandValue(const String& command);
900 // designMode support
901 enum InheritedBool { off = false, on = true, inherit };
902 void setDesignMode(InheritedBool value);
903 InheritedBool getDesignMode() const;
904 bool inDesignMode() const;
906 Document* parentDocument() const;
907 Document& topDocument() const;
909 ScriptRunner* scriptRunner() { return m_scriptRunner.get(); }
911 HTMLScriptElement* currentScript() const { return !m_currentScriptStack.isEmpty() ? m_currentScriptStack.last().get() : 0; }
912 void pushCurrentScript(PassRefPtr<HTMLScriptElement>);
913 void popCurrentScript();
916 void applyXSLTransform(ProcessingInstruction* pi);
917 RefPtr<Document> transformSourceDocument() { return m_transformSourceDocument; }
918 void setTransformSourceDocument(Document* doc) { m_transformSourceDocument = doc; }
920 void setTransformSource(std::unique_ptr<TransformSource>);
921 TransformSource* transformSource() const { return m_transformSource.get(); }
924 void incDOMTreeVersion() { m_domTreeVersion = ++s_globalTreeVersion; }
925 uint64_t domTreeVersion() const { return m_domTreeVersion; }
927 // XPathEvaluator methods
928 RefPtr<XPathExpression> createExpression(const String& expression, XPathNSResolver*, ExceptionCode&);
929 RefPtr<XPathNSResolver> createNSResolver(Node* nodeResolver);
930 RefPtr<XPathResult> evaluate(const String& expression, Node* contextNode, XPathNSResolver*, unsigned short type, XPathResult*, ExceptionCode&);
932 enum PendingSheetLayout { NoLayoutWithPendingSheets, DidLayoutWithPendingSheets, IgnoreLayoutWithPendingSheets };
934 bool didLayoutWithPendingStylesheets() const { return m_pendingSheetLayout == DidLayoutWithPendingSheets; }
936 bool hasNodesWithPlaceholderStyle() const { return m_hasNodesWithPlaceholderStyle; }
937 void setHasNodesWithPlaceholderStyle() { m_hasNodesWithPlaceholderStyle = true; }
939 void updateFocusAppearanceSoon(bool restorePreviousSelection);
940 void cancelFocusAppearanceUpdate();
942 // Extension for manipulating canvas drawing contexts for use in CSS
943 CanvasRenderingContext* getCSSCanvasContext(const String& type, const String& name, int width, int height);
944 HTMLCanvasElement* getCSSCanvasElement(const String& name);
946 bool isDNSPrefetchEnabled() const { return m_isDNSPrefetchEnabled; }
947 void parseDNSPrefetchControlHeader(const String&);
949 virtual void postTask(Task) override final; // Executes the task on context's thread asynchronously.
951 void suspendScriptedAnimationControllerCallbacks();
952 void resumeScriptedAnimationControllerCallbacks();
953 void scriptedAnimationControllerSetThrottled(bool);
955 void windowScreenDidChange(PlatformDisplayID);
957 void finishedParsing();
959 bool inPageCache() const { return m_inPageCache; }
960 void setInPageCache(bool flag);
962 // Elements can register themselves for the "documentWillSuspendForPageCache()" and
963 // "documentDidResumeFromPageCache()" callbacks
964 void registerForPageCacheSuspensionCallbacks(Element*);
965 void unregisterForPageCacheSuspensionCallbacks(Element*);
967 void documentWillBecomeInactive();
968 void documentWillSuspendForPageCache();
969 void documentDidResumeFromPageCache();
971 void registerForMediaVolumeCallbacks(Element*);
972 void unregisterForMediaVolumeCallbacks(Element*);
973 void mediaVolumeDidChange();
975 void registerForPrivateBrowsingStateChangedCallbacks(Element*);
976 void unregisterForPrivateBrowsingStateChangedCallbacks(Element*);
977 void storageBlockingStateDidChange();
978 void privateBrowsingStateDidChange();
980 #if ENABLE(VIDEO_TRACK)
981 void registerForCaptionPreferencesChangedCallbacks(Element*);
982 void unregisterForCaptionPreferencesChangedCallbacks(Element*);
983 void captionPreferencesChanged();
986 #if ENABLE(MEDIA_CONTROLS_SCRIPT)
987 void registerForPageScaleFactorChangedCallbacks(HTMLMediaElement*);
988 void unregisterForPageScaleFactorChangedCallbacks(HTMLMediaElement*);
989 void pageScaleFactorChangedAndStable();
992 void registerForVisibilityStateChangedCallbacks(Element*);
993 void unregisterForVisibilityStateChangedCallbacks(Element*);
995 WEBCORE_EXPORT void setShouldCreateRenderers(bool);
996 bool shouldCreateRenderers();
998 void setDecoder(PassRefPtr<TextResourceDecoder>);
999 TextResourceDecoder* decoder() const { return m_decoder.get(); }
1001 WEBCORE_EXPORT String displayStringModifiedByEncoding(const String&) const;
1002 RefPtr<StringImpl> displayStringModifiedByEncoding(PassRefPtr<StringImpl>) const;
1003 void displayBufferModifiedByEncoding(LChar* buffer, unsigned len) const
1005 displayBufferModifiedByEncodingInternal(buffer, len);
1007 void displayBufferModifiedByEncoding(UChar* buffer, unsigned len) const
1009 displayBufferModifiedByEncodingInternal(buffer, len);
1012 // Quirk for the benefit of Apple's Dictionary application.
1013 void setFrameElementsShouldIgnoreScrolling(bool ignore) { m_frameElementsShouldIgnoreScrolling = ignore; }
1014 bool frameElementsShouldIgnoreScrolling() const { return m_frameElementsShouldIgnoreScrolling; }
1016 #if ENABLE(DASHBOARD_SUPPORT)
1017 void setAnnotatedRegionsDirty(bool f) { m_annotatedRegionsDirty = f; }
1018 bool annotatedRegionsDirty() const { return m_annotatedRegionsDirty; }
1019 bool hasAnnotatedRegions () const { return m_hasAnnotatedRegions; }
1020 void setHasAnnotatedRegions(bool f) { m_hasAnnotatedRegions = f; }
1021 WEBCORE_EXPORT const Vector<AnnotatedRegionValue>& annotatedRegions() const;
1022 void setAnnotatedRegions(const Vector<AnnotatedRegionValue>&);
1025 virtual void removeAllEventListeners() override final;
1027 WEBCORE_EXPORT const SVGDocumentExtensions* svgExtensions();
1028 WEBCORE_EXPORT SVGDocumentExtensions& accessSVGExtensions();
1030 void initSecurityContext();
1031 void initContentSecurityPolicy();
1033 void updateURLForPushOrReplaceState(const URL&);
1034 void statePopped(PassRefPtr<SerializedScriptValue>);
1036 bool processingLoadEvent() const { return m_processingLoadEvent; }
1037 bool loadEventFinished() const { return m_loadEventFinished; }
1039 virtual bool isContextThread() const override final;
1040 virtual bool isJSExecutionForbidden() const override final { return false; }
1042 void enqueueWindowEvent(PassRefPtr<Event>);
1043 void enqueueDocumentEvent(PassRefPtr<Event>);
1044 void enqueueOverflowEvent(PassRefPtr<Event>);
1045 void enqueuePageshowEvent(PageshowEventPersistence);
1046 void enqueueHashchangeEvent(const String& oldURL, const String& newURL);
1047 void enqueuePopstateEvent(PassRefPtr<SerializedScriptValue> stateObject);
1048 virtual DocumentEventQueue& eventQueue() const override final { return m_eventQueue; }
1050 WEBCORE_EXPORT void addMediaCanStartListener(MediaCanStartListener*);
1051 WEBCORE_EXPORT void removeMediaCanStartListener(MediaCanStartListener*);
1052 MediaCanStartListener* takeAnyMediaCanStartListener();
1054 #if ENABLE(FULLSCREEN_API)
1055 bool webkitIsFullScreen() const { return m_fullScreenElement.get(); }
1056 bool webkitFullScreenKeyboardInputAllowed() const { return m_fullScreenElement.get() && m_areKeysEnabledInFullScreen; }
1057 Element* webkitCurrentFullScreenElement() const { return m_fullScreenElement.get(); }
1059 enum FullScreenCheckType {
1060 EnforceIFrameAllowFullScreenRequirement,
1061 ExemptIFrameAllowFullScreenRequirement,
1064 void requestFullScreenForElement(Element*, unsigned short flags, FullScreenCheckType);
1065 WEBCORE_EXPORT void webkitCancelFullScreen();
1067 WEBCORE_EXPORT void webkitWillEnterFullScreenForElement(Element*);
1068 WEBCORE_EXPORT void webkitDidEnterFullScreenForElement(Element*);
1069 WEBCORE_EXPORT void webkitWillExitFullScreenForElement(Element*);
1070 WEBCORE_EXPORT void webkitDidExitFullScreenForElement(Element*);
1072 void setFullScreenRenderer(RenderFullScreen*);
1073 RenderFullScreen* fullScreenRenderer() const { return m_fullScreenRenderer; }
1074 void fullScreenRendererDestroyed();
1076 void fullScreenChangeDelayTimerFired();
1077 bool fullScreenIsAllowedForElement(Element*) const;
1078 void fullScreenElementRemoved();
1079 void removeFullScreenElementOfSubtree(Node*, bool amongChildrenOnly = false);
1080 bool isAnimatingFullScreen() const;
1081 WEBCORE_EXPORT void setAnimatingFullScreen(bool);
1084 bool webkitFullscreenEnabled() const;
1085 Element* webkitFullscreenElement() const { return !m_fullScreenElementStack.isEmpty() ? m_fullScreenElementStack.last().get() : 0; }
1086 void webkitExitFullscreen();
1089 #if ENABLE(POINTER_LOCK)
1090 void exitPointerLock();
1091 Element* pointerLockElement() const;
1094 // Used to allow element that loads data without going through a FrameLoader to delay the 'load' event.
1095 void incrementLoadEventDelayCount() { ++m_loadEventDelayCount; }
1096 void decrementLoadEventDelayCount();
1097 bool isDelayingLoadEvent() const { return m_loadEventDelayCount; }
1099 #if ENABLE(IOS_TOUCH_EVENTS)
1100 #include <WebKitAdditions/DocumentIOS.h>
1101 #elif ENABLE(TOUCH_EVENTS)
1102 RefPtr<Touch> createTouch(DOMWindow*, EventTarget*, int identifier, int pageX, int pageY, int screenX, int screenY, int radiusX, int radiusY, float rotationAngle, float force, ExceptionCode&) const;
1105 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
1106 DeviceMotionController* deviceMotionController() const;
1107 DeviceOrientationController* deviceOrientationController() const;
1110 #if ENABLE(WEB_TIMING)
1111 const DocumentTiming& timing() const { return m_documentTiming; }
1114 #if ENABLE(REQUEST_ANIMATION_FRAME)
1115 int requestAnimationFrame(PassRefPtr<RequestAnimationFrameCallback>);
1116 void cancelAnimationFrame(int id);
1117 void serviceScriptedAnimations(double monotonicAnimationStartTime);
1120 void sendWillRevealEdgeEventsIfNeeded(const IntPoint& oldPosition, const IntPoint& newPosition, const IntRect& visibleRect, const IntSize& contentsSize, Element* target = nullptr);
1122 virtual EventTarget* errorEventTarget() override final;
1123 virtual void logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, RefPtr<Inspector::ScriptCallStack>&&) override final;
1125 void initDNSPrefetch();
1127 void didAddWheelEventHandler(Node&);
1128 void didRemoveWheelEventHandler(Node&, EventHandlerRemoval = EventHandlerRemoval::One);
1130 double lastHandledUserGestureTimestamp() const { return m_lastHandledUserGestureTimestamp; }
1131 void updateLastHandledUserGestureTimestamp();
1133 #if ENABLE(TOUCH_EVENTS)
1134 bool hasTouchEventHandlers() const { return (m_touchEventTargets.get()) ? m_touchEventTargets->size() : false; }
1136 bool hasTouchEventHandlers() const { return false; }
1139 // Used for testing. Count handlers in the main document, and one per frame which contains handlers.
1140 WEBCORE_EXPORT unsigned wheelEventHandlerCount() const;
1141 WEBCORE_EXPORT unsigned touchEventHandlerCount() const;
1143 WEBCORE_EXPORT void startTrackingStyleRecalcs();
1144 WEBCORE_EXPORT unsigned styleRecalcCount() const;
1146 void didAddTouchEventHandler(Node&);
1147 void didRemoveTouchEventHandler(Node&, EventHandlerRemoval = EventHandlerRemoval::One);
1149 void didRemoveEventTargetNode(Node&);
1151 const EventTargetSet* touchEventTargets() const
1153 #if ENABLE(TOUCH_EVENTS)
1154 return m_touchEventTargets.get();
1160 const EventTargetSet* wheelEventTargets() const { return m_wheelEventTargets.get(); }
1162 typedef std::pair<Region, bool> RegionFixedPair;
1163 RegionFixedPair absoluteRegionForEventTargets(const EventTargetSet*);
1165 LayoutRect absoluteEventHandlerBounds(bool&) override final;
1167 bool visualUpdatesAllowed() const { return m_visualUpdatesAllowed; }
1169 bool isInDocumentWrite() { return m_writeRecursionDepth > 0; }
1171 void suspendScheduledTasks(ActiveDOMObject::ReasonForSuspension);
1172 void resumeScheduledTasks(ActiveDOMObject::ReasonForSuspension);
1174 #if ENABLE(CSS_DEVICE_ADAPTATION)
1175 IntSize initialViewportSize() const;
1178 #if ENABLE(TEXT_AUTOSIZING)
1179 TextAutosizer* textAutosizer() { return m_textAutosizer.get(); }
1182 void adjustFloatQuadsForScrollAndAbsoluteZoomAndFrameScale(Vector<FloatQuad>&, const RenderStyle&);
1183 void adjustFloatRectForScrollAndAbsoluteZoomAndFrameScale(FloatRect&, const RenderStyle&);
1185 bool hasActiveParser();
1186 void incrementActiveParserCount() { ++m_activeParserCount; }
1187 void decrementActiveParserCount();
1189 DocumentSharedObjectPool* sharedObjectPool() { return m_sharedObjectPool.get(); }
1191 void didRemoveAllPendingStylesheet();
1192 void setNeedsNotifyRemoveAllPendingStylesheet() { m_needsNotifyRemoveAllPendingStylesheet = true; }
1193 void clearStyleResolver();
1195 bool inStyleRecalc() { return m_inStyleRecalc; }
1197 // Return a Locale for the default locale if the argument is null or empty.
1198 Locale& getCachedLocale(const AtomicString& locale = nullAtom);
1200 #if ENABLE(TEMPLATE_ELEMENT)
1201 const Document* templateDocument() const;
1202 Document& ensureTemplateDocument();
1203 void setTemplateDocumentHost(Document* templateDocumentHost) { m_templateDocumentHost = templateDocumentHost; }
1204 Document* templateDocumentHost() { return m_templateDocumentHost; }
1207 void didAssociateFormControl(Element*);
1208 bool hasDisabledFieldsetElement() const { return m_disabledFieldsetElementsCount; }
1209 void addDisabledFieldsetElement() { m_disabledFieldsetElementsCount++; }
1210 void removeDisabledFieldsetElement() { ASSERT(m_disabledFieldsetElementsCount); m_disabledFieldsetElementsCount--; }
1212 WEBCORE_EXPORT virtual void addConsoleMessage(MessageSource, MessageLevel, const String& message, unsigned long requestIdentifier = 0) override final;
1214 WEBCORE_EXPORT virtual SecurityOrigin* topOrigin() const override final;
1216 #if ENABLE(FONT_LOAD_EVENTS)
1217 RefPtr<FontLoader> fonts();
1220 void ensurePlugInsInjectedScript(DOMWrapperWorld&);
1222 void setVisualUpdatesAllowedByClient(bool);
1224 #if ENABLE(SUBTLE_CRYPTO)
1225 virtual bool wrapCryptoKey(const Vector<uint8_t>& key, Vector<uint8_t>& wrappedKey) override final;
1226 virtual bool unwrapCryptoKey(const Vector<uint8_t>& wrappedKey, Vector<uint8_t>& key) override final;
1229 void setHasStyleWithViewportUnits() { m_hasStyleWithViewportUnits = true; }
1230 bool hasStyleWithViewportUnits() const { return m_hasStyleWithViewportUnits; }
1231 void updateViewportUnitsOnResize();
1233 WEBCORE_EXPORT void addAudioProducer(MediaProducer*);
1234 WEBCORE_EXPORT void removeAudioProducer(MediaProducer*);
1235 MediaProducer::MediaStateFlags mediaState() const { return m_mediaState; }
1236 WEBCORE_EXPORT void updateIsPlayingMedia();
1237 void pageMutedStateDidChange();
1238 WeakPtr<Document> createWeakPtr() { return m_weakFactory.createWeakPtr(); }
1240 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
1241 void addPlaybackTargetPickerClient(MediaPlaybackTargetClient&);
1242 void removePlaybackTargetPickerClient(MediaPlaybackTargetClient&);
1243 void showPlaybackTargetPicker(MediaPlaybackTargetClient&, bool);
1244 void playbackTargetPickerClientStateDidChange(MediaPlaybackTargetClient&, MediaProducer::MediaStateFlags);
1246 void setPlaybackTarget(uint64_t, Ref<MediaPlaybackTarget>&&);
1247 void playbackTargetAvailabilityDidChange(uint64_t, bool);
1248 void setShouldPlayToPlaybackTarget(uint64_t, bool);
1252 enum ConstructionFlags { Synthesized = 1, NonRenderedPlaceholder = 1 << 1 };
1253 Document(Frame*, const URL&, unsigned = DefaultDocumentClass, unsigned constructionFlags = 0);
1255 void clearXMLVersion() { m_xmlVersion = String(); }
1257 virtual Ref<Document> cloneDocumentWithoutChildren() const;
1261 friend class IgnoreDestructiveWriteCountIncrementer;
1263 void commonTeardown();
1265 RenderObject* renderer() const = delete;
1266 void setRenderer(RenderObject*) = delete;
1268 void createRenderTree();
1269 void detachParser();
1271 typedef void (*ArgumentsCallback)(const String& keyString, const String& valueString, Document*, void* data);
1272 void processArguments(const String& features, void* data, ArgumentsCallback);
1274 // FontSelectorClient
1275 virtual void fontsNeedUpdate(FontSelector*) override final;
1277 virtual bool isDocument() const override final { return true; }
1279 virtual void childrenChanged(const ChildChange&) override final;
1281 virtual String nodeName() const override final;
1282 virtual NodeType nodeType() const override final;
1283 virtual bool childTypeAllowed(NodeType) const override final;
1284 virtual RefPtr<Node> cloneNodeInternal(Document&, CloningOperation) override final;
1285 void cloneDataFromDocument(const Document&);
1287 virtual void refScriptExecutionContext() override final { ref(); }
1288 virtual void derefScriptExecutionContext() override final { deref(); }
1290 virtual void addMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, unsigned columnNumber, RefPtr<Inspector::ScriptCallStack>&&, JSC::ExecState* = 0, unsigned long requestIdentifier = 0) override final;
1292 virtual double minimumTimerInterval() const override final;
1294 virtual double timerAlignmentInterval() const override final;
1296 void updateTitle(const StringWithDirection&);
1297 void updateFocusAppearanceTimerFired();
1298 void updateBaseURL();
1300 void buildAccessKeyMap(TreeScope* root);
1302 void createStyleResolver();
1304 void loadEventDelayTimerFired();
1306 void pendingTasksTimerFired();
1308 template <typename CharacterType>
1309 void displayBufferModifiedByEncodingInternal(CharacterType*, unsigned) const;
1311 PageVisibilityState pageVisibilityState() const;
1313 Node* nodeFromPoint(const LayoutPoint& clientPoint, LayoutPoint* localPoint = nullptr);
1315 Ref<HTMLCollection> ensureCachedCollection(CollectionType);
1317 #if ENABLE(FULLSCREEN_API)
1318 void dispatchFullScreenChangeOrErrorEvent(Deque<RefPtr<Node>>&, const AtomicString& eventName, bool shouldNotifyMediaElement);
1319 void clearFullscreenElementStack();
1320 void popFullscreenElementStack();
1321 void pushFullscreenElementStack(Element*);
1322 void addDocumentToFullScreenChangeEventQueue(Document*);
1325 void setVisualUpdatesAllowed(ReadyState);
1326 void setVisualUpdatesAllowed(bool);
1327 void visualUpdatesSuppressionTimerFired();
1329 void addListenerType(ListenerType listenerType) { m_listenerTypes |= listenerType; }
1331 void didAssociateFormControlsTimerFired();
1333 void wheelEventHandlersChanged();
1335 // DOM Cookies caching.
1336 const String& cachedDOMCookies() const { return m_cachedDOMCookies; }
1337 void setCachedDOMCookies(const String&);
1338 bool isDOMCookieCacheValid() const { return m_cookieCacheExpiryTimer.isActive(); }
1339 void invalidateDOMCookieCache();
1340 void domCookieCacheExpiryTimerFired();
1341 virtual void didLoadResourceSynchronously(const ResourceRequest&) override final;
1343 unsigned m_referencingNodeCount;
1345 std::unique_ptr<StyleResolver> m_styleResolver;
1346 bool m_didCalculateStyleResolver;
1347 bool m_hasNodesWithPlaceholderStyle;
1348 bool m_needsNotifyRemoveAllPendingStylesheet;
1349 // But sometimes you need to ignore pending stylesheet count to
1350 // force an immediate layout when requested by JS.
1351 bool m_ignorePendingStylesheets;
1353 // If we do ignore the pending stylesheet count, then we need to add a boolean
1354 // to track that this happened so that we can do a full repaint when the stylesheets
1355 // do eventually load.
1356 PendingSheetLayout m_pendingSheetLayout;
1359 RefPtr<DOMWindow> m_domWindow;
1361 Ref<CachedResourceLoader> m_cachedResourceLoader;
1362 RefPtr<DocumentParser> m_parser;
1363 unsigned m_activeParserCount;
1368 URL m_url; // Document.URL: The URL from which this document was retrieved.
1369 URL m_baseURL; // Node.baseURI: The URL to use when resolving relative URLs.
1370 URL m_baseURLOverride; // An alternative base URL that takes precedence over m_baseURL (but not m_baseElementURL).
1371 URL m_baseElementURL; // The URL set by the <base> element.
1372 URL m_cookieURL; // The URL to use for cookie access.
1373 URL m_firstPartyForCookies; // The policy URL for third-party cookie blocking.
1375 // Document.documentURI:
1376 // Although URL-like, Document.documentURI can actually be set to any
1377 // string by content. Document.documentURI affects m_baseURL unless the
1378 // document contains a <base> element, in which case the <base> element
1379 // takes precedence.
1381 // This property is read-only from JavaScript, but writable from Objective C.
1382 String m_documentURI;
1384 String m_baseTarget;
1386 // MIME type of the document in case it was cloned or created by XHR.
1387 String m_overriddenMIMEType;
1389 std::unique_ptr<DOMImplementation> m_implementation;
1391 RefPtr<CSSStyleSheet> m_elementSheet;
1394 bool m_paginatedForScreen;
1396 DocumentCompatibilityMode m_compatibilityMode;
1397 bool m_compatibilityModeLocked; // This is cheaper than making setCompatibilityMode virtual.
1401 RefPtr<Element> m_focusedElement;
1402 RefPtr<Element> m_hoveredElement;
1403 RefPtr<Element> m_activeElement;
1404 RefPtr<Element> m_documentElement;
1405 UserActionElementSet m_userActionElements;
1407 uint64_t m_domTreeVersion;
1408 static uint64_t s_globalTreeVersion;
1410 HashSet<NodeIterator*> m_nodeIterators;
1411 HashSet<Range*> m_ranges;
1413 unsigned m_listenerTypes;
1415 MutationObserverOptions m_mutationObserverTypes;
1417 DocumentStyleSheetCollection m_styleSheetCollection;
1418 RefPtr<StyleSheetList> m_styleSheetList;
1420 std::unique_ptr<FormController> m_formController;
1423 Color m_visitedLinkColor;
1424 Color m_activeLinkColor;
1425 const std::unique_ptr<VisitedLinkState> m_visitedLinkState;
1427 bool m_visuallyOrdered;
1428 ReadyState m_readyState;
1431 Timer m_optimizedStyleSheetUpdateTimer;
1432 Timer m_styleRecalcTimer;
1433 bool m_pendingStyleRecalcShouldForce;
1434 bool m_inStyleRecalc;
1435 bool m_closeAfterStyleRecalc;
1437 bool m_gotoAnchorNeededAfterStylesheetsLoad;
1438 bool m_isDNSPrefetchEnabled;
1439 bool m_haveExplicitlyDisabledDNSPrefetch;
1440 bool m_frameElementsShouldIgnoreScrolling;
1441 bool m_updateFocusAppearanceRestoresSelection;
1443 // http://www.whatwg.org/specs/web-apps/current-work/#ignore-destructive-writes-counter
1444 unsigned m_ignoreDestructiveWriteCount;
1446 unsigned m_styleRecalcCount { 0 };
1448 StringWithDirection m_title;
1449 StringWithDirection m_rawTitle;
1450 bool m_titleSetExplicitly;
1451 RefPtr<Element> m_titleElement;
1453 std::unique_ptr<AXObjectCache> m_axObjectCache;
1454 const std::unique_ptr<DocumentMarkerController> m_markers;
1456 Timer m_updateFocusAppearanceTimer;
1458 Element* m_cssTarget;
1460 // FIXME: Merge these 2 variables into an enum. Also, FrameLoader::m_didCallImplicitClose
1461 // is almost a duplication of this data, so that should probably get merged in too.
1462 // FIXME: Document::m_processingLoadEvent and DocumentLoader::m_wasOnloadHandled are roughly the same
1463 // and should be merged.
1464 bool m_processingLoadEvent;
1465 bool m_loadEventFinished;
1467 RefPtr<SerializedScriptValue> m_pendingStateObject;
1468 std::chrono::steady_clock::time_point m_startTime;
1469 bool m_overMinimumLayoutThreshold;
1471 std::unique_ptr<ScriptRunner> m_scriptRunner;
1473 Vector<RefPtr<HTMLScriptElement>> m_currentScriptStack;
1476 std::unique_ptr<TransformSource> m_transformSource;
1477 RefPtr<Document> m_transformSourceDocument;
1480 String m_xmlEncoding;
1481 String m_xmlVersion;
1482 unsigned m_xmlStandalone : 2;
1483 unsigned m_hasXMLDeclaration : 1;
1485 String m_contentLanguage;
1487 RefPtr<TextResourceDecoder> m_decoder;
1489 InheritedBool m_designMode;
1491 HashSet<LiveNodeList*> m_listsInvalidatedAtDocument;
1492 HashSet<HTMLCollection*> m_collectionsInvalidatedAtDocument;
1493 #if !ASSERT_DISABLED
1494 bool m_inInvalidateNodeListAndCollectionCaches;
1497 unsigned m_nodeListAndCollectionCounts[numNodeListInvalidationTypes];
1499 RefPtr<XPathEvaluator> m_xpathEvaluator;
1501 std::unique_ptr<SVGDocumentExtensions> m_svgExtensions;
1503 #if ENABLE(DASHBOARD_SUPPORT)
1504 Vector<AnnotatedRegionValue> m_annotatedRegions;
1505 bool m_hasAnnotatedRegions;
1506 bool m_annotatedRegionsDirty;
1509 HashMap<String, RefPtr<HTMLCanvasElement>> m_cssCanvasElements;
1511 bool m_createRenderers;
1514 HashSet<Element*> m_documentSuspensionCallbackElements;
1515 HashSet<Element*> m_mediaVolumeCallbackElements;
1516 HashSet<Element*> m_privateBrowsingStateChangedElements;
1517 #if ENABLE(VIDEO_TRACK)
1518 HashSet<Element*> m_captionPreferencesChangedElements;
1521 #if ENABLE(MEDIA_CONTROLS_SCRIPT)
1522 HashSet<HTMLMediaElement*> m_pageScaleFactorChangedElements;
1525 HashSet<Element*> m_visibilityStateCallbackElements;
1527 HashMap<StringImpl*, Element*, CaseFoldingHash> m_elementsByAccessKey;
1528 bool m_accessKeyMapValid;
1530 DocumentOrderedMap m_imagesByUsemap;
1532 std::unique_ptr<SelectorQueryCache> m_selectorQueryCache;
1534 DocumentClassFlags m_documentClasses;
1536 bool m_isSynthesized;
1537 bool m_isNonRenderedPlaceholder;
1539 bool m_sawElementsInKnownNamespaces;
1540 bool m_isSrcdocDocument;
1542 RenderPtr<RenderView> m_renderView;
1543 mutable DocumentEventQueue m_eventQueue;
1545 WeakPtrFactory<Document> m_weakFactory;
1547 HashSet<MediaCanStartListener*> m_mediaCanStartListeners;
1549 #if ENABLE(FULLSCREEN_API)
1550 bool m_areKeysEnabledInFullScreen;
1551 RefPtr<Element> m_fullScreenElement;
1552 Vector<RefPtr<Element>> m_fullScreenElementStack;
1553 RenderFullScreen* m_fullScreenRenderer;
1554 Timer m_fullScreenChangeDelayTimer;
1555 Deque<RefPtr<Node>> m_fullScreenChangeEventTargetQueue;
1556 Deque<RefPtr<Node>> m_fullScreenErrorEventTargetQueue;
1557 bool m_isAnimatingFullScreen;
1558 LayoutRect m_savedPlaceholderFrameRect;
1559 RefPtr<RenderStyle> m_savedPlaceholderRenderStyle;
1562 int m_loadEventDelayCount;
1563 Timer m_loadEventDelayTimer;
1565 ViewportArguments m_viewportArguments;
1567 ReferrerPolicy m_referrerPolicy;
1569 bool m_directionSetOnDocumentElement;
1570 bool m_writingModeSetOnDocumentElement;
1572 #if ENABLE(WEB_TIMING)
1573 DocumentTiming m_documentTiming;
1576 RefPtr<MediaQueryMatcher> m_mediaQueryMatcher;
1577 bool m_writeRecursionIsTooDeep;
1578 unsigned m_writeRecursionDepth;
1580 #if ENABLE(TOUCH_EVENTS)
1581 std::unique_ptr<EventTargetSet> m_touchEventTargets;
1583 std::unique_ptr<EventTargetSet> m_wheelEventTargets;
1585 double m_lastHandledUserGestureTimestamp;
1587 #if ENABLE(REQUEST_ANIMATION_FRAME)
1588 void clearScriptedAnimationController();
1589 RefPtr<ScriptedAnimationController> m_scriptedAnimationController;
1592 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
1593 std::unique_ptr<DeviceMotionClient> m_deviceMotionClient;
1594 std::unique_ptr<DeviceMotionController> m_deviceMotionController;
1595 std::unique_ptr<DeviceOrientationClient> m_deviceOrientationClient;
1596 std::unique_ptr<DeviceOrientationController> m_deviceOrientationController;
1599 // FIXME: Find a better place for this functionality.
1600 #if ENABLE(TELEPHONE_NUMBER_DETECTION)
1603 // These functions provide a two-level setting:
1604 // - A user-settable wantsTelephoneNumberParsing (at the Page / WebView level)
1605 // - A read-only telephoneNumberParsingAllowed which is set by the
1606 // document if it has the appropriate meta tag.
1607 // - isTelephoneNumberParsingEnabled() == isTelephoneNumberParsingAllowed() && page()->settings()->isTelephoneNumberParsingEnabled()
1609 WEBCORE_EXPORT bool isTelephoneNumberParsingAllowed() const;
1610 WEBCORE_EXPORT bool isTelephoneNumberParsingEnabled() const;
1613 friend void setParserFeature(const String& key, const String& value, Document*, void* userData);
1614 void setIsTelephoneNumberParsingAllowed(bool);
1616 bool m_isTelephoneNumberParsingAllowed;
1619 Timer m_pendingTasksTimer;
1620 Vector<Task> m_pendingTasks;
1622 #if ENABLE(IOS_TEXT_AUTOSIZING)
1624 void addAutoSizingNode(Node*, float size);
1625 void validateAutoSizingNodes();
1626 void resetAutoSizingNodes();
1629 typedef HashMap<TextAutoSizingKey, RefPtr<TextAutoSizingValue>, TextAutoSizingHash, TextAutoSizingTraits> TextAutoSizingMap;
1630 TextAutoSizingMap m_textAutoSizedNodes;
1633 #if ENABLE(TEXT_AUTOSIZING)
1634 std::unique_ptr<TextAutosizer> m_textAutosizer;
1637 void platformSuspendOrStopActiveDOMObjects();
1639 bool m_scheduledTasksAreSuspended;
1641 bool m_visualUpdatesAllowed;
1642 Timer m_visualUpdatesSuppressionTimer;
1644 RefPtr<NamedFlowCollection> m_namedFlows;
1646 #if ENABLE(CSP_NEXT)
1647 RefPtr<DOMSecurityPolicy> m_domSecurityPolicy;
1650 void sharedObjectPoolClearTimerFired();
1651 Timer m_sharedObjectPoolClearTimer;
1653 std::unique_ptr<DocumentSharedObjectPool> m_sharedObjectPool;
1656 bool m_didDispatchViewportPropertiesChanged;
1659 typedef HashMap<AtomicString, std::unique_ptr<Locale>> LocaleIdentifierToLocaleMap;
1660 LocaleIdentifierToLocaleMap m_localeCache;
1662 #if ENABLE(TEMPLATE_ELEMENT)
1663 RefPtr<Document> m_templateDocument;
1664 Document* m_templateDocumentHost; // Manually managed weakref (backpointer from m_templateDocument).
1667 RefPtr<CSSFontSelector> m_fontSelector;
1669 #if ENABLE(FONT_LOAD_EVENTS)
1670 RefPtr<FontLoader> m_fontloader;
1673 #if ENABLE(WEB_REPLAY)
1674 RefPtr<JSC::InputCursor> m_inputCursor;
1677 Timer m_didAssociateFormControlsTimer;
1678 Timer m_cookieCacheExpiryTimer;
1679 String m_cachedDOMCookies;
1680 HashSet<RefPtr<Element>> m_associatedFormControls;
1681 unsigned m_disabledFieldsetElementsCount;
1683 bool m_hasInjectedPlugInsScript;
1684 bool m_renderTreeBeingDestroyed;
1685 bool m_hasPreparedForDestruction;
1687 bool m_hasStyleWithViewportUnits;
1689 HashSet<MediaProducer*> m_audioProducers;
1690 MediaProducer::MediaStateFlags m_mediaState { MediaProducer::IsNotPlaying };
1692 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
1693 typedef HashMap<uint64_t, WebCore::MediaPlaybackTargetClient*> TargetIdToClientMap;
1694 TargetIdToClientMap m_idToClientMap;
1695 typedef HashMap<WebCore::MediaPlaybackTargetClient*, uint64_t> TargetClientToIdMap;
1696 TargetClientToIdMap m_clientToIDMap;
1700 inline void Document::notifyRemovePendingSheetIfNeeded()
1702 if (m_needsNotifyRemoveAllPendingStylesheet)
1703 didRemoveAllPendingStylesheet();
1706 #if ENABLE(TEMPLATE_ELEMENT)
1707 inline const Document* Document::templateDocument() const
1709 // If DOCUMENT does not have a browsing context, Let TEMPLATE CONTENTS OWNER be DOCUMENT and abort these steps.
1713 return m_templateDocument.get();
1717 // Put these methods here, because they require the Document definition, but we really want to inline them.
1719 inline bool Node::isDocumentNode() const
1721 return this == &document();
1724 inline ScriptExecutionContext* Node::scriptExecutionContext() const
1729 Element* eventTargetElementForDocument(Document*);
1731 } // namespace WebCore
1733 SPECIALIZE_TYPE_TRAITS_BEGIN(WebCore::Document)
1734 static bool isType(const WebCore::ScriptExecutionContext& context) { return context.isDocument(); }
1735 static bool isType(const WebCore::Node& node) { return node.isDocumentNode(); }
1736 SPECIALIZE_TYPE_TRAITS_END()
1738 #endif // Document_h