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 #if ENABLE(REQUEST_ANIMATION_FRAME)
952 ScriptedAnimationController* scriptedAnimationController() { return m_scriptedAnimationController.get(); }
954 void suspendScriptedAnimationControllerCallbacks();
955 void resumeScriptedAnimationControllerCallbacks();
956 void scriptedAnimationControllerSetThrottled(bool);
958 void windowScreenDidChange(PlatformDisplayID);
960 void finishedParsing();
962 bool inPageCache() const { return m_inPageCache; }
963 void setInPageCache(bool flag);
965 // Elements can register themselves for the "documentWillSuspendForPageCache()" and
966 // "documentDidResumeFromPageCache()" callbacks
967 void registerForPageCacheSuspensionCallbacks(Element*);
968 void unregisterForPageCacheSuspensionCallbacks(Element*);
970 void documentWillBecomeInactive();
971 void documentWillSuspendForPageCache();
972 void documentDidResumeFromPageCache();
974 void registerForMediaVolumeCallbacks(Element*);
975 void unregisterForMediaVolumeCallbacks(Element*);
976 void mediaVolumeDidChange();
978 void registerForPrivateBrowsingStateChangedCallbacks(Element*);
979 void unregisterForPrivateBrowsingStateChangedCallbacks(Element*);
980 void storageBlockingStateDidChange();
981 void privateBrowsingStateDidChange();
983 #if ENABLE(VIDEO_TRACK)
984 void registerForCaptionPreferencesChangedCallbacks(Element*);
985 void unregisterForCaptionPreferencesChangedCallbacks(Element*);
986 void captionPreferencesChanged();
989 #if ENABLE(MEDIA_CONTROLS_SCRIPT)
990 void registerForPageScaleFactorChangedCallbacks(HTMLMediaElement*);
991 void unregisterForPageScaleFactorChangedCallbacks(HTMLMediaElement*);
992 void pageScaleFactorChangedAndStable();
995 void registerForVisibilityStateChangedCallbacks(Element*);
996 void unregisterForVisibilityStateChangedCallbacks(Element*);
998 WEBCORE_EXPORT void setShouldCreateRenderers(bool);
999 bool shouldCreateRenderers();
1001 void setDecoder(PassRefPtr<TextResourceDecoder>);
1002 TextResourceDecoder* decoder() const { return m_decoder.get(); }
1004 WEBCORE_EXPORT String displayStringModifiedByEncoding(const String&) const;
1005 RefPtr<StringImpl> displayStringModifiedByEncoding(PassRefPtr<StringImpl>) const;
1006 void displayBufferModifiedByEncoding(LChar* buffer, unsigned len) const
1008 displayBufferModifiedByEncodingInternal(buffer, len);
1010 void displayBufferModifiedByEncoding(UChar* buffer, unsigned len) const
1012 displayBufferModifiedByEncodingInternal(buffer, len);
1015 // Quirk for the benefit of Apple's Dictionary application.
1016 void setFrameElementsShouldIgnoreScrolling(bool ignore) { m_frameElementsShouldIgnoreScrolling = ignore; }
1017 bool frameElementsShouldIgnoreScrolling() const { return m_frameElementsShouldIgnoreScrolling; }
1019 #if ENABLE(DASHBOARD_SUPPORT)
1020 void setAnnotatedRegionsDirty(bool f) { m_annotatedRegionsDirty = f; }
1021 bool annotatedRegionsDirty() const { return m_annotatedRegionsDirty; }
1022 bool hasAnnotatedRegions () const { return m_hasAnnotatedRegions; }
1023 void setHasAnnotatedRegions(bool f) { m_hasAnnotatedRegions = f; }
1024 WEBCORE_EXPORT const Vector<AnnotatedRegionValue>& annotatedRegions() const;
1025 void setAnnotatedRegions(const Vector<AnnotatedRegionValue>&);
1028 virtual void removeAllEventListeners() override final;
1030 WEBCORE_EXPORT const SVGDocumentExtensions* svgExtensions();
1031 WEBCORE_EXPORT SVGDocumentExtensions& accessSVGExtensions();
1033 void initSecurityContext();
1034 void initContentSecurityPolicy();
1036 void updateURLForPushOrReplaceState(const URL&);
1037 void statePopped(PassRefPtr<SerializedScriptValue>);
1039 bool processingLoadEvent() const { return m_processingLoadEvent; }
1040 bool loadEventFinished() const { return m_loadEventFinished; }
1042 virtual bool isContextThread() const override final;
1043 virtual bool isJSExecutionForbidden() const override final { return false; }
1045 void enqueueWindowEvent(PassRefPtr<Event>);
1046 void enqueueDocumentEvent(PassRefPtr<Event>);
1047 void enqueueOverflowEvent(PassRefPtr<Event>);
1048 void enqueuePageshowEvent(PageshowEventPersistence);
1049 void enqueueHashchangeEvent(const String& oldURL, const String& newURL);
1050 void enqueuePopstateEvent(PassRefPtr<SerializedScriptValue> stateObject);
1051 virtual DocumentEventQueue& eventQueue() const override final { return m_eventQueue; }
1053 WEBCORE_EXPORT void addMediaCanStartListener(MediaCanStartListener*);
1054 WEBCORE_EXPORT void removeMediaCanStartListener(MediaCanStartListener*);
1055 MediaCanStartListener* takeAnyMediaCanStartListener();
1057 #if ENABLE(FULLSCREEN_API)
1058 bool webkitIsFullScreen() const { return m_fullScreenElement.get(); }
1059 bool webkitFullScreenKeyboardInputAllowed() const { return m_fullScreenElement.get() && m_areKeysEnabledInFullScreen; }
1060 Element* webkitCurrentFullScreenElement() const { return m_fullScreenElement.get(); }
1062 enum FullScreenCheckType {
1063 EnforceIFrameAllowFullScreenRequirement,
1064 ExemptIFrameAllowFullScreenRequirement,
1067 void requestFullScreenForElement(Element*, unsigned short flags, FullScreenCheckType);
1068 WEBCORE_EXPORT void webkitCancelFullScreen();
1070 WEBCORE_EXPORT void webkitWillEnterFullScreenForElement(Element*);
1071 WEBCORE_EXPORT void webkitDidEnterFullScreenForElement(Element*);
1072 WEBCORE_EXPORT void webkitWillExitFullScreenForElement(Element*);
1073 WEBCORE_EXPORT void webkitDidExitFullScreenForElement(Element*);
1075 void setFullScreenRenderer(RenderFullScreen*);
1076 RenderFullScreen* fullScreenRenderer() const { return m_fullScreenRenderer; }
1077 void fullScreenRendererDestroyed();
1079 void fullScreenChangeDelayTimerFired();
1080 bool fullScreenIsAllowedForElement(Element*) const;
1081 void fullScreenElementRemoved();
1082 void removeFullScreenElementOfSubtree(Node*, bool amongChildrenOnly = false);
1083 bool isAnimatingFullScreen() const;
1084 WEBCORE_EXPORT void setAnimatingFullScreen(bool);
1087 bool webkitFullscreenEnabled() const;
1088 Element* webkitFullscreenElement() const { return !m_fullScreenElementStack.isEmpty() ? m_fullScreenElementStack.last().get() : 0; }
1089 void webkitExitFullscreen();
1092 #if ENABLE(POINTER_LOCK)
1093 void exitPointerLock();
1094 Element* pointerLockElement() const;
1097 // Used to allow element that loads data without going through a FrameLoader to delay the 'load' event.
1098 void incrementLoadEventDelayCount() { ++m_loadEventDelayCount; }
1099 void decrementLoadEventDelayCount();
1100 bool isDelayingLoadEvent() const { return m_loadEventDelayCount; }
1102 #if ENABLE(IOS_TOUCH_EVENTS)
1103 #include <WebKitAdditions/DocumentIOS.h>
1104 #elif ENABLE(TOUCH_EVENTS)
1105 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;
1108 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
1109 DeviceMotionController* deviceMotionController() const;
1110 DeviceOrientationController* deviceOrientationController() const;
1113 #if ENABLE(WEB_TIMING)
1114 const DocumentTiming& timing() const { return m_documentTiming; }
1117 #if ENABLE(REQUEST_ANIMATION_FRAME)
1118 int requestAnimationFrame(PassRefPtr<RequestAnimationFrameCallback>);
1119 void cancelAnimationFrame(int id);
1120 void serviceScriptedAnimations(double monotonicAnimationStartTime);
1123 void sendWillRevealEdgeEventsIfNeeded(const IntPoint& oldPosition, const IntPoint& newPosition, const IntRect& visibleRect, const IntSize& contentsSize, Element* target = nullptr);
1125 virtual EventTarget* errorEventTarget() override final;
1126 virtual void logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, RefPtr<Inspector::ScriptCallStack>&&) override final;
1128 void initDNSPrefetch();
1130 void didAddWheelEventHandler(Node&);
1131 void didRemoveWheelEventHandler(Node&, EventHandlerRemoval = EventHandlerRemoval::One);
1133 double lastHandledUserGestureTimestamp() const { return m_lastHandledUserGestureTimestamp; }
1134 void updateLastHandledUserGestureTimestamp();
1136 #if ENABLE(TOUCH_EVENTS)
1137 bool hasTouchEventHandlers() const { return (m_touchEventTargets.get()) ? m_touchEventTargets->size() : false; }
1139 bool hasTouchEventHandlers() const { return false; }
1142 // Used for testing. Count handlers in the main document, and one per frame which contains handlers.
1143 WEBCORE_EXPORT unsigned wheelEventHandlerCount() const;
1144 WEBCORE_EXPORT unsigned touchEventHandlerCount() const;
1146 WEBCORE_EXPORT void startTrackingStyleRecalcs();
1147 WEBCORE_EXPORT unsigned styleRecalcCount() const;
1149 void didAddTouchEventHandler(Node&);
1150 void didRemoveTouchEventHandler(Node&, EventHandlerRemoval = EventHandlerRemoval::One);
1152 void didRemoveEventTargetNode(Node&);
1154 const EventTargetSet* touchEventTargets() const
1156 #if ENABLE(TOUCH_EVENTS)
1157 return m_touchEventTargets.get();
1163 const EventTargetSet* wheelEventTargets() const { return m_wheelEventTargets.get(); }
1165 typedef std::pair<Region, bool> RegionFixedPair;
1166 RegionFixedPair absoluteRegionForEventTargets(const EventTargetSet*);
1168 LayoutRect absoluteEventHandlerBounds(bool&) override final;
1170 bool visualUpdatesAllowed() const { return m_visualUpdatesAllowed; }
1172 bool isInDocumentWrite() { return m_writeRecursionDepth > 0; }
1174 void suspendScheduledTasks(ActiveDOMObject::ReasonForSuspension);
1175 void resumeScheduledTasks(ActiveDOMObject::ReasonForSuspension);
1177 #if ENABLE(CSS_DEVICE_ADAPTATION)
1178 IntSize initialViewportSize() const;
1181 #if ENABLE(TEXT_AUTOSIZING)
1182 TextAutosizer* textAutosizer() { return m_textAutosizer.get(); }
1185 void adjustFloatQuadsForScrollAndAbsoluteZoomAndFrameScale(Vector<FloatQuad>&, const RenderStyle&);
1186 void adjustFloatRectForScrollAndAbsoluteZoomAndFrameScale(FloatRect&, const RenderStyle&);
1188 bool hasActiveParser();
1189 void incrementActiveParserCount() { ++m_activeParserCount; }
1190 void decrementActiveParserCount();
1192 DocumentSharedObjectPool* sharedObjectPool() { return m_sharedObjectPool.get(); }
1194 void didRemoveAllPendingStylesheet();
1195 void setNeedsNotifyRemoveAllPendingStylesheet() { m_needsNotifyRemoveAllPendingStylesheet = true; }
1196 void clearStyleResolver();
1198 bool inStyleRecalc() { return m_inStyleRecalc; }
1200 // Return a Locale for the default locale if the argument is null or empty.
1201 Locale& getCachedLocale(const AtomicString& locale = nullAtom);
1203 #if ENABLE(TEMPLATE_ELEMENT)
1204 const Document* templateDocument() const;
1205 Document& ensureTemplateDocument();
1206 void setTemplateDocumentHost(Document* templateDocumentHost) { m_templateDocumentHost = templateDocumentHost; }
1207 Document* templateDocumentHost() { return m_templateDocumentHost; }
1210 void didAssociateFormControl(Element*);
1211 bool hasDisabledFieldsetElement() const { return m_disabledFieldsetElementsCount; }
1212 void addDisabledFieldsetElement() { m_disabledFieldsetElementsCount++; }
1213 void removeDisabledFieldsetElement() { ASSERT(m_disabledFieldsetElementsCount); m_disabledFieldsetElementsCount--; }
1215 WEBCORE_EXPORT virtual void addConsoleMessage(MessageSource, MessageLevel, const String& message, unsigned long requestIdentifier = 0) override final;
1217 WEBCORE_EXPORT virtual SecurityOrigin* topOrigin() const override final;
1219 #if ENABLE(FONT_LOAD_EVENTS)
1220 RefPtr<FontLoader> fonts();
1223 void ensurePlugInsInjectedScript(DOMWrapperWorld&);
1225 void setVisualUpdatesAllowedByClient(bool);
1227 #if ENABLE(SUBTLE_CRYPTO)
1228 virtual bool wrapCryptoKey(const Vector<uint8_t>& key, Vector<uint8_t>& wrappedKey) override final;
1229 virtual bool unwrapCryptoKey(const Vector<uint8_t>& wrappedKey, Vector<uint8_t>& key) override final;
1232 void setHasStyleWithViewportUnits() { m_hasStyleWithViewportUnits = true; }
1233 bool hasStyleWithViewportUnits() const { return m_hasStyleWithViewportUnits; }
1234 void updateViewportUnitsOnResize();
1236 WEBCORE_EXPORT void addAudioProducer(MediaProducer*);
1237 WEBCORE_EXPORT void removeAudioProducer(MediaProducer*);
1238 MediaProducer::MediaStateFlags mediaState() const { return m_mediaState; }
1239 WEBCORE_EXPORT void updateIsPlayingMedia();
1240 void pageMutedStateDidChange();
1241 WeakPtr<Document> createWeakPtr() { return m_weakFactory.createWeakPtr(); }
1243 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
1244 void addPlaybackTargetPickerClient(MediaPlaybackTargetClient&);
1245 void removePlaybackTargetPickerClient(MediaPlaybackTargetClient&);
1246 void showPlaybackTargetPicker(MediaPlaybackTargetClient&, bool);
1247 void playbackTargetPickerClientStateDidChange(MediaPlaybackTargetClient&, MediaProducer::MediaStateFlags);
1249 void setPlaybackTarget(uint64_t, Ref<MediaPlaybackTarget>&&);
1250 void playbackTargetAvailabilityDidChange(uint64_t, bool);
1251 void setShouldPlayToPlaybackTarget(uint64_t, bool);
1255 enum ConstructionFlags { Synthesized = 1, NonRenderedPlaceholder = 1 << 1 };
1256 Document(Frame*, const URL&, unsigned = DefaultDocumentClass, unsigned constructionFlags = 0);
1258 void clearXMLVersion() { m_xmlVersion = String(); }
1260 virtual Ref<Document> cloneDocumentWithoutChildren() const;
1264 friend class IgnoreDestructiveWriteCountIncrementer;
1266 void commonTeardown();
1268 RenderObject* renderer() const = delete;
1269 void setRenderer(RenderObject*) = delete;
1271 void createRenderTree();
1272 void detachParser();
1274 typedef void (*ArgumentsCallback)(const String& keyString, const String& valueString, Document*, void* data);
1275 void processArguments(const String& features, void* data, ArgumentsCallback);
1277 // FontSelectorClient
1278 virtual void fontsNeedUpdate(FontSelector*) override final;
1280 virtual bool isDocument() const override final { return true; }
1282 virtual void childrenChanged(const ChildChange&) override final;
1284 virtual String nodeName() const override final;
1285 virtual NodeType nodeType() const override final;
1286 virtual bool childTypeAllowed(NodeType) const override final;
1287 virtual RefPtr<Node> cloneNodeInternal(Document&, CloningOperation) override final;
1288 void cloneDataFromDocument(const Document&);
1290 virtual void refScriptExecutionContext() override final { ref(); }
1291 virtual void derefScriptExecutionContext() override final { deref(); }
1293 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;
1295 virtual double minimumTimerInterval() const override final;
1297 virtual double timerAlignmentInterval() const override final;
1299 void updateTitle(const StringWithDirection&);
1300 void updateFocusAppearanceTimerFired();
1301 void updateBaseURL();
1303 void buildAccessKeyMap(TreeScope* root);
1305 void createStyleResolver();
1307 void loadEventDelayTimerFired();
1309 void pendingTasksTimerFired();
1311 template <typename CharacterType>
1312 void displayBufferModifiedByEncodingInternal(CharacterType*, unsigned) const;
1314 PageVisibilityState pageVisibilityState() const;
1316 Node* nodeFromPoint(const LayoutPoint& clientPoint, LayoutPoint* localPoint = nullptr);
1318 Ref<HTMLCollection> ensureCachedCollection(CollectionType);
1320 #if ENABLE(FULLSCREEN_API)
1321 void dispatchFullScreenChangeOrErrorEvent(Deque<RefPtr<Node>>&, const AtomicString& eventName, bool shouldNotifyMediaElement);
1322 void clearFullscreenElementStack();
1323 void popFullscreenElementStack();
1324 void pushFullscreenElementStack(Element*);
1325 void addDocumentToFullScreenChangeEventQueue(Document*);
1328 void setVisualUpdatesAllowed(ReadyState);
1329 void setVisualUpdatesAllowed(bool);
1330 void visualUpdatesSuppressionTimerFired();
1332 void addListenerType(ListenerType listenerType) { m_listenerTypes |= listenerType; }
1334 void didAssociateFormControlsTimerFired();
1336 void wheelEventHandlersChanged();
1338 // DOM Cookies caching.
1339 const String& cachedDOMCookies() const { return m_cachedDOMCookies; }
1340 void setCachedDOMCookies(const String&);
1341 bool isDOMCookieCacheValid() const { return m_cookieCacheExpiryTimer.isActive(); }
1342 void invalidateDOMCookieCache();
1343 void domCookieCacheExpiryTimerFired();
1344 virtual void didLoadResourceSynchronously(const ResourceRequest&) override final;
1346 unsigned m_referencingNodeCount;
1348 std::unique_ptr<StyleResolver> m_styleResolver;
1349 bool m_didCalculateStyleResolver;
1350 bool m_hasNodesWithPlaceholderStyle;
1351 bool m_needsNotifyRemoveAllPendingStylesheet;
1352 // But sometimes you need to ignore pending stylesheet count to
1353 // force an immediate layout when requested by JS.
1354 bool m_ignorePendingStylesheets;
1356 // If we do ignore the pending stylesheet count, then we need to add a boolean
1357 // to track that this happened so that we can do a full repaint when the stylesheets
1358 // do eventually load.
1359 PendingSheetLayout m_pendingSheetLayout;
1362 RefPtr<DOMWindow> m_domWindow;
1364 Ref<CachedResourceLoader> m_cachedResourceLoader;
1365 RefPtr<DocumentParser> m_parser;
1366 unsigned m_activeParserCount;
1371 URL m_url; // Document.URL: The URL from which this document was retrieved.
1372 URL m_baseURL; // Node.baseURI: The URL to use when resolving relative URLs.
1373 URL m_baseURLOverride; // An alternative base URL that takes precedence over m_baseURL (but not m_baseElementURL).
1374 URL m_baseElementURL; // The URL set by the <base> element.
1375 URL m_cookieURL; // The URL to use for cookie access.
1376 URL m_firstPartyForCookies; // The policy URL for third-party cookie blocking.
1378 // Document.documentURI:
1379 // Although URL-like, Document.documentURI can actually be set to any
1380 // string by content. Document.documentURI affects m_baseURL unless the
1381 // document contains a <base> element, in which case the <base> element
1382 // takes precedence.
1384 // This property is read-only from JavaScript, but writable from Objective C.
1385 String m_documentURI;
1387 String m_baseTarget;
1389 // MIME type of the document in case it was cloned or created by XHR.
1390 String m_overriddenMIMEType;
1392 std::unique_ptr<DOMImplementation> m_implementation;
1394 RefPtr<CSSStyleSheet> m_elementSheet;
1397 bool m_paginatedForScreen;
1399 DocumentCompatibilityMode m_compatibilityMode;
1400 bool m_compatibilityModeLocked; // This is cheaper than making setCompatibilityMode virtual.
1404 RefPtr<Element> m_focusedElement;
1405 RefPtr<Element> m_hoveredElement;
1406 RefPtr<Element> m_activeElement;
1407 RefPtr<Element> m_documentElement;
1408 UserActionElementSet m_userActionElements;
1410 uint64_t m_domTreeVersion;
1411 static uint64_t s_globalTreeVersion;
1413 HashSet<NodeIterator*> m_nodeIterators;
1414 HashSet<Range*> m_ranges;
1416 unsigned m_listenerTypes;
1418 MutationObserverOptions m_mutationObserverTypes;
1420 DocumentStyleSheetCollection m_styleSheetCollection;
1421 RefPtr<StyleSheetList> m_styleSheetList;
1423 std::unique_ptr<FormController> m_formController;
1426 Color m_visitedLinkColor;
1427 Color m_activeLinkColor;
1428 const std::unique_ptr<VisitedLinkState> m_visitedLinkState;
1430 bool m_visuallyOrdered;
1431 ReadyState m_readyState;
1434 Timer m_optimizedStyleSheetUpdateTimer;
1435 Timer m_styleRecalcTimer;
1436 bool m_pendingStyleRecalcShouldForce;
1437 bool m_inStyleRecalc;
1438 bool m_closeAfterStyleRecalc;
1440 bool m_gotoAnchorNeededAfterStylesheetsLoad;
1441 bool m_isDNSPrefetchEnabled;
1442 bool m_haveExplicitlyDisabledDNSPrefetch;
1443 bool m_frameElementsShouldIgnoreScrolling;
1444 bool m_updateFocusAppearanceRestoresSelection;
1446 // http://www.whatwg.org/specs/web-apps/current-work/#ignore-destructive-writes-counter
1447 unsigned m_ignoreDestructiveWriteCount;
1449 unsigned m_styleRecalcCount { 0 };
1451 StringWithDirection m_title;
1452 StringWithDirection m_rawTitle;
1453 bool m_titleSetExplicitly;
1454 RefPtr<Element> m_titleElement;
1456 std::unique_ptr<AXObjectCache> m_axObjectCache;
1457 const std::unique_ptr<DocumentMarkerController> m_markers;
1459 Timer m_updateFocusAppearanceTimer;
1461 Element* m_cssTarget;
1463 // FIXME: Merge these 2 variables into an enum. Also, FrameLoader::m_didCallImplicitClose
1464 // is almost a duplication of this data, so that should probably get merged in too.
1465 // FIXME: Document::m_processingLoadEvent and DocumentLoader::m_wasOnloadHandled are roughly the same
1466 // and should be merged.
1467 bool m_processingLoadEvent;
1468 bool m_loadEventFinished;
1470 RefPtr<SerializedScriptValue> m_pendingStateObject;
1471 std::chrono::steady_clock::time_point m_startTime;
1472 bool m_overMinimumLayoutThreshold;
1474 std::unique_ptr<ScriptRunner> m_scriptRunner;
1476 Vector<RefPtr<HTMLScriptElement>> m_currentScriptStack;
1479 std::unique_ptr<TransformSource> m_transformSource;
1480 RefPtr<Document> m_transformSourceDocument;
1483 String m_xmlEncoding;
1484 String m_xmlVersion;
1485 unsigned m_xmlStandalone : 2;
1486 unsigned m_hasXMLDeclaration : 1;
1488 String m_contentLanguage;
1490 RefPtr<TextResourceDecoder> m_decoder;
1492 InheritedBool m_designMode;
1494 HashSet<LiveNodeList*> m_listsInvalidatedAtDocument;
1495 HashSet<HTMLCollection*> m_collectionsInvalidatedAtDocument;
1496 #if !ASSERT_DISABLED
1497 bool m_inInvalidateNodeListAndCollectionCaches;
1500 unsigned m_nodeListAndCollectionCounts[numNodeListInvalidationTypes];
1502 RefPtr<XPathEvaluator> m_xpathEvaluator;
1504 std::unique_ptr<SVGDocumentExtensions> m_svgExtensions;
1506 #if ENABLE(DASHBOARD_SUPPORT)
1507 Vector<AnnotatedRegionValue> m_annotatedRegions;
1508 bool m_hasAnnotatedRegions;
1509 bool m_annotatedRegionsDirty;
1512 HashMap<String, RefPtr<HTMLCanvasElement>> m_cssCanvasElements;
1514 bool m_createRenderers;
1517 HashSet<Element*> m_documentSuspensionCallbackElements;
1518 HashSet<Element*> m_mediaVolumeCallbackElements;
1519 HashSet<Element*> m_privateBrowsingStateChangedElements;
1520 #if ENABLE(VIDEO_TRACK)
1521 HashSet<Element*> m_captionPreferencesChangedElements;
1524 #if ENABLE(MEDIA_CONTROLS_SCRIPT)
1525 HashSet<HTMLMediaElement*> m_pageScaleFactorChangedElements;
1528 HashSet<Element*> m_visibilityStateCallbackElements;
1530 HashMap<StringImpl*, Element*, CaseFoldingHash> m_elementsByAccessKey;
1531 bool m_accessKeyMapValid;
1533 DocumentOrderedMap m_imagesByUsemap;
1535 std::unique_ptr<SelectorQueryCache> m_selectorQueryCache;
1537 DocumentClassFlags m_documentClasses;
1539 bool m_isSynthesized;
1540 bool m_isNonRenderedPlaceholder;
1542 bool m_sawElementsInKnownNamespaces;
1543 bool m_isSrcdocDocument;
1545 RenderPtr<RenderView> m_renderView;
1546 mutable DocumentEventQueue m_eventQueue;
1548 WeakPtrFactory<Document> m_weakFactory;
1550 HashSet<MediaCanStartListener*> m_mediaCanStartListeners;
1552 #if ENABLE(FULLSCREEN_API)
1553 bool m_areKeysEnabledInFullScreen;
1554 RefPtr<Element> m_fullScreenElement;
1555 Vector<RefPtr<Element>> m_fullScreenElementStack;
1556 RenderFullScreen* m_fullScreenRenderer;
1557 Timer m_fullScreenChangeDelayTimer;
1558 Deque<RefPtr<Node>> m_fullScreenChangeEventTargetQueue;
1559 Deque<RefPtr<Node>> m_fullScreenErrorEventTargetQueue;
1560 bool m_isAnimatingFullScreen;
1561 LayoutRect m_savedPlaceholderFrameRect;
1562 RefPtr<RenderStyle> m_savedPlaceholderRenderStyle;
1565 int m_loadEventDelayCount;
1566 Timer m_loadEventDelayTimer;
1568 ViewportArguments m_viewportArguments;
1570 ReferrerPolicy m_referrerPolicy;
1572 bool m_directionSetOnDocumentElement;
1573 bool m_writingModeSetOnDocumentElement;
1575 #if ENABLE(WEB_TIMING)
1576 DocumentTiming m_documentTiming;
1579 RefPtr<MediaQueryMatcher> m_mediaQueryMatcher;
1580 bool m_writeRecursionIsTooDeep;
1581 unsigned m_writeRecursionDepth;
1583 #if ENABLE(TOUCH_EVENTS)
1584 std::unique_ptr<EventTargetSet> m_touchEventTargets;
1586 std::unique_ptr<EventTargetSet> m_wheelEventTargets;
1588 double m_lastHandledUserGestureTimestamp;
1590 #if ENABLE(REQUEST_ANIMATION_FRAME)
1591 void clearScriptedAnimationController();
1592 RefPtr<ScriptedAnimationController> m_scriptedAnimationController;
1595 #if ENABLE(DEVICE_ORIENTATION) && PLATFORM(IOS)
1596 std::unique_ptr<DeviceMotionClient> m_deviceMotionClient;
1597 std::unique_ptr<DeviceMotionController> m_deviceMotionController;
1598 std::unique_ptr<DeviceOrientationClient> m_deviceOrientationClient;
1599 std::unique_ptr<DeviceOrientationController> m_deviceOrientationController;
1602 // FIXME: Find a better place for this functionality.
1603 #if ENABLE(TELEPHONE_NUMBER_DETECTION)
1606 // These functions provide a two-level setting:
1607 // - A user-settable wantsTelephoneNumberParsing (at the Page / WebView level)
1608 // - A read-only telephoneNumberParsingAllowed which is set by the
1609 // document if it has the appropriate meta tag.
1610 // - isTelephoneNumberParsingEnabled() == isTelephoneNumberParsingAllowed() && page()->settings()->isTelephoneNumberParsingEnabled()
1612 WEBCORE_EXPORT bool isTelephoneNumberParsingAllowed() const;
1613 WEBCORE_EXPORT bool isTelephoneNumberParsingEnabled() const;
1616 friend void setParserFeature(const String& key, const String& value, Document*, void* userData);
1617 void setIsTelephoneNumberParsingAllowed(bool);
1619 bool m_isTelephoneNumberParsingAllowed;
1622 Timer m_pendingTasksTimer;
1623 Vector<Task> m_pendingTasks;
1625 #if ENABLE(IOS_TEXT_AUTOSIZING)
1627 void addAutoSizingNode(Node*, float size);
1628 void validateAutoSizingNodes();
1629 void resetAutoSizingNodes();
1632 typedef HashMap<TextAutoSizingKey, RefPtr<TextAutoSizingValue>, TextAutoSizingHash, TextAutoSizingTraits> TextAutoSizingMap;
1633 TextAutoSizingMap m_textAutoSizedNodes;
1636 #if ENABLE(TEXT_AUTOSIZING)
1637 std::unique_ptr<TextAutosizer> m_textAutosizer;
1640 void platformSuspendOrStopActiveDOMObjects();
1642 bool m_scheduledTasksAreSuspended;
1644 bool m_visualUpdatesAllowed;
1645 Timer m_visualUpdatesSuppressionTimer;
1647 RefPtr<NamedFlowCollection> m_namedFlows;
1649 #if ENABLE(CSP_NEXT)
1650 RefPtr<DOMSecurityPolicy> m_domSecurityPolicy;
1653 void sharedObjectPoolClearTimerFired();
1654 Timer m_sharedObjectPoolClearTimer;
1656 std::unique_ptr<DocumentSharedObjectPool> m_sharedObjectPool;
1659 bool m_didDispatchViewportPropertiesChanged;
1662 typedef HashMap<AtomicString, std::unique_ptr<Locale>> LocaleIdentifierToLocaleMap;
1663 LocaleIdentifierToLocaleMap m_localeCache;
1665 #if ENABLE(TEMPLATE_ELEMENT)
1666 RefPtr<Document> m_templateDocument;
1667 Document* m_templateDocumentHost; // Manually managed weakref (backpointer from m_templateDocument).
1670 RefPtr<CSSFontSelector> m_fontSelector;
1672 #if ENABLE(FONT_LOAD_EVENTS)
1673 RefPtr<FontLoader> m_fontloader;
1676 #if ENABLE(WEB_REPLAY)
1677 RefPtr<JSC::InputCursor> m_inputCursor;
1680 Timer m_didAssociateFormControlsTimer;
1681 Timer m_cookieCacheExpiryTimer;
1682 String m_cachedDOMCookies;
1683 HashSet<RefPtr<Element>> m_associatedFormControls;
1684 unsigned m_disabledFieldsetElementsCount;
1686 bool m_hasInjectedPlugInsScript;
1687 bool m_renderTreeBeingDestroyed;
1688 bool m_hasPreparedForDestruction;
1690 bool m_hasStyleWithViewportUnits;
1692 HashSet<MediaProducer*> m_audioProducers;
1693 MediaProducer::MediaStateFlags m_mediaState { MediaProducer::IsNotPlaying };
1695 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
1696 typedef HashMap<uint64_t, WebCore::MediaPlaybackTargetClient*> TargetIdToClientMap;
1697 TargetIdToClientMap m_idToClientMap;
1698 typedef HashMap<WebCore::MediaPlaybackTargetClient*, uint64_t> TargetClientToIdMap;
1699 TargetClientToIdMap m_clientToIDMap;
1703 inline void Document::notifyRemovePendingSheetIfNeeded()
1705 if (m_needsNotifyRemoveAllPendingStylesheet)
1706 didRemoveAllPendingStylesheet();
1709 #if ENABLE(TEMPLATE_ELEMENT)
1710 inline const Document* Document::templateDocument() const
1712 // If DOCUMENT does not have a browsing context, Let TEMPLATE CONTENTS OWNER be DOCUMENT and abort these steps.
1716 return m_templateDocument.get();
1720 // Put these methods here, because they require the Document definition, but we really want to inline them.
1722 inline bool Node::isDocumentNode() const
1724 return this == &document();
1727 inline ScriptExecutionContext* Node::scriptExecutionContext() const
1732 Element* eventTargetElementForDocument(Document*);
1734 } // namespace WebCore
1736 SPECIALIZE_TYPE_TRAITS_BEGIN(WebCore::Document)
1737 static bool isType(const WebCore::ScriptExecutionContext& context) { return context.isDocument(); }
1738 static bool isType(const WebCore::Node& node) { return node.isDocumentNode(); }
1739 SPECIALIZE_TYPE_TRAITS_END()
1741 #endif // Document_h