1/*
2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * (C) 1999 Antti Koivisto (koivisto@kde.org)
4 * (C) 2001 Dirk Mueller (mueller@kde.org)
5 * (C) 2006 Alexey Proskuryakov (ap@webkit.org)
6 * Copyright (C) 2004-2019 Apple Inc. All rights reserved.
7 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
8 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
9 * Copyright (C) 2011 Google Inc. All rights reserved.
10 *
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Library General Public
13 * License as published by the Free Software Foundation; either
14 * version 2 of the License, or (at your option) any later version.
15 *
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Library General Public License for more details.
20 *
21 * You should have received a copy of the GNU Library General Public License
22 * along with this library; see the file COPYING.LIB. If not, write to
23 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24 * Boston, MA 02110-1301, USA.
25 *
26 */
27
28#pragma once
29
30#include "CSSRegisteredCustomProperty.h"
31#include "Color.h"
32#include "ContainerNode.h"
33#include "DisabledAdaptations.h"
34#include "DocumentEventQueue.h"
35#include "DocumentIdentifier.h"
36#include "DocumentTiming.h"
37#include "ElementIdentifier.h"
38#include "FocusDirection.h"
39#include "FontSelectorClient.h"
40#include "FrameDestructionObserver.h"
41#include "GenericTaskQueue.h"
42#include "MediaProducer.h"
43#include "MutationObserver.h"
44#include "OrientationNotifier.h"
45#include "PageIdentifier.h"
46#include "PlatformEvent.h"
47#include "ReferrerPolicy.h"
48#include "Region.h"
49#include "RegistrableDomain.h"
50#include "RenderPtr.h"
51#include "ScriptExecutionContext.h"
52#include "SecurityPolicyViolationEvent.h"
53#include "StringWithDirection.h"
54#include "StyleColor.h"
55#include "Supplementable.h"
56#include "TextResourceDecoder.h"
57#include "Timer.h"
58#include "TreeScope.h"
59#include "UserActionElementSet.h"
60#include "ViewportArguments.h"
61#include "VisibilityState.h"
62#include <pal/SessionID.h>
63#include <wtf/Deque.h>
64#include <wtf/Forward.h>
65#include <wtf/HashCountedSet.h>
66#include <wtf/HashSet.h>
67#include <wtf/Logger.h>
68#include <wtf/ObjectIdentifier.h>
69#include <wtf/UniqueRef.h>
70#include <wtf/WeakHashSet.h>
71#include <wtf/WeakPtr.h>
72#include <wtf/text/AtomStringHash.h>
73
74#if PLATFORM(IOS_FAMILY)
75#include "EventTrackingRegions.h"
76#endif
77
78#if ENABLE(IOS_TOUCH_EVENTS)
79#include <wtf/ThreadingPrimitives.h>
80#endif
81
82namespace JSC {
83class ExecState;
84class InputCursor;
85}
86
87namespace WebCore {
88
89class ApplicationStateChangeListener;
90class AXObjectCache;
91class Attr;
92class CDATASection;
93class CSSCustomPropertyValue;
94class CSSFontSelector;
95class CSSStyleDeclaration;
96class CSSStyleSheet;
97class CachedCSSStyleSheet;
98class CachedFrameBase;
99class CachedResourceLoader;
100class CachedScript;
101class CanvasRenderingContext2D;
102class CharacterData;
103class Comment;
104class ConstantPropertyMap;
105class ContentChangeObserver;
106class DOMImplementation;
107class DOMSelection;
108class DOMWindow;
109class DOMWrapperWorld;
110class Database;
111class DatabaseThread;
112class DocumentFragment;
113class DocumentLoader;
114class DocumentMarkerController;
115class DocumentParser;
116class DocumentSharedObjectPool;
117class DocumentTimeline;
118class DocumentType;
119class EditingBehavior;
120class ExtensionStyleSheets;
121class FloatQuad;
122class FloatRect;
123class FontFaceSet;
124class FormController;
125class Frame;
126class FrameView;
127class FullscreenManager;
128class HTMLAllCollection;
129class HTMLBodyElement;
130class HTMLCanvasElement;
131class HTMLCollection;
132class HTMLDocument;
133class HTMLElement;
134class HTMLFrameOwnerElement;
135class HTMLHeadElement;
136class HTMLIFrameElement;
137class HTMLImageElement;
138class HTMLMapElement;
139class HTMLMediaElement;
140class HTMLPictureElement;
141class HTMLScriptElement;
142class HitTestLocation;
143class HitTestRequest;
144class HitTestResult;
145class ImageBitmapRenderingContext;
146class IntPoint;
147class JSNode;
148class LayoutPoint;
149class LayoutRect;
150class LiveNodeList;
151class Locale;
152class Location;
153class MediaCanStartListener;
154class MediaPlaybackTarget;
155class MediaPlaybackTargetClient;
156class MediaQueryList;
157class MediaQueryMatcher;
158class MouseEventWithHitTestResults;
159class NodeFilter;
160class NodeIterator;
161class Page;
162class PaintWorkletGlobalScope;
163class PlatformMouseEvent;
164class ProcessingInstruction;
165class QualifiedName;
166class Quirks;
167class Range;
168class RenderTreeBuilder;
169class RenderView;
170class RequestAnimationFrameCallback;
171class SVGDocumentExtensions;
172class SVGSVGElement;
173class SVGUseElement;
174class SWClientConnection;
175class ScriptElementData;
176class ScriptModuleLoader;
177class ScriptRunner;
178class ScriptableDocumentParser;
179class ScriptedAnimationController;
180class SecurityOrigin;
181class SegmentedString;
182class SelectorQuery;
183class SelectorQueryCache;
184class SerializedScriptValue;
185class Settings;
186class StringCallback;
187class StyleResolver;
188class StyleSheet;
189class StyleSheetContents;
190class StyleSheetList;
191class Text;
192class TextResourceDecoder;
193class TreeWalker;
194class UndoManager;
195class VisibilityChangeClient;
196class VisitedLinkState;
197class WebAnimation;
198class WebGL2RenderingContext;
199class WebGLRenderingContext;
200class GPUCanvasContext;
201class WindowProxy;
202class Worklet;
203class XPathEvaluator;
204class XPathExpression;
205class XPathNSResolver;
206class XPathResult;
207
208template<typename> class ExceptionOr;
209
210enum CollectionType;
211enum class ShouldOpenExternalURLsPolicy : uint8_t;
212
213enum class RouteSharingPolicy : uint8_t;
214
215using PlatformDisplayID = uint32_t;
216
217#if ENABLE(XSLT)
218class TransformSource;
219#endif
220
221#if ENABLE(TOUCH_EVENTS) || ENABLE(IOS_TOUCH_EVENTS)
222class Touch;
223class TouchList;
224#endif
225
226#if ENABLE(DEVICE_ORIENTATION)
227#if PLATFORM(IOS_FAMILY)
228class DeviceMotionClient;
229class DeviceMotionController;
230class DeviceOrientationClient;
231class DeviceOrientationController;
232#endif
233class DeviceOrientationAndMotionAccessController;
234#endif
235
236#if ENABLE(TEXT_AUTOSIZING)
237class TextAutoSizing;
238#endif
239
240#if ENABLE(MEDIA_SESSION)
241class MediaSession;
242#endif
243
244#if ENABLE(ATTACHMENT_ELEMENT)
245class HTMLAttachmentElement;
246#endif
247
248#if ENABLE(INTERSECTION_OBSERVER)
249class IntersectionObserver;
250#endif
251
252#if ENABLE(RESIZE_OBSERVER)
253class ResizeObserver;
254#endif
255
256namespace Style {
257class Scope;
258};
259
260const uint64_t HTMLMediaElementInvalidID = 0;
261
262enum PageshowEventPersistence { PageshowEventNotPersisted, PageshowEventPersisted };
263
264enum NodeListInvalidationType {
265 DoNotInvalidateOnAttributeChanges,
266 InvalidateOnClassAttrChange,
267 InvalidateOnIdNameAttrChange,
268 InvalidateOnNameAttrChange,
269 InvalidateOnForTypeAttrChange,
270 InvalidateForFormControls,
271 InvalidateOnHRefAttrChange,
272 InvalidateOnAnyAttrChange,
273};
274const int numNodeListInvalidationTypes = InvalidateOnAnyAttrChange + 1;
275
276enum class EventHandlerRemoval { One, All };
277typedef HashCountedSet<Node*> EventTargetSet;
278
279enum DocumentClass {
280 DefaultDocumentClass = 0,
281 HTMLDocumentClass = 1,
282 XHTMLDocumentClass = 1 << 1,
283 ImageDocumentClass = 1 << 2,
284 PluginDocumentClass = 1 << 3,
285 MediaDocumentClass = 1 << 4,
286 SVGDocumentClass = 1 << 5,
287 TextDocumentClass = 1 << 6,
288 XMLDocumentClass = 1 << 7,
289};
290typedef unsigned char DocumentClassFlags;
291
292enum class DocumentCompatibilityMode : unsigned char {
293 NoQuirksMode = 1,
294 QuirksMode = 1 << 1,
295 LimitedQuirksMode = 1 << 2
296};
297
298enum DimensionsCheck { WidthDimensionsCheck = 1 << 0, HeightDimensionsCheck = 1 << 1, AllDimensionsCheck = 1 << 2 };
299
300enum class SelectionRestorationMode { Restore, SetDefault };
301
302enum class HttpEquivPolicy {
303 Enabled,
304 DisabledBySettings,
305 DisabledByContentDispositionAttachmentSandbox
306};
307
308enum class CustomElementNameValidationStatus {
309 Valid,
310 FirstCharacterIsNotLowercaseASCIILetter,
311 ContainsNoHyphen,
312 ContainsUppercaseASCIILetter,
313 ContainsDisallowedCharacter,
314 ConflictsWithStandardElementName
315};
316
317using RenderingContext = Variant<
318#if ENABLE(WEBGL)
319 RefPtr<WebGLRenderingContext>,
320#endif
321#if ENABLE(WEBGL2)
322 RefPtr<WebGL2RenderingContext>,
323#endif
324#if ENABLE(WEBGPU)
325 RefPtr<GPUCanvasContext>,
326#endif
327 RefPtr<ImageBitmapRenderingContext>,
328 RefPtr<CanvasRenderingContext2D>
329>;
330
331class DocumentParserYieldToken {
332 WTF_MAKE_FAST_ALLOCATED;
333public:
334 WEBCORE_EXPORT DocumentParserYieldToken(Document&);
335 WEBCORE_EXPORT ~DocumentParserYieldToken();
336
337private:
338 WeakPtr<Document> m_document;
339};
340
341class Document
342 : public ContainerNode
343 , public TreeScope
344 , public ScriptExecutionContext
345 , public FontSelectorClient
346 , public FrameDestructionObserver
347 , public Supplementable<Document>
348 , public Logger::Observer {
349 WTF_MAKE_ISO_ALLOCATED(Document);
350public:
351 static Ref<Document> create(const URL&);
352 static Ref<Document> createNonRenderedPlaceholder(Frame&, const URL&);
353 static Ref<Document> create(Document&);
354
355 virtual ~Document();
356
357 // Nodes belonging to this document increase referencingNodeCount -
358 // these are enough to keep the document from being destroyed, but
359 // not enough to keep it from removing its children. This allows a
360 // node that outlives its document to still have a valid document
361 // pointer without introducing reference cycles.
362 void incrementReferencingNodeCount()
363 {
364 ASSERT(!m_deletionHasBegun);
365 ++m_referencingNodeCount;
366 }
367
368 void decrementReferencingNodeCount()
369 {
370 ASSERT(!m_deletionHasBegun || !m_referencingNodeCount);
371 --m_referencingNodeCount;
372 if (!m_referencingNodeCount && !refCount()) {
373#if !ASSERT_DISABLED
374 m_deletionHasBegun = true;
375#endif
376 m_refCountAndParentBit = s_refCountIncrement; // Avoid double destruction through use of Ref<T>/RefPtr<T>. (This is a security mitigation in case of programmer error. It will ASSERT in debug builds.)
377 delete this;
378 }
379 }
380
381 unsigned referencingNodeCount() const { return m_referencingNodeCount; }
382
383 void removedLastRef();
384
385 DocumentIdentifier identifier() const { return m_identifier; }
386
387 using DocumentsMap = HashMap<DocumentIdentifier, Document*>;
388 WEBCORE_EXPORT static DocumentsMap::ValuesIteratorRange allDocuments();
389 WEBCORE_EXPORT static DocumentsMap& allDocumentsMap();
390
391 WEBCORE_EXPORT ElementIdentifier identifierForElement(Element&);
392 WEBCORE_EXPORT Element* searchForElementByIdentifier(const ElementIdentifier&);
393 void identifiedElementWasRemovedFromDocument(Element&);
394
395 MediaQueryMatcher& mediaQueryMatcher();
396
397 using ContainerNode::ref;
398 using ContainerNode::deref;
399 using TreeScope::rootNode;
400
401 bool canContainRangeEndPoint() const final { return true; }
402
403 Element* elementForAccessKey(const String& key);
404 void invalidateAccessKeyCache();
405
406 ExceptionOr<SelectorQuery&> selectorQueryForString(const String&);
407 void clearSelectorQueryCache();
408
409 void setViewportArguments(const ViewportArguments& viewportArguments) { m_viewportArguments = viewportArguments; }
410 WEBCORE_EXPORT ViewportArguments viewportArguments() const;
411
412 OptionSet<DisabledAdaptations> disabledAdaptations() const { return m_disabledAdaptations; }
413#ifndef NDEBUG
414 bool didDispatchViewportPropertiesChanged() const { return m_didDispatchViewportPropertiesChanged; }
415#endif
416
417 void setReferrerPolicy(ReferrerPolicy);
418 ReferrerPolicy referrerPolicy() const { return m_referrerPolicy.valueOr(ReferrerPolicy::NoReferrerWhenDowngrade); }
419
420 WEBCORE_EXPORT DocumentType* doctype() const;
421
422 WEBCORE_EXPORT DOMImplementation& implementation();
423
424 Element* documentElement() const { return m_documentElement.get(); }
425 static ptrdiff_t documentElementMemoryOffset() { return OBJECT_OFFSETOF(Document, m_documentElement); }
426
427 WEBCORE_EXPORT Element* activeElement();
428 WEBCORE_EXPORT bool hasFocus() const;
429
430 bool hasManifest() const;
431
432 WEBCORE_EXPORT ExceptionOr<Ref<Element>> createElementForBindings(const AtomString& tagName);
433 WEBCORE_EXPORT Ref<DocumentFragment> createDocumentFragment();
434 WEBCORE_EXPORT Ref<Text> createTextNode(const String& data);
435 WEBCORE_EXPORT Ref<Comment> createComment(const String& data);
436 WEBCORE_EXPORT ExceptionOr<Ref<CDATASection>> createCDATASection(const String& data);
437 WEBCORE_EXPORT ExceptionOr<Ref<ProcessingInstruction>> createProcessingInstruction(const String& target, const String& data);
438 WEBCORE_EXPORT ExceptionOr<Ref<Attr>> createAttribute(const String& name);
439 WEBCORE_EXPORT ExceptionOr<Ref<Attr>> createAttributeNS(const AtomString& namespaceURI, const String& qualifiedName, bool shouldIgnoreNamespaceChecks = false);
440 WEBCORE_EXPORT ExceptionOr<Ref<Node>> importNode(Node& nodeToImport, bool deep);
441 WEBCORE_EXPORT ExceptionOr<Ref<Element>> createElementNS(const AtomString& namespaceURI, const String& qualifiedName);
442 WEBCORE_EXPORT Ref<Element> createElement(const QualifiedName&, bool createdByParser);
443
444 static CustomElementNameValidationStatus validateCustomElementName(const AtomString&);
445
446 WEBCORE_EXPORT RefPtr<Range> caretRangeFromPoint(int x, int y);
447 RefPtr<Range> caretRangeFromPoint(const LayoutPoint& clientPoint);
448
449 WEBCORE_EXPORT Element* scrollingElementForAPI();
450 Element* scrollingElement();
451
452 enum ReadyState { Loading, Interactive, Complete };
453 ReadyState readyState() const { return m_readyState; }
454
455 WEBCORE_EXPORT String defaultCharsetForLegacyBindings() const;
456
457 String charset() const { return Document::encoding(); }
458 WEBCORE_EXPORT String characterSetWithUTF8Fallback() const;
459 TextEncoding textEncoding() const;
460
461 AtomString encoding() const { return textEncoding().domName(); }
462
463 WEBCORE_EXPORT void setCharset(const String&); // Used by ObjC / GOBject bindings only.
464
465 void setContent(const String&);
466
467 String suggestedMIMEType() const;
468
469 void overrideMIMEType(const String&);
470 WEBCORE_EXPORT String contentType() const;
471
472 String contentLanguage() const { return m_contentLanguage; }
473 void setContentLanguage(const String&);
474
475 String xmlEncoding() const { return m_xmlEncoding; }
476 String xmlVersion() const { return m_xmlVersion; }
477 enum class StandaloneStatus : uint8_t { Unspecified, Standalone, NotStandalone };
478 bool xmlStandalone() const { return m_xmlStandalone == StandaloneStatus::Standalone; }
479 StandaloneStatus xmlStandaloneStatus() const { return m_xmlStandalone; }
480 bool hasXMLDeclaration() const { return m_hasXMLDeclaration; }
481
482 void setXMLEncoding(const String& encoding) { m_xmlEncoding = encoding; } // read-only property, only to be set from XMLDocumentParser
483 WEBCORE_EXPORT ExceptionOr<void> setXMLVersion(const String&);
484 WEBCORE_EXPORT void setXMLStandalone(bool);
485 void setHasXMLDeclaration(bool hasXMLDeclaration) { m_hasXMLDeclaration = hasXMLDeclaration; }
486
487 String documentURI() const { return m_documentURI; }
488 WEBCORE_EXPORT void setDocumentURI(const String&);
489
490 WEBCORE_EXPORT VisibilityState visibilityState() const;
491 void visibilityStateChanged();
492 WEBCORE_EXPORT bool hidden() const;
493
494 void setTimerThrottlingEnabled(bool);
495 bool isTimerThrottlingEnabled() const { return m_isTimerThrottlingEnabled; }
496
497 WEBCORE_EXPORT ExceptionOr<Ref<Node>> adoptNode(Node& source);
498
499 WEBCORE_EXPORT Ref<HTMLCollection> images();
500 WEBCORE_EXPORT Ref<HTMLCollection> embeds();
501 WEBCORE_EXPORT Ref<HTMLCollection> plugins(); // an alias for embeds() required for the JS DOM bindings.
502 WEBCORE_EXPORT Ref<HTMLCollection> applets();
503 WEBCORE_EXPORT Ref<HTMLCollection> links();
504 WEBCORE_EXPORT Ref<HTMLCollection> forms();
505 WEBCORE_EXPORT Ref<HTMLCollection> anchors();
506 WEBCORE_EXPORT Ref<HTMLCollection> scripts();
507 Ref<HTMLCollection> all();
508 Ref<HTMLCollection> allFilteredByName(const AtomString&);
509
510 Ref<HTMLCollection> windowNamedItems(const AtomString&);
511 Ref<HTMLCollection> documentNamedItems(const AtomString&);
512
513 // Other methods (not part of DOM)
514 bool isSynthesized() const { return m_isSynthesized; }
515 bool isHTMLDocument() const { return m_documentClasses & HTMLDocumentClass; }
516 bool isXHTMLDocument() const { return m_documentClasses & XHTMLDocumentClass; }
517 bool isXMLDocument() const { return m_documentClasses & XMLDocumentClass; }
518 bool isImageDocument() const { return m_documentClasses & ImageDocumentClass; }
519 bool isSVGDocument() const { return m_documentClasses & SVGDocumentClass; }
520 bool isPluginDocument() const { return m_documentClasses & PluginDocumentClass; }
521 bool isMediaDocument() const { return m_documentClasses & MediaDocumentClass; }
522 bool isTextDocument() const { return m_documentClasses & TextDocumentClass; }
523 bool hasSVGRootNode() const;
524 virtual bool isFrameSet() const { return false; }
525
526 static ptrdiff_t documentClassesMemoryOffset() { return OBJECT_OFFSETOF(Document, m_documentClasses); }
527 static uint32_t isHTMLDocumentClassFlag() { return HTMLDocumentClass; }
528
529 bool isSrcdocDocument() const { return m_isSrcdocDocument; }
530
531 bool sawElementsInKnownNamespaces() const { return m_sawElementsInKnownNamespaces; }
532
533 StyleResolver& userAgentShadowTreeStyleResolver();
534
535 CSSFontSelector& fontSelector() { return m_fontSelector; }
536
537 WEBCORE_EXPORT bool haveStylesheetsLoaded() const;
538 bool isIgnoringPendingStylesheets() const { return m_ignorePendingStylesheets; }
539
540 WEBCORE_EXPORT StyleSheetList& styleSheets();
541
542 Style::Scope& styleScope() { return *m_styleScope; }
543 const Style::Scope& styleScope() const { return *m_styleScope; }
544 ExtensionStyleSheets& extensionStyleSheets() { return *m_extensionStyleSheets; }
545 const ExtensionStyleSheets& extensionStyleSheets() const { return *m_extensionStyleSheets; }
546
547 bool gotoAnchorNeededAfterStylesheetsLoad() { return m_gotoAnchorNeededAfterStylesheetsLoad; }
548 void setGotoAnchorNeededAfterStylesheetsLoad(bool b) { m_gotoAnchorNeededAfterStylesheetsLoad = b; }
549
550 void evaluateMediaQueryList();
551
552 FormController& formController();
553 Vector<String> formElementsState() const;
554 void setStateForNewFormElements(const Vector<String>&);
555
556 WEBCORE_EXPORT FrameView* view() const; // Can be null.
557 WEBCORE_EXPORT Page* page() const; // Can be null.
558 const Settings& settings() const { return m_settings.get(); }
559 Settings& mutableSettings() { return m_settings.get(); }
560 EditingBehavior editingBehavior() const;
561
562 const Quirks& quirks() const { return m_quirks; }
563
564 float deviceScaleFactor() const;
565
566 WEBCORE_EXPORT bool useSystemAppearance() const;
567 WEBCORE_EXPORT bool useInactiveAppearance() const;
568 WEBCORE_EXPORT bool useDarkAppearance(const RenderStyle*) const;
569
570 OptionSet<StyleColor::Options> styleColorOptions(const RenderStyle*) const;
571
572 WEBCORE_EXPORT Ref<Range> createRange();
573
574 // The last bool parameter is for ObjC bindings.
575 WEBCORE_EXPORT Ref<NodeIterator> createNodeIterator(Node& root, unsigned long whatToShow = 0xFFFFFFFF, RefPtr<NodeFilter>&& = nullptr, bool = false);
576
577 // The last bool parameter is for ObjC bindings.
578 WEBCORE_EXPORT Ref<TreeWalker> createTreeWalker(Node& root, unsigned long whatToShow = 0xFFFFFFFF, RefPtr<NodeFilter>&& = nullptr, bool = false);
579
580 // Special support for editing
581 WEBCORE_EXPORT Ref<CSSStyleDeclaration> createCSSStyleDeclaration();
582 Ref<Text> createEditingTextNode(const String&);
583
584 enum class ResolveStyleType { Normal, Rebuild };
585 void resolveStyle(ResolveStyleType = ResolveStyleType::Normal);
586 WEBCORE_EXPORT bool updateStyleIfNeeded();
587 bool needsStyleRecalc() const;
588 unsigned lastStyleUpdateSizeForTesting() const { return m_lastStyleUpdateSizeForTesting; }
589
590 WEBCORE_EXPORT void updateLayout();
591
592 // updateLayoutIgnorePendingStylesheets() forces layout even if we are waiting for pending stylesheet loads,
593 // so calling this may cause a flash of unstyled content (FOUC).
594 enum class RunPostLayoutTasks { Asynchronously, Synchronously };
595 WEBCORE_EXPORT void updateLayoutIgnorePendingStylesheets(RunPostLayoutTasks = RunPostLayoutTasks::Asynchronously);
596
597 std::unique_ptr<RenderStyle> styleForElementIgnoringPendingStylesheets(Element&, const RenderStyle* parentStyle, PseudoId = PseudoId::None);
598
599 // Returns true if page box (margin boxes and page borders) is visible.
600 WEBCORE_EXPORT bool isPageBoxVisible(int pageIndex);
601
602 // Returns the preferred page size and margins in pixels, assuming 96
603 // pixels per inch. pageSize, marginTop, marginRight, marginBottom,
604 // marginLeft must be initialized to the default values that are used if
605 // auto is specified.
606 WEBCORE_EXPORT void pageSizeAndMarginsInPixels(int pageIndex, IntSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft);
607
608 CachedResourceLoader& cachedResourceLoader() { return m_cachedResourceLoader; }
609
610 void didBecomeCurrentDocumentInFrame();
611 void destroyRenderTree();
612 void prepareForDestruction();
613
614 // Override ScriptExecutionContext methods to do additional work
615 WEBCORE_EXPORT bool shouldBypassMainWorldContentSecurityPolicy() const final;
616 void suspendActiveDOMObjects(ReasonForSuspension) final;
617 void resumeActiveDOMObjects(ReasonForSuspension) final;
618 void stopActiveDOMObjects() final;
619
620 void suspendDeviceMotionAndOrientationUpdates();
621 void resumeDeviceMotionAndOrientationUpdates();
622
623 RenderView* renderView() const { return m_renderView.get(); }
624
625 bool renderTreeBeingDestroyed() const { return m_renderTreeBeingDestroyed; }
626 bool hasLivingRenderTree() const { return renderView() && !renderTreeBeingDestroyed(); }
627
628 bool updateLayoutIfDimensionsOutOfDate(Element&, DimensionsCheck = AllDimensionsCheck);
629
630 AXObjectCache* existingAXObjectCache() const;
631 WEBCORE_EXPORT AXObjectCache* axObjectCache() const;
632 void clearAXObjectCache();
633
634 Optional<PageIdentifier> pageID() const;
635 // to get visually ordered hebrew and arabic pages right
636 void setVisuallyOrdered();
637 bool visuallyOrdered() const { return m_visuallyOrdered; }
638
639 WEBCORE_EXPORT DocumentLoader* loader() const;
640
641 WEBCORE_EXPORT ExceptionOr<RefPtr<WindowProxy>> openForBindings(DOMWindow& activeWindow, DOMWindow& firstDOMWindow, const String& url, const AtomString& name, const String& features);
642 WEBCORE_EXPORT ExceptionOr<Document&> openForBindings(Document* responsibleDocument, const String&, const String&);
643
644 // FIXME: We should rename this at some point and give back the name 'open' to the HTML specified ones.
645 WEBCORE_EXPORT ExceptionOr<void> open(Document* responsibleDocument = nullptr);
646 void implicitOpen();
647
648 WEBCORE_EXPORT ExceptionOr<void> closeForBindings();
649
650 // FIXME: We should rename this at some point and give back the name 'close' to the HTML specified one.
651 WEBCORE_EXPORT void close();
652 // In some situations (see the code), we ignore document.close().
653 // explicitClose() bypass these checks and actually tries to close the
654 // input stream.
655 void explicitClose();
656 // implicitClose() actually does the work of closing the input stream.
657 void implicitClose();
658
659 void cancelParsing();
660
661 ExceptionOr<void> write(Document* responsibleDocument, SegmentedString&&);
662 WEBCORE_EXPORT ExceptionOr<void> write(Document* responsibleDocument, Vector<String>&&);
663 WEBCORE_EXPORT ExceptionOr<void> writeln(Document* responsibleDocument, Vector<String>&&);
664
665 bool wellFormed() const { return m_wellFormed; }
666
667 const URL& url() const final { return m_url; }
668 void setURL(const URL&);
669 const URL& urlForBindings() const { return m_url.isEmpty() ? WTF::blankURL() : m_url; }
670
671 // To understand how these concepts relate to one another, please see the
672 // comments surrounding their declaration.
673 const URL& baseURL() const { return m_baseURL; }
674 void setBaseURLOverride(const URL&);
675 const URL& baseURLOverride() const { return m_baseURLOverride; }
676 const URL& baseElementURL() const { return m_baseElementURL; }
677 const String& baseTarget() const { return m_baseTarget; }
678 void processBaseElement();
679
680 WEBCORE_EXPORT URL completeURL(const String&) const final;
681 URL completeURL(const String&, const URL& baseURLOverride) const;
682 WEBCORE_EXPORT PAL::SessionID sessionID() const final;
683
684 String userAgent(const URL&) const final;
685
686 void disableEval(const String& errorMessage) final;
687 void disableWebAssembly(const String& errorMessage) final;
688
689#if ENABLE(INDEXED_DATABASE)
690 IDBClient::IDBConnectionProxy* idbConnectionProxy() final;
691#endif
692 SocketProvider* socketProvider() final;
693
694 bool canNavigate(Frame* targetFrame, const URL& destinationURL = URL());
695
696 bool usesStyleBasedEditability() const;
697 void setHasElementUsingStyleBasedEditability();
698
699 virtual Ref<DocumentParser> createParser();
700 DocumentParser* parser() const { return m_parser.get(); }
701 ScriptableDocumentParser* scriptableDocumentParser() const;
702
703 bool printing() const { return m_printing; }
704 void setPrinting(bool p) { m_printing = p; }
705
706 bool paginatedForScreen() const { return m_paginatedForScreen; }
707 void setPaginatedForScreen(bool p) { m_paginatedForScreen = p; }
708
709 bool paginated() const { return printing() || paginatedForScreen(); }
710
711 void setCompatibilityMode(DocumentCompatibilityMode);
712 void lockCompatibilityMode() { m_compatibilityModeLocked = true; }
713 static ptrdiff_t compatibilityModeMemoryOffset() { return OBJECT_OFFSETOF(Document, m_compatibilityMode); }
714
715 WEBCORE_EXPORT String compatMode() const;
716
717 bool inQuirksMode() const { return m_compatibilityMode == DocumentCompatibilityMode::QuirksMode; }
718 bool inLimitedQuirksMode() const { return m_compatibilityMode == DocumentCompatibilityMode::LimitedQuirksMode; }
719 bool inNoQuirksMode() const { return m_compatibilityMode == DocumentCompatibilityMode::NoQuirksMode; }
720
721 void setReadyState(ReadyState);
722 void setParsing(bool);
723 bool parsing() const { return m_bParsing; }
724 Seconds minimumLayoutDelay();
725
726 bool shouldScheduleLayout();
727 bool isLayoutTimerActive();
728 Seconds timeSinceDocumentCreation() const;
729
730 void setTextColor(const Color& color) { m_textColor = color; }
731 const Color& textColor() const { return m_textColor; }
732
733 const Color& linkColor() const { return m_linkColor; }
734 const Color& visitedLinkColor() const { return m_visitedLinkColor; }
735 const Color& activeLinkColor() const { return m_activeLinkColor; }
736 void setLinkColor(const Color& c) { m_linkColor = c; }
737 void setVisitedLinkColor(const Color& c) { m_visitedLinkColor = c; }
738 void setActiveLinkColor(const Color& c) { m_activeLinkColor = c; }
739 void resetLinkColor();
740 void resetVisitedLinkColor();
741 void resetActiveLinkColor();
742 VisitedLinkState& visitedLinkState() const { return *m_visitedLinkState; }
743
744 MouseEventWithHitTestResults prepareMouseEvent(const HitTestRequest&, const LayoutPoint&, const PlatformMouseEvent&);
745
746 enum class FocusRemovalEventsMode { Dispatch, DoNotDispatch };
747 WEBCORE_EXPORT bool setFocusedElement(Element*, FocusDirection = FocusDirectionNone,
748 FocusRemovalEventsMode = FocusRemovalEventsMode::Dispatch);
749 Element* focusedElement() const { return m_focusedElement.get(); }
750 UserActionElementSet& userActionElements() { return m_userActionElements; }
751 const UserActionElementSet& userActionElements() const { return m_userActionElements; }
752
753 void setFocusNavigationStartingNode(Node*);
754 Element* focusNavigationStartingNode(FocusDirection) const;
755
756 enum class NodeRemoval { Node, ChildrenOfNode };
757 void adjustFocusedNodeOnNodeRemoval(Node&, NodeRemoval = NodeRemoval::Node);
758 void adjustFocusNavigationNodeOnNodeRemoval(Node&, NodeRemoval = NodeRemoval::Node);
759
760 void hoveredElementDidDetach(Element&);
761 void elementInActiveChainDidDetach(Element&);
762
763 void updateHoverActiveState(const HitTestRequest&, Element*);
764
765 // Updates for :target (CSS3 selector).
766 void setCSSTarget(Element*);
767 Element* cssTarget() const { return m_cssTarget; }
768 static ptrdiff_t cssTargetMemoryOffset() { return OBJECT_OFFSETOF(Document, m_cssTarget); }
769
770 WEBCORE_EXPORT void scheduleFullStyleRebuild();
771 void scheduleStyleRecalc();
772 void unscheduleStyleRecalc();
773 bool hasPendingStyleRecalc() const;
774 bool hasPendingFullStyleRebuild() const;
775
776 void registerNodeListForInvalidation(LiveNodeList&);
777 void unregisterNodeListForInvalidation(LiveNodeList&);
778 WEBCORE_EXPORT void registerCollection(HTMLCollection&);
779 void unregisterCollection(HTMLCollection&);
780 void collectionCachedIdNameMap(const HTMLCollection&);
781 void collectionWillClearIdNameMap(const HTMLCollection&);
782 bool shouldInvalidateNodeListAndCollectionCaches() const;
783 bool shouldInvalidateNodeListAndCollectionCachesForAttribute(const QualifiedName& attrName) const;
784
785 template <typename InvalidationFunction>
786 void invalidateNodeListAndCollectionCaches(InvalidationFunction);
787
788 void attachNodeIterator(NodeIterator&);
789 void detachNodeIterator(NodeIterator&);
790 void moveNodeIteratorsToNewDocument(Node& node, Document& newDocument)
791 {
792 if (!m_nodeIterators.isEmpty())
793 moveNodeIteratorsToNewDocumentSlowCase(node, newDocument);
794 }
795
796 void attachRange(Range&);
797 void detachRange(Range&);
798
799 void updateRangesAfterChildrenChanged(ContainerNode&);
800 // nodeChildrenWillBeRemoved is used when removing all node children at once.
801 void nodeChildrenWillBeRemoved(ContainerNode&);
802 // nodeWillBeRemoved is only safe when removing one node at a time.
803 void nodeWillBeRemoved(Node&);
804
805 enum class AcceptChildOperation { Replace, InsertOrAdd };
806 bool canAcceptChild(const Node& newChild, const Node* refChild, AcceptChildOperation) const;
807
808 void textInserted(Node&, unsigned offset, unsigned length);
809 void textRemoved(Node&, unsigned offset, unsigned length);
810 void textNodesMerged(Text& oldNode, unsigned offset);
811 void textNodeSplit(Text& oldNode);
812
813 void createDOMWindow();
814 void takeDOMWindowFrom(Document&);
815
816 DOMWindow* domWindow() const { return m_domWindow.get(); }
817 // In DOM Level 2, the Document's DOMWindow is called the defaultView.
818 WEBCORE_EXPORT WindowProxy* windowProxy() const;
819
820 bool hasBrowsingContext() const { return !!frame(); }
821
822 Document& contextDocument() const;
823 void setContextDocument(Document& document) { m_contextDocument = makeWeakPtr(document); }
824
825 // Helper functions for forwarding DOMWindow event related tasks to the DOMWindow if it exists.
826 void setWindowAttributeEventListener(const AtomString& eventType, const QualifiedName& attributeName, const AtomString& value, DOMWrapperWorld&);
827 void setWindowAttributeEventListener(const AtomString& eventType, RefPtr<EventListener>&&, DOMWrapperWorld&);
828 EventListener* getWindowAttributeEventListener(const AtomString& eventType, DOMWrapperWorld&);
829 WEBCORE_EXPORT void dispatchWindowEvent(Event&, EventTarget* = nullptr);
830 void dispatchWindowLoadEvent();
831
832 WEBCORE_EXPORT ExceptionOr<Ref<Event>> createEvent(const String& eventType);
833
834 // keep track of what types of event listeners are registered, so we don't
835 // dispatch events unnecessarily
836 enum ListenerType {
837 DOMSUBTREEMODIFIED_LISTENER = 1,
838 DOMNODEINSERTED_LISTENER = 1 << 1,
839 DOMNODEREMOVED_LISTENER = 1 << 2,
840 DOMNODEREMOVEDFROMDOCUMENT_LISTENER = 1 << 3,
841 DOMNODEINSERTEDINTODOCUMENT_LISTENER = 1 << 4,
842 DOMCHARACTERDATAMODIFIED_LISTENER = 1 << 5,
843 OVERFLOWCHANGED_LISTENER = 1 << 6,
844 ANIMATIONEND_LISTENER = 1 << 7,
845 ANIMATIONSTART_LISTENER = 1 << 8,
846 ANIMATIONITERATION_LISTENER = 1 << 9,
847 TRANSITIONEND_LISTENER = 1 << 10,
848 BEFORELOAD_LISTENER = 1 << 11,
849 SCROLL_LISTENER = 1 << 12,
850 FORCEWILLBEGIN_LISTENER = 1 << 13,
851 FORCECHANGED_LISTENER = 1 << 14,
852 FORCEDOWN_LISTENER = 1 << 15,
853 FORCEUP_LISTENER = 1 << 16,
854 RESIZE_LISTENER = 1 << 17
855 };
856
857 bool hasListenerType(ListenerType listenerType) const { return (m_listenerTypes & listenerType); }
858 bool hasListenerTypeForEventType(PlatformEvent::Type) const;
859 void addListenerTypeIfNeeded(const AtomString& eventType);
860
861 bool hasMutationObserversOfType(MutationObserver::MutationType type) const
862 {
863 return m_mutationObserverTypes & type;
864 }
865 bool hasMutationObservers() const { return m_mutationObserverTypes; }
866 void addMutationObserverTypes(MutationObserverOptions types) { m_mutationObserverTypes |= types; }
867
868 CSSStyleDeclaration* getOverrideStyle(Element*, const String&) { return nullptr; }
869
870 // Handles an HTTP header equivalent set by a meta tag using <meta http-equiv="..." content="...">. This is called
871 // when a meta tag is encountered during document parsing, and also when a script dynamically changes or adds a meta
872 // tag. This enables scripts to use meta tags to perform refreshes and set expiry dates in addition to them being
873 // specified in an HTML file.
874 void processHttpEquiv(const String& equiv, const String& content, bool isInDocumentHead);
875
876#if PLATFORM(IOS_FAMILY)
877 void processFormatDetection(const String&);
878
879 // Called when <meta name="apple-mobile-web-app-orientations"> changes.
880 void processWebAppOrientations();
881
882 WEBCORE_EXPORT ContentChangeObserver& contentChangeObserver();
883#endif
884
885 void processViewport(const String& features, ViewportArguments::Type origin);
886 void processDisabledAdaptations(const String& adaptations);
887 void updateViewportArguments();
888 void processReferrerPolicy(const String& policy, ReferrerPolicySource);
889
890#if ENABLE(DARK_MODE_CSS)
891 void processColorScheme(const String& colorScheme);
892#endif
893
894 // Returns the owning element in the parent document.
895 // Returns nullptr if this is the top level document.
896 HTMLFrameOwnerElement* ownerElement() const;
897
898 // Used by DOM bindings; no direction known.
899 const String& title() const { return m_title.string; }
900 WEBCORE_EXPORT void setTitle(const String&);
901
902 WEBCORE_EXPORT const AtomString& dir() const;
903 WEBCORE_EXPORT void setDir(const AtomString&);
904
905 void titleElementAdded(Element& titleElement);
906 void titleElementRemoved(Element& titleElement);
907 void titleElementTextChanged(Element& titleElement);
908
909 WEBCORE_EXPORT ExceptionOr<String> cookie();
910 WEBCORE_EXPORT ExceptionOr<void> setCookie(const String&);
911
912 WEBCORE_EXPORT String referrer() const;
913
914 WEBCORE_EXPORT String origin() const final;
915
916 WEBCORE_EXPORT String domain() const;
917 ExceptionOr<void> setDomain(const String& newDomain);
918
919 void overrideLastModified(const Optional<WallTime>&);
920 WEBCORE_EXPORT String lastModified() const;
921
922 // The cookieURL is used to query the cookie database for this document's
923 // cookies. For example, if the cookie URL is http://example.com, we'll
924 // use the non-Secure cookies for example.com when computing
925 // document.cookie.
926 //
927 // Q: How is the cookieURL different from the document's URL?
928 // A: The two URLs are the same almost all the time. However, if one
929 // document inherits the security context of another document, it
930 // inherits its cookieURL but not its URL.
931 //
932 const URL& cookieURL() const { return m_cookieURL; }
933 void setCookieURL(const URL&);
934
935 // The firstPartyForCookies is used to compute whether this document
936 // appears in a "third-party" context for the purpose of third-party
937 // cookie blocking. The document is in a third-party context if the
938 // cookieURL and the firstPartyForCookies are from different hosts.
939 //
940 // Note: Some ports (including possibly Apple's) only consider the
941 // document in a third-party context if the cookieURL and the
942 // firstPartyForCookies have a different registry-controlled
943 // domain.
944 //
945 const URL& firstPartyForCookies() const { return m_firstPartyForCookies; }
946 void setFirstPartyForCookies(const URL& url) { m_firstPartyForCookies = url; }
947
948 bool isFullyActive() const;
949
950 // The full URL corresponding to the "site for cookies" in the Same-Site Cookies spec.,
951 // <https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00>. It is either
952 // the URL of the top-level document or the null URL depending on whether the registrable
953 // domain of this document's URL matches the registrable domain of its parent's/opener's
954 // URL. For the top-level document, it is set to the document's URL.
955 const URL& siteForCookies() const { return m_siteForCookies; }
956 void setSiteForCookies(const URL& url) { m_siteForCookies = url; }
957
958 // The following implements the rule from HTML 4 for what valid names are.
959 // To get this right for all the XML cases, we probably have to improve this or move it
960 // and make it sensitive to the type of document.
961 static bool isValidName(const String&);
962
963 // The following breaks a qualified name into a prefix and a local name.
964 // It also does a validity check, and returns an error if the qualified name is invalid.
965 static ExceptionOr<std::pair<AtomString, AtomString>> parseQualifiedName(const String& qualifiedName);
966 static ExceptionOr<QualifiedName> parseQualifiedName(const AtomString& namespaceURI, const String& qualifiedName);
967
968 // Checks to make sure prefix and namespace do not conflict (per DOM Core 3)
969 static bool hasValidNamespaceForElements(const QualifiedName&);
970 static bool hasValidNamespaceForAttributes(const QualifiedName&);
971
972 // This is the "HTML body element" as defined by CSSOM View spec, the first body child of the
973 // document element. See http://dev.w3.org/csswg/cssom-view/#the-html-body-element.
974 WEBCORE_EXPORT HTMLBodyElement* body() const;
975
976 // This is the "body element" as defined by HTML5, the first body or frameset child of the
977 // document element. See https://html.spec.whatwg.org/multipage/dom.html#the-body-element-2.
978 WEBCORE_EXPORT HTMLElement* bodyOrFrameset() const;
979 WEBCORE_EXPORT ExceptionOr<void> setBodyOrFrameset(RefPtr<HTMLElement>&&);
980
981 Location* location() const;
982
983 WEBCORE_EXPORT HTMLHeadElement* head();
984
985 DocumentMarkerController& markers() const { return *m_markers; }
986
987 WEBCORE_EXPORT bool execCommand(const String& command, bool userInterface = false, const String& value = String());
988 WEBCORE_EXPORT bool queryCommandEnabled(const String& command);
989 WEBCORE_EXPORT bool queryCommandIndeterm(const String& command);
990 WEBCORE_EXPORT bool queryCommandState(const String& command);
991 WEBCORE_EXPORT bool queryCommandSupported(const String& command);
992 WEBCORE_EXPORT String queryCommandValue(const String& command);
993
994 UndoManager& undoManager() const { return m_undoManager.get(); }
995
996 // designMode support
997 enum InheritedBool { off = false, on = true, inherit };
998 void setDesignMode(InheritedBool value);
999 InheritedBool getDesignMode() const;
1000 bool inDesignMode() const;
1001 WEBCORE_EXPORT String designMode() const;
1002 WEBCORE_EXPORT void setDesignMode(const String&);
1003
1004 Document* parentDocument() const;
1005 WEBCORE_EXPORT Document& topDocument() const;
1006
1007 ScriptRunner& scriptRunner() { return *m_scriptRunner; }
1008 ScriptModuleLoader& moduleLoader() { return *m_moduleLoader; }
1009
1010 HTMLScriptElement* currentScript() const { return !m_currentScriptStack.isEmpty() ? m_currentScriptStack.last().get() : nullptr; }
1011 void pushCurrentScript(HTMLScriptElement*);
1012 void popCurrentScript();
1013
1014 bool shouldDeferAsynchronousScriptsUntilParsingFinishes() const;
1015
1016#if ENABLE(XSLT)
1017 void scheduleToApplyXSLTransforms();
1018 void applyPendingXSLTransformsNowIfScheduled();
1019 RefPtr<Document> transformSourceDocument() { return m_transformSourceDocument; }
1020 void setTransformSourceDocument(Document* document) { m_transformSourceDocument = document; }
1021
1022 void setTransformSource(std::unique_ptr<TransformSource>);
1023 TransformSource* transformSource() const { return m_transformSource.get(); }
1024#endif
1025
1026 void incDOMTreeVersion() { m_domTreeVersion = ++s_globalTreeVersion; }
1027 uint64_t domTreeVersion() const { return m_domTreeVersion; }
1028
1029 WEBCORE_EXPORT String originIdentifierForPasteboard();
1030
1031 // XPathEvaluator methods
1032 WEBCORE_EXPORT ExceptionOr<Ref<XPathExpression>> createExpression(const String& expression, RefPtr<XPathNSResolver>&&);
1033 WEBCORE_EXPORT Ref<XPathNSResolver> createNSResolver(Node* nodeResolver);
1034 WEBCORE_EXPORT ExceptionOr<Ref<XPathResult>> evaluate(const String& expression, Node* contextNode, RefPtr<XPathNSResolver>&&, unsigned short type, XPathResult*);
1035
1036 bool hasNodesWithNonFinalStyle() const { return m_hasNodesWithNonFinalStyle; }
1037 void setHasNodesWithNonFinalStyle() { m_hasNodesWithNonFinalStyle = true; }
1038 bool hasNodesWithMissingStyle() const { return m_hasNodesWithMissingStyle; }
1039 void setHasNodesWithMissingStyle() { m_hasNodesWithMissingStyle = true; }
1040
1041 // Extension for manipulating canvas drawing contexts for use in CSS
1042 Optional<RenderingContext> getCSSCanvasContext(const String& type, const String& name, int width, int height);
1043 HTMLCanvasElement* getCSSCanvasElement(const String& name);
1044 String nameForCSSCanvasElement(const HTMLCanvasElement&) const;
1045
1046 bool isDNSPrefetchEnabled() const { return m_isDNSPrefetchEnabled; }
1047 void parseDNSPrefetchControlHeader(const String&);
1048
1049 WEBCORE_EXPORT void postTask(Task&&) final; // Executes the task on context's thread asynchronously.
1050
1051 ScriptedAnimationController* scriptedAnimationController() { return m_scriptedAnimationController.get(); }
1052 void suspendScriptedAnimationControllerCallbacks();
1053 void resumeScriptedAnimationControllerCallbacks();
1054
1055 void updateAnimationsAndSendEvents(DOMHighResTimeStamp timestamp);
1056 void serviceRequestAnimationFrameCallbacks(DOMHighResTimeStamp timestamp);
1057
1058 void windowScreenDidChange(PlatformDisplayID);
1059
1060 void finishedParsing();
1061
1062 enum PageCacheState { NotInPageCache, AboutToEnterPageCache, InPageCache };
1063
1064 PageCacheState pageCacheState() const { return m_pageCacheState; }
1065 void setPageCacheState(PageCacheState);
1066
1067 void registerForDocumentSuspensionCallbacks(Element&);
1068 void unregisterForDocumentSuspensionCallbacks(Element&);
1069
1070 void documentWillBecomeInactive();
1071 void suspend(ReasonForSuspension);
1072 void resume(ReasonForSuspension);
1073
1074 void registerForMediaVolumeCallbacks(Element&);
1075 void unregisterForMediaVolumeCallbacks(Element&);
1076 void mediaVolumeDidChange();
1077
1078 bool audioPlaybackRequiresUserGesture() const;
1079 bool videoPlaybackRequiresUserGesture() const;
1080
1081#if ENABLE(MEDIA_SESSION)
1082 MediaSession& defaultMediaSession();
1083#endif
1084
1085 void registerForPrivateBrowsingStateChangedCallbacks(Element&);
1086 void unregisterForPrivateBrowsingStateChangedCallbacks(Element&);
1087 void storageBlockingStateDidChange();
1088 void privateBrowsingStateDidChange();
1089
1090#if ENABLE(VIDEO_TRACK)
1091 void registerForCaptionPreferencesChangedCallbacks(Element&);
1092 void unregisterForCaptionPreferencesChangedCallbacks(Element&);
1093 void captionPreferencesChanged();
1094#endif
1095
1096#if ENABLE(MEDIA_CONTROLS_SCRIPT)
1097 void registerForPageScaleFactorChangedCallbacks(HTMLMediaElement&);
1098 void unregisterForPageScaleFactorChangedCallbacks(HTMLMediaElement&);
1099 void pageScaleFactorChangedAndStable();
1100 void registerForUserInterfaceLayoutDirectionChangedCallbacks(HTMLMediaElement&);
1101 void unregisterForUserInterfaceLayoutDirectionChangedCallbacks(HTMLMediaElement&);
1102 void userInterfaceLayoutDirectionChanged();
1103#endif
1104
1105 void registerForVisibilityStateChangedCallbacks(VisibilityChangeClient&);
1106 void unregisterForVisibilityStateChangedCallbacks(VisibilityChangeClient&);
1107
1108#if ENABLE(VIDEO)
1109 void registerForAllowsMediaDocumentInlinePlaybackChangedCallbacks(HTMLMediaElement&);
1110 void unregisterForAllowsMediaDocumentInlinePlaybackChangedCallbacks(HTMLMediaElement&);
1111 void allowsMediaDocumentInlinePlaybackChanged();
1112
1113 void stopAllMediaPlayback();
1114 void suspendAllMediaPlayback();
1115 void resumeAllMediaPlayback();
1116 void suspendAllMediaBuffering();
1117 void resumeAllMediaBuffering();
1118#endif
1119
1120 WEBCORE_EXPORT void setShouldCreateRenderers(bool);
1121 bool shouldCreateRenderers();
1122
1123 void setDecoder(RefPtr<TextResourceDecoder>&&);
1124 TextResourceDecoder* decoder() const { return m_decoder.get(); }
1125
1126 WEBCORE_EXPORT String displayStringModifiedByEncoding(const String&) const;
1127
1128 void invalidateRenderingDependentRegions();
1129
1130 void removeAllEventListeners() final;
1131
1132 WEBCORE_EXPORT const SVGDocumentExtensions* svgExtensions();
1133 WEBCORE_EXPORT SVGDocumentExtensions& accessSVGExtensions();
1134
1135 void addSVGUseElement(SVGUseElement&);
1136 void removeSVGUseElement(SVGUseElement&);
1137 HashSet<SVGUseElement*> const svgUseElements() const { return m_svgUseElements; }
1138
1139 void initSecurityContext();
1140 void initContentSecurityPolicy(ContentSecurityPolicy* previousPolicy);
1141
1142 void updateURLForPushOrReplaceState(const URL&);
1143 void statePopped(Ref<SerializedScriptValue>&&);
1144
1145 bool processingLoadEvent() const { return m_processingLoadEvent; }
1146 bool loadEventFinished() const { return m_loadEventFinished; }
1147
1148 bool isContextThread() const final;
1149 bool isSecureContext() const final;
1150 bool isJSExecutionForbidden() const final { return false; }
1151
1152 void enqueueWindowEvent(Ref<Event>&&);
1153 void enqueueDocumentEvent(Ref<Event>&&);
1154 void enqueueOverflowEvent(Ref<Event>&&);
1155 void dispatchPageshowEvent(PageshowEventPersistence);
1156 WEBCORE_EXPORT void enqueueSecurityPolicyViolationEvent(SecurityPolicyViolationEvent::Init&&);
1157 void enqueueHashchangeEvent(const String& oldURL, const String& newURL);
1158 void dispatchPopstateEvent(RefPtr<SerializedScriptValue>&& stateObject);
1159 DocumentEventQueue& eventQueue() const final { return m_eventQueue; }
1160
1161 WEBCORE_EXPORT void addMediaCanStartListener(MediaCanStartListener&);
1162 WEBCORE_EXPORT void removeMediaCanStartListener(MediaCanStartListener&);
1163 MediaCanStartListener* takeAnyMediaCanStartListener();
1164
1165#if ENABLE(FULLSCREEN_API)
1166 FullscreenManager& fullscreenManager() { return m_fullscreenManager; }
1167 const FullscreenManager& fullscreenManager() const { return m_fullscreenManager; }
1168#endif
1169
1170#if ENABLE(POINTER_LOCK)
1171 WEBCORE_EXPORT void exitPointerLock();
1172#endif
1173
1174 // Used to allow element that loads data without going through a FrameLoader to delay the 'load' event.
1175 void incrementLoadEventDelayCount() { ++m_loadEventDelayCount; }
1176 void decrementLoadEventDelayCount();
1177 bool isDelayingLoadEvent() const { return m_loadEventDelayCount; }
1178 void checkCompleted();
1179
1180#if ENABLE(IOS_TOUCH_EVENTS)
1181#include <WebKitAdditions/DocumentIOS.h>
1182#endif
1183
1184#if ENABLE(DEVICE_ORIENTATION)
1185#if PLATFORM(IOS_FAMILY)
1186 DeviceMotionController& deviceMotionController() const;
1187 DeviceOrientationController& deviceOrientationController() const;
1188 WEBCORE_EXPORT void simulateDeviceOrientationChange(double alpha, double beta, double gamma);
1189#endif
1190
1191 DeviceOrientationAndMotionAccessController& deviceOrientationAndMotionAccessController();
1192#endif // ENABLE(DEVICE_ORIENTATION)
1193
1194 const DocumentTiming& timing() const { return m_documentTiming; }
1195
1196 WEBCORE_EXPORT double monotonicTimestamp() const;
1197
1198 int requestAnimationFrame(Ref<RequestAnimationFrameCallback>&&);
1199 void cancelAnimationFrame(int id);
1200
1201 EventTarget* errorEventTarget() final;
1202 void logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, RefPtr<Inspector::ScriptCallStack>&&) final;
1203
1204 void initDNSPrefetch();
1205
1206 void didAddWheelEventHandler(Node&);
1207 void didRemoveWheelEventHandler(Node&, EventHandlerRemoval = EventHandlerRemoval::One);
1208
1209 MonotonicTime lastHandledUserGestureTimestamp() const { return m_lastHandledUserGestureTimestamp; }
1210 bool hasHadUserInteraction() const { return static_cast<bool>(m_lastHandledUserGestureTimestamp); }
1211 void updateLastHandledUserGestureTimestamp(MonotonicTime);
1212 bool processingUserGestureForMedia() const;
1213 void userActivatedMediaFinishedPlaying() { m_userActivatedMediaFinishedPlayingTimestamp = MonotonicTime::now(); }
1214
1215 void setUserDidInteractWithPage(bool userDidInteractWithPage) { ASSERT(&topDocument() == this); m_userDidInteractWithPage = userDidInteractWithPage; }
1216 bool userDidInteractWithPage() const { ASSERT(&topDocument() == this); return m_userDidInteractWithPage; }
1217
1218 // Used for testing. Count handlers in the main document, and one per frame which contains handlers.
1219 WEBCORE_EXPORT unsigned wheelEventHandlerCount() const;
1220 WEBCORE_EXPORT unsigned touchEventHandlerCount() const;
1221
1222 WEBCORE_EXPORT void startTrackingStyleRecalcs();
1223 WEBCORE_EXPORT unsigned styleRecalcCount() const;
1224
1225#if ENABLE(TOUCH_EVENTS)
1226 bool hasTouchEventHandlers() const { return (m_touchEventTargets.get()) ? m_touchEventTargets->size() : false; }
1227 bool touchEventTargetsContain(Node& node) const { return m_touchEventTargets ? m_touchEventTargets->contains(&node) : false; }
1228#else
1229 bool hasTouchEventHandlers() const { return false; }
1230 bool touchEventTargetsContain(Node&) const { return false; }
1231#endif
1232#if PLATFORM(IOS_FAMILY) && ENABLE(POINTER_EVENTS)
1233 void updateTouchActionElements(Element&, const RenderStyle&);
1234 const HashSet<RefPtr<Element>>* touchActionElements() const { return m_touchActionElements.get(); }
1235#endif
1236
1237 void didAddTouchEventHandler(Node&);
1238 void didRemoveTouchEventHandler(Node&, EventHandlerRemoval = EventHandlerRemoval::One);
1239
1240 void didRemoveEventTargetNode(Node&);
1241
1242 const EventTargetSet* touchEventTargets() const
1243 {
1244#if ENABLE(TOUCH_EVENTS)
1245 return m_touchEventTargets.get();
1246#else
1247 return nullptr;
1248#endif
1249 }
1250
1251 const EventTargetSet* wheelEventTargets() const { return m_wheelEventTargets.get(); }
1252
1253 typedef std::pair<Region, bool> RegionFixedPair;
1254 RegionFixedPair absoluteEventRegionForNode(Node&);
1255 RegionFixedPair absoluteRegionForEventTargets(const EventTargetSet*);
1256
1257 LayoutRect absoluteEventHandlerBounds(bool&) final;
1258
1259 bool visualUpdatesAllowed() const { return m_visualUpdatesAllowed; }
1260
1261 bool isInDocumentWrite() { return m_writeRecursionDepth > 0; }
1262
1263 void suspendScheduledTasks(ReasonForSuspension);
1264 void resumeScheduledTasks(ReasonForSuspension);
1265
1266#if ENABLE(CSS_DEVICE_ADAPTATION)
1267 IntSize initialViewportSize() const;
1268#endif
1269
1270 void convertAbsoluteToClientQuads(Vector<FloatQuad>&, const RenderStyle&);
1271 void convertAbsoluteToClientRects(Vector<FloatRect>&, const RenderStyle&);
1272 void convertAbsoluteToClientRect(FloatRect&, const RenderStyle&);
1273
1274 bool hasActiveParser();
1275 void incrementActiveParserCount() { ++m_activeParserCount; }
1276 void decrementActiveParserCount();
1277
1278 std::unique_ptr<DocumentParserYieldToken> createParserYieldToken()
1279 {
1280 return std::make_unique<DocumentParserYieldToken>(*this);
1281 }
1282
1283 bool hasActiveParserYieldToken() const { return m_parserYieldTokenCount; }
1284
1285 DocumentSharedObjectPool* sharedObjectPool() { return m_sharedObjectPool.get(); }
1286
1287 void invalidateMatchedPropertiesCacheAndForceStyleRecalc();
1288
1289 void didRemoveAllPendingStylesheet();
1290 void didClearStyleResolver();
1291
1292 bool inStyleRecalc() const { return m_inStyleRecalc; }
1293 bool inRenderTreeUpdate() const { return m_inRenderTreeUpdate; }
1294 bool isResolvingTreeStyle() const { return m_isResolvingTreeStyle; }
1295 void setIsResolvingTreeStyle(bool);
1296
1297 void updateTextRenderer(Text&, unsigned offsetOfReplacedText, unsigned lengthOfReplacedText);
1298
1299 // Return a Locale for the default locale if the argument is null or empty.
1300 Locale& getCachedLocale(const AtomString& locale = nullAtom());
1301
1302 const Document* templateDocument() const;
1303 Document& ensureTemplateDocument();
1304 void setTemplateDocumentHost(Document* templateDocumentHost) { m_templateDocumentHost = makeWeakPtr(templateDocumentHost); }
1305 Document* templateDocumentHost() { return m_templateDocumentHost.get(); }
1306
1307 void didAssociateFormControl(Element&);
1308 bool hasDisabledFieldsetElement() const { return m_disabledFieldsetElementsCount; }
1309 void addDisabledFieldsetElement() { m_disabledFieldsetElementsCount++; }
1310 void removeDisabledFieldsetElement() { ASSERT(m_disabledFieldsetElementsCount); m_disabledFieldsetElementsCount--; }
1311
1312 void getParserLocation(String& url, unsigned& line, unsigned& column) const;
1313
1314 WEBCORE_EXPORT void addConsoleMessage(std::unique_ptr<Inspector::ConsoleMessage>&&) final;
1315
1316 // The following addConsoleMessage function is deprecated.
1317 // Callers should try to create the ConsoleMessage themselves.
1318 WEBCORE_EXPORT void addConsoleMessage(MessageSource, MessageLevel, const String& message, unsigned long requestIdentifier = 0) final;
1319
1320 // The following addMessage function is deprecated.
1321 // Callers should try to create the ConsoleMessage themselves.
1322 void addMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, unsigned columnNumber, RefPtr<Inspector::ScriptCallStack>&&, JSC::ExecState* = nullptr, unsigned long requestIdentifier = 0) final;
1323
1324 SecurityOrigin& securityOrigin() const { return *SecurityContext::securityOrigin(); }
1325 SecurityOrigin& topOrigin() const final { return topDocument().securityOrigin(); }
1326
1327 Ref<FontFaceSet> fonts();
1328
1329 void ensurePlugInsInjectedScript(DOMWrapperWorld&);
1330
1331 void setVisualUpdatesAllowedByClient(bool);
1332
1333#if ENABLE(WEB_CRYPTO)
1334 bool wrapCryptoKey(const Vector<uint8_t>& key, Vector<uint8_t>& wrappedKey) final;
1335 bool unwrapCryptoKey(const Vector<uint8_t>& wrappedKey, Vector<uint8_t>& key) final;
1336#endif
1337
1338 void setHasStyleWithViewportUnits() { m_hasStyleWithViewportUnits = true; }
1339 bool hasStyleWithViewportUnits() const { return m_hasStyleWithViewportUnits; }
1340 void updateViewportUnitsOnResize();
1341
1342 WEBCORE_EXPORT void addAudioProducer(MediaProducer&);
1343 WEBCORE_EXPORT void removeAudioProducer(MediaProducer&);
1344 MediaProducer::MediaStateFlags mediaState() const { return m_mediaState; }
1345 void noteUserInteractionWithMediaElement();
1346 bool isCapturing() const { return MediaProducer::isCapturing(m_mediaState); }
1347 WEBCORE_EXPORT void updateIsPlayingMedia(uint64_t = HTMLMediaElementInvalidID);
1348 void pageMutedStateDidChange();
1349
1350#if ENABLE(WIRELESS_PLAYBACK_TARGET)
1351 void addPlaybackTargetPickerClient(MediaPlaybackTargetClient&);
1352 void removePlaybackTargetPickerClient(MediaPlaybackTargetClient&);
1353 void showPlaybackTargetPicker(MediaPlaybackTargetClient&, bool, RouteSharingPolicy, const String&);
1354 void playbackTargetPickerClientStateDidChange(MediaPlaybackTargetClient&, MediaProducer::MediaStateFlags);
1355
1356 void setPlaybackTarget(uint64_t, Ref<MediaPlaybackTarget>&&);
1357 void playbackTargetAvailabilityDidChange(uint64_t, bool);
1358 void setShouldPlayToPlaybackTarget(uint64_t, bool);
1359#endif
1360
1361 ShouldOpenExternalURLsPolicy shouldOpenExternalURLsPolicyToPropagate() const;
1362 bool shouldEnforceContentDispositionAttachmentSandbox() const;
1363 void applyContentDispositionAttachmentSandbox();
1364
1365 void addViewportDependentPicture(HTMLPictureElement&);
1366 void removeViewportDependentPicture(HTMLPictureElement&);
1367
1368 void addAppearanceDependentPicture(HTMLPictureElement&);
1369 void removeAppearanceDependentPicture(HTMLPictureElement&);
1370
1371 void scheduleTimedRenderingUpdate();
1372
1373#if ENABLE(INTERSECTION_OBSERVER)
1374 void addIntersectionObserver(IntersectionObserver&);
1375 void removeIntersectionObserver(IntersectionObserver&);
1376 unsigned numberOfIntersectionObservers() const { return m_intersectionObservers.size(); }
1377 void updateIntersectionObservations();
1378 void scheduleInitialIntersectionObservationUpdate();
1379#endif
1380
1381#if ENABLE(RESIZE_OBSERVER)
1382 void addResizeObserver(ResizeObserver&);
1383 void removeResizeObserver(ResizeObserver&);
1384 bool hasResizeObservers();
1385 // Return the minDepth of the active observations.
1386 size_t gatherResizeObservations(size_t deeperThan);
1387 void deliverResizeObservations();
1388 bool hasSkippedResizeObservations() const;
1389 void setHasSkippedResizeObservations(bool);
1390 void updateResizeObservations(Page&);
1391#endif
1392
1393#if ENABLE(MEDIA_STREAM)
1394 void setHasCaptureMediaStreamTrack() { m_hasHadCaptureMediaStreamTrack = true; }
1395 bool hasHadCaptureMediaStreamTrack() const { return m_hasHadCaptureMediaStreamTrack; }
1396 void setDeviceIDHashSalt(const String&);
1397 String deviceIDHashSalt() const { return m_idHashSalt; }
1398 void stopMediaCapture();
1399 void registerForMediaStreamStateChangeCallbacks(HTMLMediaElement&);
1400 void unregisterForMediaStreamStateChangeCallbacks(HTMLMediaElement&);
1401 void mediaStreamCaptureStateChanged();
1402#endif
1403
1404// FIXME: Find a better place for this functionality.
1405#if ENABLE(TELEPHONE_NUMBER_DETECTION)
1406 // These functions provide a two-level setting:
1407 // - A user-settable wantsTelephoneNumberParsing (at the Page / WebView level)
1408 // - A read-only telephoneNumberParsingAllowed which is set by the
1409 // document if it has the appropriate meta tag.
1410 // - isTelephoneNumberParsingEnabled() == isTelephoneNumberParsingAllowed() && page()->settings()->isTelephoneNumberParsingEnabled()
1411 WEBCORE_EXPORT bool isTelephoneNumberParsingAllowed() const;
1412 WEBCORE_EXPORT bool isTelephoneNumberParsingEnabled() const;
1413#endif
1414
1415 using ContainerNode::setAttributeEventListener;
1416 void setAttributeEventListener(const AtomString& eventType, const QualifiedName& attributeName, const AtomString& value, DOMWrapperWorld& isolatedWorld);
1417
1418 DOMSelection* getSelection();
1419
1420 void didInsertInDocumentShadowRoot(ShadowRoot&);
1421 void didRemoveInDocumentShadowRoot(ShadowRoot&);
1422 const HashSet<ShadowRoot*>& inDocumentShadowRoots() const { return m_inDocumentShadowRoots; }
1423
1424 void attachToCachedFrame(CachedFrameBase&);
1425 void detachFromCachedFrame(CachedFrameBase&);
1426
1427 ConstantPropertyMap& constantProperties() const { return *m_constantPropertyMap; }
1428
1429 void orientationChanged(int orientation);
1430 OrientationNotifier& orientationNotifier() { return m_orientationNotifier; }
1431
1432 WEBCORE_EXPORT const AtomString& bgColor() const;
1433 WEBCORE_EXPORT void setBgColor(const String&);
1434 WEBCORE_EXPORT const AtomString& fgColor() const;
1435 WEBCORE_EXPORT void setFgColor(const String&);
1436 WEBCORE_EXPORT const AtomString& alinkColor() const;
1437 WEBCORE_EXPORT void setAlinkColor(const String&);
1438 WEBCORE_EXPORT const AtomString& linkColorForBindings() const;
1439 WEBCORE_EXPORT void setLinkColorForBindings(const String&);
1440 WEBCORE_EXPORT const AtomString& vlinkColor() const;
1441 WEBCORE_EXPORT void setVlinkColor(const String&);
1442
1443 // Per https://html.spec.whatwg.org/multipage/obsolete.html#dom-document-clear, this method does nothing.
1444 void clear() { }
1445 // Per https://html.spec.whatwg.org/multipage/obsolete.html#dom-document-captureevents, this method does nothing.
1446 void captureEvents() { }
1447 // Per https://html.spec.whatwg.org/multipage/obsolete.html#dom-document-releaseevents, this method does nothing.
1448 void releaseEvents() { }
1449
1450#if ENABLE(TEXT_AUTOSIZING)
1451 TextAutoSizing& textAutoSizing();
1452#endif
1453
1454 // For debugging rdar://problem/49877867.
1455 void setMayBeDetachedFromFrame(bool mayBeDetachedFromFrame) { m_mayBeDetachedFromFrame = mayBeDetachedFromFrame; }
1456
1457 Logger& logger();
1458
1459 WEBCORE_EXPORT void setConsoleMessageListener(RefPtr<StringCallback>&&); // For testing.
1460
1461 WEBCORE_EXPORT DocumentTimeline& timeline();
1462 DocumentTimeline* existingTimeline() const { return m_timeline.get(); }
1463 Vector<RefPtr<WebAnimation>> getAnimations();
1464
1465#if ENABLE(ATTACHMENT_ELEMENT)
1466 void registerAttachmentIdentifier(const String&);
1467 void didInsertAttachmentElement(HTMLAttachmentElement&);
1468 void didRemoveAttachmentElement(HTMLAttachmentElement&);
1469 WEBCORE_EXPORT RefPtr<HTMLAttachmentElement> attachmentForIdentifier(const String&) const;
1470 const HashMap<String, Ref<HTMLAttachmentElement>>& attachmentElementsByIdentifier() const { return m_attachmentIdentifierToElementMap; }
1471#endif
1472
1473#if ENABLE(SERVICE_WORKER)
1474 void setServiceWorkerConnection(SWClientConnection*);
1475#endif
1476
1477 void addApplicationStateChangeListener(ApplicationStateChangeListener&);
1478 void removeApplicationStateChangeListener(ApplicationStateChangeListener&);
1479 void forEachApplicationStateChangeListener(const Function<void(ApplicationStateChangeListener&)>&);
1480
1481#if ENABLE(IOS_TOUCH_EVENTS)
1482 bool handlingTouchEvent() const { return m_handlingTouchEvent; }
1483#endif
1484
1485#if ENABLE(RESOURCE_LOAD_STATISTICS)
1486 bool hasRequestedPageSpecificStorageAccessWithUserInteraction(const RegistrableDomain&);
1487 void setHasRequestedPageSpecificStorageAccessWithUserInteraction(const RegistrableDomain&);
1488 WEBCORE_EXPORT void wasLoadedWithDataTransferFromPrevalentResource();
1489 void downgradeReferrerToRegistrableDomain();
1490#endif
1491
1492 String signedPublicKeyAndChallengeString(unsigned keySizeIndex, const String& challengeString, const URL&);
1493
1494 void registerArticleElement(Element&);
1495 void unregisterArticleElement(Element&);
1496 void updateMainArticleElementAfterLayout();
1497 bool hasMainArticleElement() const { return !!m_mainArticleElement; }
1498
1499 const CSSRegisteredCustomPropertySet& getCSSRegisteredCustomPropertySet() const { return m_CSSRegisteredPropertySet; }
1500 bool registerCSSProperty(CSSRegisteredCustomProperty&&);
1501
1502#if ENABLE(CSS_PAINTING_API)
1503 Worklet& ensurePaintWorklet();
1504 PaintWorkletGlobalScope* paintWorkletGlobalScopeForName(const String& name);
1505 void setPaintWorkletGlobalScopeForName(const String& name, Ref<PaintWorkletGlobalScope>&&);
1506#endif
1507
1508 WEBCORE_EXPORT bool hasEvaluatedUserAgentScripts() const;
1509 WEBCORE_EXPORT bool isRunningUserScripts() const;
1510 WEBCORE_EXPORT void setAsRunningUserScripts();
1511 void setHasEvaluatedUserAgentScripts();
1512#if ENABLE(APPLE_PAY)
1513 WEBCORE_EXPORT bool isApplePayActive() const;
1514 WEBCORE_EXPORT void setApplePayIsActive();
1515#endif
1516
1517 void frameWasDisconnectedFromOwner();
1518
1519 WEBCORE_EXPORT bool hitTest(const HitTestRequest&, HitTestResult&);
1520 bool hitTest(const HitTestRequest&, const HitTestLocation&, HitTestResult&);
1521#if !ASSERT_DISABLED
1522 bool inHitTesting() const { return m_inHitTesting; }
1523#endif
1524
1525protected:
1526 enum ConstructionFlags { Synthesized = 1, NonRenderedPlaceholder = 1 << 1 };
1527 Document(Frame*, const URL&, unsigned = DefaultDocumentClass, unsigned constructionFlags = 0);
1528
1529 void clearXMLVersion() { m_xmlVersion = String(); }
1530
1531 virtual Ref<Document> cloneDocumentWithoutChildren() const;
1532
1533private:
1534 friend class DocumentParserYieldToken;
1535 friend class Node;
1536 friend class ThrowOnDynamicMarkupInsertionCountIncrementer;
1537 friend class IgnoreOpensDuringUnloadCountIncrementer;
1538 friend class IgnoreDestructiveWriteCountIncrementer;
1539
1540 bool shouldInheritContentSecurityPolicy() const;
1541
1542 void updateTitleElement(Element& changingTitleElement);
1543 void willDetachPage() final;
1544 void frameDestroyed() final;
1545
1546 void commonTeardown();
1547
1548 RenderObject* renderer() const = delete;
1549 void setRenderer(RenderObject*) = delete;
1550
1551 void createRenderTree();
1552 void detachParser();
1553
1554 // FontSelectorClient
1555 void fontsNeedUpdate(FontSelector&) final;
1556
1557 bool isDocument() const final { return true; }
1558
1559 void childrenChanged(const ChildChange&) final;
1560
1561 String nodeName() const final;
1562 NodeType nodeType() const final;
1563 bool childTypeAllowed(NodeType) const final;
1564 Ref<Node> cloneNodeInternal(Document&, CloningOperation) final;
1565 void cloneDataFromDocument(const Document&);
1566
1567 void refScriptExecutionContext() final { ref(); }
1568 void derefScriptExecutionContext() final { deref(); }
1569
1570 Seconds minimumDOMTimerInterval() const final;
1571
1572 Seconds domTimerAlignmentInterval(bool hasReachedMaxNestingLevel) const final;
1573
1574 void updateTitleFromTitleElement();
1575 void updateTitle(const StringWithDirection&);
1576 void updateBaseURL();
1577
1578 void invalidateAccessKeyCacheSlowCase();
1579 void buildAccessKeyCache();
1580
1581 void moveNodeIteratorsToNewDocumentSlowCase(Node&, Document&);
1582
1583 void loadEventDelayTimerFired();
1584
1585 void pendingTasksTimerFired();
1586 bool isCookieAverse() const;
1587
1588 void detachFromFrame();
1589
1590 template<CollectionType> Ref<HTMLCollection> ensureCachedCollection();
1591
1592 void dispatchDisabledAdaptationsDidChangeForMainFrame();
1593
1594 void setVisualUpdatesAllowed(ReadyState);
1595 void setVisualUpdatesAllowed(bool);
1596 void visualUpdatesSuppressionTimerFired();
1597
1598 void addListenerType(ListenerType listenerType) { m_listenerTypes |= listenerType; }
1599
1600 void didAssociateFormControlsTimerFired();
1601
1602 void wheelEventHandlersChanged();
1603
1604 HttpEquivPolicy httpEquivPolicy() const;
1605 AXObjectCache* existingAXObjectCacheSlow() const;
1606
1607 // DOM Cookies caching.
1608 const String& cachedDOMCookies() const { return m_cachedDOMCookies; }
1609 void setCachedDOMCookies(const String&);
1610 bool isDOMCookieCacheValid() const { return m_cookieCacheExpiryTimer.isActive(); }
1611 void invalidateDOMCookieCache();
1612 void didLoadResourceSynchronously() final;
1613
1614 void checkViewportDependentPictures();
1615 void checkAppearanceDependentPictures();
1616
1617 bool canNavigateInternal(Frame& targetFrame);
1618 bool isNavigationBlockedByThirdPartyIFrameRedirectBlocking(Frame& targetFrame, const URL& destinationURL);
1619
1620#if ENABLE(INTERSECTION_OBSERVER)
1621 void notifyIntersectionObserversTimerFired();
1622#endif
1623
1624#if USE(QUICK_LOOK)
1625 bool shouldEnforceQuickLookSandbox() const;
1626 void applyQuickLookSandbox();
1627#endif
1628
1629 bool shouldEnforceHTTP09Sandbox() const;
1630
1631 void platformSuspendOrStopActiveDOMObjects();
1632
1633 bool isBodyPotentiallyScrollable(HTMLBodyElement&);
1634
1635 const Ref<Settings> m_settings;
1636
1637 UniqueRef<Quirks> m_quirks;
1638
1639 std::unique_ptr<StyleResolver> m_userAgentShadowTreeStyleResolver;
1640
1641 RefPtr<DOMWindow> m_domWindow;
1642 WeakPtr<Document> m_contextDocument;
1643
1644 Ref<CachedResourceLoader> m_cachedResourceLoader;
1645 RefPtr<DocumentParser> m_parser;
1646
1647 unsigned m_parserYieldTokenCount { 0 };
1648
1649 // Document URLs.
1650 URL m_url; // Document.URL: The URL from which this document was retrieved.
1651 URL m_baseURL; // Node.baseURI: The URL to use when resolving relative URLs.
1652 URL m_baseURLOverride; // An alternative base URL that takes precedence over m_baseURL (but not m_baseElementURL).
1653 URL m_baseElementURL; // The URL set by the <base> element.
1654 URL m_cookieURL; // The URL to use for cookie access.
1655 URL m_firstPartyForCookies; // The policy URL for third-party cookie blocking.
1656 URL m_siteForCookies; // The policy URL for Same-Site cookies.
1657
1658 // Document.documentURI:
1659 // Although URL-like, Document.documentURI can actually be set to any
1660 // string by content. Document.documentURI affects m_baseURL unless the
1661 // document contains a <base> element, in which case the <base> element
1662 // takes precedence.
1663 //
1664 // This property is read-only from JavaScript, but writable from Objective C.
1665 String m_documentURI;
1666
1667 String m_baseTarget;
1668
1669 // MIME type of the document in case it was cloned or created by XHR.
1670 String m_overriddenMIMEType;
1671
1672 std::unique_ptr<DOMImplementation> m_implementation;
1673
1674 RefPtr<Node> m_focusNavigationStartingNode;
1675 RefPtr<Element> m_focusedElement;
1676 RefPtr<Element> m_hoveredElement;
1677 RefPtr<Element> m_activeElement;
1678 RefPtr<Element> m_documentElement;
1679 UserActionElementSet m_userActionElements;
1680
1681 uint64_t m_domTreeVersion;
1682 static uint64_t s_globalTreeVersion;
1683
1684 String m_uniqueIdentifier;
1685
1686 HashSet<NodeIterator*> m_nodeIterators;
1687 HashSet<Range*> m_ranges;
1688
1689 std::unique_ptr<Style::Scope> m_styleScope;
1690 std::unique_ptr<ExtensionStyleSheets> m_extensionStyleSheets;
1691 RefPtr<StyleSheetList> m_styleSheetList;
1692
1693 std::unique_ptr<FormController> m_formController;
1694
1695 Color m_textColor { Color::black };
1696 Color m_linkColor;
1697 Color m_visitedLinkColor;
1698 Color m_activeLinkColor;
1699 const std::unique_ptr<VisitedLinkState> m_visitedLinkState;
1700
1701 StringWithDirection m_title;
1702 StringWithDirection m_rawTitle;
1703 RefPtr<Element> m_titleElement;
1704
1705 std::unique_ptr<AXObjectCache> m_axObjectCache;
1706 const std::unique_ptr<DocumentMarkerController> m_markers;
1707
1708 Timer m_styleRecalcTimer;
1709
1710 Element* m_cssTarget { nullptr };
1711
1712 RefPtr<SerializedScriptValue> m_pendingStateObject;
1713 MonotonicTime m_documentCreationTime;
1714 bool m_overMinimumLayoutThreshold { false };
1715
1716 std::unique_ptr<ScriptRunner> m_scriptRunner;
1717 std::unique_ptr<ScriptModuleLoader> m_moduleLoader;
1718
1719 Vector<RefPtr<HTMLScriptElement>> m_currentScriptStack;
1720
1721#if ENABLE(XSLT)
1722 void applyPendingXSLTransformsTimerFired();
1723
1724 std::unique_ptr<TransformSource> m_transformSource;
1725 RefPtr<Document> m_transformSourceDocument;
1726 Timer m_applyPendingXSLTransformsTimer;
1727 bool m_hasPendingXSLTransforms { false };
1728#endif
1729
1730 String m_xmlEncoding;
1731 String m_xmlVersion;
1732 StandaloneStatus m_xmlStandalone { StandaloneStatus::Unspecified };
1733 bool m_hasXMLDeclaration { false };
1734
1735 String m_contentLanguage;
1736
1737 RefPtr<TextResourceDecoder> m_decoder;
1738
1739 HashSet<LiveNodeList*> m_listsInvalidatedAtDocument;
1740 HashSet<HTMLCollection*> m_collectionsInvalidatedAtDocument;
1741 unsigned m_nodeListAndCollectionCounts[numNodeListInvalidationTypes];
1742
1743 RefPtr<XPathEvaluator> m_xpathEvaluator;
1744
1745 std::unique_ptr<SVGDocumentExtensions> m_svgExtensions;
1746 HashSet<SVGUseElement*> m_svgUseElements;
1747
1748#if ENABLE(DARK_MODE_CSS)
1749 OptionSet<ColorScheme> m_colorScheme;
1750 bool m_allowsColorSchemeTransformations { true };
1751#endif
1752
1753 HashMap<String, RefPtr<HTMLCanvasElement>> m_cssCanvasElements;
1754
1755 HashSet<Element*> m_documentSuspensionCallbackElements;
1756 HashSet<Element*> m_mediaVolumeCallbackElements;
1757 HashSet<Element*> m_privateBrowsingStateChangedElements;
1758#if ENABLE(VIDEO_TRACK)
1759 HashSet<Element*> m_captionPreferencesChangedElements;
1760#endif
1761
1762 Element* m_mainArticleElement { nullptr };
1763 HashSet<Element*> m_articleElements;
1764
1765#if ENABLE(MEDIA_CONTROLS_SCRIPT)
1766 HashSet<HTMLMediaElement*> m_pageScaleFactorChangedElements;
1767 HashSet<HTMLMediaElement*> m_userInterfaceLayoutDirectionChangedElements;
1768#endif
1769
1770 HashSet<VisibilityChangeClient*> m_visibilityStateCallbackClients;
1771#if ENABLE(VIDEO)
1772 HashSet<HTMLMediaElement*> m_allowsMediaDocumentInlinePlaybackElements;
1773#endif
1774
1775 std::unique_ptr<HashMap<String, Element*, ASCIICaseInsensitiveHash>> m_accessKeyCache;
1776
1777 std::unique_ptr<ConstantPropertyMap> m_constantPropertyMap;
1778
1779 std::unique_ptr<SelectorQueryCache> m_selectorQueryCache;
1780
1781 DocumentClassFlags m_documentClasses;
1782
1783 RenderPtr<RenderView> m_renderView;
1784 mutable DocumentEventQueue m_eventQueue;
1785
1786 HashSet<MediaCanStartListener*> m_mediaCanStartListeners;
1787
1788#if ENABLE(FULLSCREEN_API)
1789 UniqueRef<FullscreenManager> m_fullscreenManager;
1790#endif
1791
1792 HashSet<HTMLPictureElement*> m_viewportDependentPictures;
1793 HashSet<HTMLPictureElement*> m_appearanceDependentPictures;
1794
1795#if ENABLE(INTERSECTION_OBSERVER)
1796 Vector<WeakPtr<IntersectionObserver>> m_intersectionObservers;
1797 Vector<WeakPtr<IntersectionObserver>> m_intersectionObserversWithPendingNotifications;
1798 Timer m_intersectionObserversNotifyTimer;
1799 Timer m_intersectionObserversInitialUpdateTimer;
1800#endif
1801
1802#if ENABLE(RESIZE_OBSERVER)
1803 Vector<WeakPtr<ResizeObserver>> m_resizeObservers;
1804#endif
1805
1806 Timer m_loadEventDelayTimer;
1807
1808 ViewportArguments m_viewportArguments;
1809 OptionSet<DisabledAdaptations> m_disabledAdaptations;
1810
1811 DocumentTiming m_documentTiming;
1812
1813 RefPtr<MediaQueryMatcher> m_mediaQueryMatcher;
1814
1815#if ENABLE(TOUCH_EVENTS)
1816 std::unique_ptr<EventTargetSet> m_touchEventTargets;
1817#endif
1818#if PLATFORM(IOS_FAMILY) && ENABLE(POINTER_EVENTS)
1819 std::unique_ptr<HashSet<RefPtr<Element>>> m_touchActionElements;
1820#endif
1821 std::unique_ptr<EventTargetSet> m_wheelEventTargets;
1822
1823 MonotonicTime m_lastHandledUserGestureTimestamp;
1824 MonotonicTime m_userActivatedMediaFinishedPlayingTimestamp;
1825
1826 void clearScriptedAnimationController();
1827 RefPtr<ScriptedAnimationController> m_scriptedAnimationController;
1828
1829 void notifyMediaCaptureOfVisibilityChanged();
1830
1831 void didLogMessage(const WTFLogChannel&, WTFLogLevel, Vector<JSONLogValue>&&) final;
1832
1833#if ENABLE(DEVICE_ORIENTATION)
1834#if PLATFORM(IOS_FAMILY)
1835 std::unique_ptr<DeviceMotionClient> m_deviceMotionClient;
1836 std::unique_ptr<DeviceMotionController> m_deviceMotionController;
1837 std::unique_ptr<DeviceOrientationClient> m_deviceOrientationClient;
1838 std::unique_ptr<DeviceOrientationController> m_deviceOrientationController;
1839#endif
1840 std::unique_ptr<DeviceOrientationAndMotionAccessController> m_deviceOrientationAndMotionAccessController;
1841#endif
1842
1843 GenericTaskQueue<Timer> m_logMessageTaskQueue;
1844
1845 Timer m_pendingTasksTimer;
1846 Vector<Task> m_pendingTasks;
1847
1848#if ENABLE(TEXT_AUTOSIZING)
1849 std::unique_ptr<TextAutoSizing> m_textAutoSizing;
1850#endif
1851
1852 Timer m_visualUpdatesSuppressionTimer;
1853
1854 void clearSharedObjectPool();
1855 Timer m_sharedObjectPoolClearTimer;
1856
1857 std::unique_ptr<DocumentSharedObjectPool> m_sharedObjectPool;
1858
1859 typedef HashMap<AtomString, std::unique_ptr<Locale>> LocaleIdentifierToLocaleMap;
1860 LocaleIdentifierToLocaleMap m_localeCache;
1861
1862 RefPtr<Document> m_templateDocument;
1863 WeakPtr<Document> m_templateDocumentHost; // Manually managed weakref (backpointer from m_templateDocument).
1864
1865 Ref<CSSFontSelector> m_fontSelector;
1866
1867 WeakHashSet<MediaProducer> m_audioProducers;
1868
1869 HashSet<ShadowRoot*> m_inDocumentShadowRoots;
1870
1871#if ENABLE(WIRELESS_PLAYBACK_TARGET)
1872 typedef HashMap<uint64_t, WebCore::MediaPlaybackTargetClient*> TargetIdToClientMap;
1873 TargetIdToClientMap m_idToClientMap;
1874 typedef HashMap<WebCore::MediaPlaybackTargetClient*, uint64_t> TargetClientToIdMap;
1875 TargetClientToIdMap m_clientToIDMap;
1876#endif
1877
1878#if ENABLE(MEDIA_SESSION)
1879 RefPtr<MediaSession> m_defaultMediaSession;
1880#endif
1881
1882#if ENABLE(INDEXED_DATABASE)
1883 RefPtr<IDBClient::IDBConnectionProxy> m_idbConnectionProxy;
1884#endif
1885
1886#if ENABLE(ATTACHMENT_ELEMENT)
1887 HashMap<String, Ref<HTMLAttachmentElement>> m_attachmentIdentifierToElementMap;
1888#endif
1889
1890 Timer m_didAssociateFormControlsTimer;
1891 Timer m_cookieCacheExpiryTimer;
1892
1893 RefPtr<SocketProvider> m_socketProvider;
1894
1895 String m_cachedDOMCookies;
1896
1897 Optional<WallTime> m_overrideLastModified;
1898
1899 HashSet<RefPtr<Element>> m_associatedFormControls;
1900 unsigned m_disabledFieldsetElementsCount { 0 };
1901
1902 unsigned m_listenerTypes { 0 };
1903 unsigned m_referencingNodeCount { 0 };
1904 int m_loadEventDelayCount { 0 };
1905 unsigned m_lastStyleUpdateSizeForTesting { 0 };
1906
1907 // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#throw-on-dynamic-markup-insertion-counter
1908 unsigned m_throwOnDynamicMarkupInsertionCount { 0 };
1909
1910 // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#ignore-opens-during-unload-counter
1911 unsigned m_ignoreOpensDuringUnloadCount { 0 };
1912
1913 // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#ignore-destructive-writes-counter
1914 unsigned m_ignoreDestructiveWriteCount { 0 };
1915
1916 unsigned m_activeParserCount { 0 };
1917 unsigned m_styleRecalcCount { 0 };
1918
1919 unsigned m_writeRecursionDepth { 0 };
1920
1921 InheritedBool m_designMode { inherit };
1922 MediaProducer::MediaStateFlags m_mediaState { MediaProducer::IsNotPlaying };
1923 bool m_userHasInteractedWithMediaElement { false };
1924 PageCacheState m_pageCacheState { NotInPageCache };
1925 Optional<ReferrerPolicy> m_referrerPolicy;
1926 ReadyState m_readyState { Complete };
1927
1928 MutationObserverOptions m_mutationObserverTypes { 0 };
1929
1930 bool m_writeRecursionIsTooDeep { false };
1931 bool m_wellFormed { false };
1932 bool m_createRenderers { true };
1933
1934 bool m_hasNodesWithNonFinalStyle { false };
1935 bool m_hasNodesWithMissingStyle { false };
1936 // But sometimes you need to ignore pending stylesheet count to
1937 // force an immediate layout when requested by JS.
1938 bool m_ignorePendingStylesheets { false };
1939
1940 bool m_hasElementUsingStyleBasedEditability { false };
1941 bool m_focusNavigationStartingNodeIsRemoved { false };
1942
1943 bool m_printing { false };
1944 bool m_paginatedForScreen { false };
1945
1946 DocumentCompatibilityMode m_compatibilityMode { DocumentCompatibilityMode::NoQuirksMode };
1947 bool m_compatibilityModeLocked { false }; // This is cheaper than making setCompatibilityMode virtual.
1948
1949 // FIXME: Merge these 2 variables into an enum. Also, FrameLoader::m_didCallImplicitClose
1950 // is almost a duplication of this data, so that should probably get merged in too.
1951 // FIXME: Document::m_processingLoadEvent and DocumentLoader::m_wasOnloadDispatched are roughly the same
1952 // and should be merged.
1953 bool m_processingLoadEvent { false };
1954 bool m_loadEventFinished { false };
1955
1956 bool m_visuallyOrdered { false };
1957 bool m_bParsing { false }; // FIXME: rename
1958
1959 bool m_needsFullStyleRebuild { false };
1960 bool m_inStyleRecalc { false };
1961 bool m_closeAfterStyleRecalc { false };
1962 bool m_inRenderTreeUpdate { false };
1963 bool m_isResolvingTreeStyle { false };
1964
1965 bool m_gotoAnchorNeededAfterStylesheetsLoad { false };
1966 bool m_isDNSPrefetchEnabled { false };
1967 bool m_haveExplicitlyDisabledDNSPrefetch { false };
1968
1969 bool m_isSynthesized { false };
1970 bool m_isNonRenderedPlaceholder { false };
1971
1972 bool m_sawElementsInKnownNamespaces { false };
1973 bool m_isSrcdocDocument { false };
1974
1975 bool m_hasInjectedPlugInsScript { false };
1976 bool m_renderTreeBeingDestroyed { false };
1977 bool m_hasPreparedForDestruction { false };
1978
1979 bool m_hasStyleWithViewportUnits { false };
1980 bool m_isTimerThrottlingEnabled { false };
1981 bool m_isSuspended { false };
1982
1983 bool m_scheduledTasksAreSuspended { false };
1984 bool m_visualUpdatesAllowed { true };
1985
1986 bool m_areDeviceMotionAndOrientationUpdatesSuspended { false };
1987 bool m_userDidInteractWithPage { false };
1988#if !ASSERT_DISABLED
1989 bool m_inHitTesting { false };
1990#endif
1991
1992#if ENABLE(TELEPHONE_NUMBER_DETECTION)
1993 bool m_isTelephoneNumberParsingAllowed { true };
1994#endif
1995
1996#if ENABLE(MEDIA_STREAM)
1997 HashSet<HTMLMediaElement*> m_mediaStreamStateChangeElements;
1998 String m_idHashSalt;
1999 bool m_hasHadCaptureMediaStreamTrack { false };
2000#endif
2001
2002#ifndef NDEBUG
2003 bool m_didDispatchViewportPropertiesChanged { false };
2004#endif
2005
2006 OrientationNotifier m_orientationNotifier;
2007 mutable PAL::SessionID m_sessionID;
2008 mutable RefPtr<Logger> m_logger;
2009 RefPtr<StringCallback> m_consoleMessageListener;
2010
2011 static bool hasEverCreatedAnAXObjectCache;
2012
2013 RefPtr<DocumentTimeline> m_timeline;
2014 DocumentIdentifier m_identifier;
2015
2016#if ENABLE(SERVICE_WORKER)
2017 RefPtr<SWClientConnection> m_serviceWorkerConnection;
2018#endif
2019
2020 HashSet<ApplicationStateChangeListener*> m_applicationStateChangeListeners;
2021
2022#if ENABLE(RESOURCE_LOAD_STATISTICS)
2023 RegistrableDomain m_registrableDomainRequestedPageSpecificStorageAccessWithUserInteraction { };
2024 String m_referrerOverride;
2025#endif
2026
2027 CSSRegisteredCustomPropertySet m_CSSRegisteredPropertySet;
2028
2029#if ENABLE(CSS_PAINTING_API)
2030 RefPtr<Worklet> m_paintWorklet;
2031 HashMap<String, Ref<PaintWorkletGlobalScope>> m_paintWorkletGlobalScopes;
2032#endif
2033
2034 bool m_hasEvaluatedUserAgentScripts { false };
2035 bool m_isRunningUserScripts { false };
2036 bool m_mayBeDetachedFromFrame { true };
2037#if ENABLE(APPLE_PAY)
2038 bool m_hasStartedApplePaySession { false };
2039#endif
2040
2041 Ref<UndoManager> m_undoManager;
2042#if PLATFORM(IOS_FAMILY)
2043 std::unique_ptr<ContentChangeObserver> m_contentChangeObserver;
2044#endif
2045
2046 HashMap<Element*, ElementIdentifier> m_identifiedElementsMap;
2047};
2048
2049Element* eventTargetElementForDocument(Document*);
2050
2051inline TextEncoding Document::textEncoding() const
2052{
2053 if (auto* decoder = this->decoder())
2054 return decoder->encoding();
2055 return TextEncoding();
2056}
2057
2058inline const Document* Document::templateDocument() const
2059{
2060 return m_templateDocumentHost ? this : m_templateDocument.get();
2061}
2062
2063inline AXObjectCache* Document::existingAXObjectCache() const
2064{
2065 if (!hasEverCreatedAnAXObjectCache)
2066 return nullptr;
2067 return existingAXObjectCacheSlow();
2068}
2069
2070inline Ref<Document> Document::create(const URL& url)
2071{
2072 return adoptRef(*new Document(nullptr, url));
2073}
2074
2075inline Ref<Document> Document::createNonRenderedPlaceholder(Frame& frame, const URL& url)
2076{
2077 return adoptRef(*new Document(&frame, url, DefaultDocumentClass, NonRenderedPlaceholder));
2078}
2079
2080inline void Document::invalidateAccessKeyCache()
2081{
2082 if (UNLIKELY(m_accessKeyCache))
2083 invalidateAccessKeyCacheSlowCase();
2084}
2085
2086// These functions are here because they require the Document class definition and we want to inline them.
2087
2088inline ScriptExecutionContext* Node::scriptExecutionContext() const
2089{
2090 return &document().contextDocument();
2091}
2092
2093inline ActiveDOMObject::ActiveDOMObject(Document& document)
2094 : ActiveDOMObject(static_cast<ScriptExecutionContext*>(&document.contextDocument()))
2095{
2096}
2097
2098} // namespace WebCore
2099
2100SPECIALIZE_TYPE_TRAITS_BEGIN(WebCore::Document)
2101 static bool isType(const WebCore::ScriptExecutionContext& context) { return context.isDocument(); }
2102 static bool isType(const WebCore::Node& node) { return node.isDocumentNode(); }
2103SPECIALIZE_TYPE_TRAITS_END()
2104