Bug 1727271: part 3) const-qualify `Document::HasValidTransientUserGestureActivation...
[gecko.git] / dom / base / Document.h
blobf4def501ba9748eb58f8cd10f7ee435801461584
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #ifndef mozilla_dom_Document_h___
8 #define mozilla_dom_Document_h___
10 #include <bitset>
11 #include <cstddef>
12 #include <cstdint>
13 #include <new>
14 #include <utility>
15 #include "ErrorList.h"
16 #include "MainThreadUtils.h"
17 #include "ReferrerInfo.h"
18 #include "Units.h"
19 #include "imgIRequest.h"
20 #include "js/RootingAPI.h"
21 #include "js/friend/DOMProxy.h"
22 #include "mozilla/AlreadyAddRefed.h"
23 #include "mozilla/Assertions.h"
24 #include "mozilla/Attributes.h"
25 #include "mozilla/BasicEvents.h"
26 #include "mozilla/BitSet.h"
27 #include "mozilla/CORSMode.h"
28 #include "mozilla/CallState.h"
29 #include "mozilla/EventStates.h"
30 #include "mozilla/FlushType.h"
31 #include "mozilla/FunctionRef.h"
32 #include "mozilla/HashTable.h"
33 #include "mozilla/LinkedList.h"
34 #include "mozilla/Maybe.h"
35 #include "mozilla/MozPromise.h"
36 #include "mozilla/NotNull.h"
37 #include "mozilla/PointerLockManager.h"
38 #include "mozilla/PreloadService.h"
39 #include "mozilla/RefPtr.h"
40 #include "mozilla/Result.h"
41 #include "mozilla/SegmentedVector.h"
42 #include "mozilla/TaskCategory.h"
43 #include "mozilla/TimeStamp.h"
44 #include "mozilla/UniquePtr.h"
45 #include "mozilla/UseCounter.h"
46 #include "mozilla/WeakPtr.h"
47 #include "mozilla/css/StylePreloadKind.h"
48 #include "mozilla/dom/DispatcherTrait.h"
49 #include "mozilla/dom/DocumentOrShadowRoot.h"
50 #include "mozilla/dom/Element.h"
51 #include "mozilla/dom/EventTarget.h"
52 #include "mozilla/dom/Nullable.h"
53 #include "mozilla/dom/ViewportMetaData.h"
54 #include "nsAtom.h"
55 #include "nsCOMArray.h"
56 #include "nsCOMPtr.h"
57 #include "nsClassHashtable.h"
58 #include "nsCompatibility.h"
59 #include "nsContentListDeclarations.h"
60 #include "nsCycleCollectionParticipant.h"
61 #include "nsTHashMap.h"
62 #include "nsDebug.h"
63 #include "nsExpirationTracker.h"
64 #include "nsGkAtoms.h"
65 #include "nsHashKeys.h"
66 #include "nsIChannel.h"
67 #include "nsIChannelEventSink.h"
68 #include "nsIContentViewer.h"
69 #include "nsID.h"
70 #include "nsIInterfaceRequestor.h"
71 #include "nsILoadContext.h"
72 #include "nsILoadGroup.h"
73 #include "nsILoadInfo.h"
74 #include "nsINode.h"
75 #include "nsIObserver.h"
76 #include "nsIParser.h"
77 #include "nsIPrincipal.h"
78 #include "nsIProgressEventSink.h"
79 #include "nsIRadioGroupContainer.h"
80 #include "nsIReferrerInfo.h"
81 #include "nsIRequestObserver.h"
82 #include "nsIScriptObjectPrincipal.h"
83 #include "nsIStreamListener.h"
84 #include "nsISupports.h"
85 #include "nsISupportsUtils.h"
86 #include "nsIURI.h"
87 #include "nsIWeakReferenceUtils.h"
88 #include "nsLiteralString.h"
89 #include "nsPIDOMWindow.h"
90 #include "nsPropertyTable.h"
91 #include "nsRefPtrHashtable.h"
92 #include "nsString.h"
93 #include "nsTArray.h"
94 #include "nsTHashSet.h"
95 #include "nsTLiteralString.h"
96 #include "nsTObserverArray.h"
97 #include "nsThreadUtils.h"
98 #include "nsURIHashKey.h"
99 #include "nsViewportInfo.h"
100 #include "nsWeakReference.h"
101 #include "nsWindowSizes.h"
102 #include "nsXULElement.h"
103 #include "nscore.h"
105 // XXX We need to include this here to ensure that DefaultDeleter for Servo
106 // types is specialized before the template is instantiated. Probably, this
107 // should be included at some other place already that's generated by cbindgen.
108 #include "mozilla/ServoBindingTypes.h"
110 // windows.h #defines CreateEvent
111 #ifdef CreateEvent
112 # undef CreateEvent
113 #endif
115 #ifdef MOZILLA_INTERNAL_API
116 # include "mozilla/dom/DocumentBinding.h"
117 #else
118 namespace mozilla {
119 namespace dom {
120 class ElementCreationOptionsOrString;
121 } // namespace dom
122 } // namespace mozilla
123 #endif // MOZILLA_INTERNAL_API
125 class InfallibleAllocPolicy;
126 class JSObject;
127 class JSTracer;
128 class PLDHashTable;
129 class gfxUserFontSet;
130 class mozIDOMWindowProxy;
131 class nsCachableElementsByNameNodeList;
132 class nsCommandManager;
133 class nsContentList;
134 class nsCycleCollectionTraversalCallback;
135 class nsDOMCaretPosition;
136 class nsDOMNavigationTiming;
137 class nsDocShell;
138 class nsFrameLoader;
139 class nsFrameLoaderOwner;
140 class nsGenericHTMLElement;
141 class nsGlobalWindowInner;
142 class nsHTMLCSSStyleSheet;
143 class nsHTMLDocument;
144 class nsHTMLStyleSheet;
145 class nsHtml5TreeOpExecutor;
146 class nsIAppWindow;
147 class nsIAsyncVerifyRedirectCallback;
148 class nsIBFCacheEntry;
149 class nsIContent;
150 class nsIContentSecurityPolicy;
151 class nsIContentSink;
152 class nsICookieJarSettings;
153 class nsIDOMXULCommandDispatcher;
154 class nsIDocShell;
155 class nsIDocShellTreeItem;
156 class nsIDocumentEncoder;
157 class nsIDocumentObserver;
158 class nsIEventTarget;
159 class nsIFrame;
160 class nsIGlobalObject;
161 class nsIHTMLCollection;
162 class nsIInputStream;
163 class nsILayoutHistoryState;
164 class nsIObjectLoadingContent;
165 class nsIPermissionDelegateHandler;
166 class nsIRadioVisitor;
167 class nsIRequest;
168 class nsIRunnable;
169 class nsIScriptGlobalObject;
170 class nsISecurityConsoleMessage;
171 class nsISerialEventTarget;
172 class nsIStructuredCloneContainer;
173 class nsIVariant;
174 class nsNodeInfoManager;
175 class nsPIWindowRoot;
176 class nsPresContext;
177 class nsRange;
178 class nsSimpleContentList;
179 class nsTextNode;
180 class nsViewManager;
181 class nsXULPrototypeDocument;
182 struct JSContext;
183 struct RawServoSelectorList;
184 struct StyleUseCounters;
185 struct nsFont;
187 namespace mozilla {
188 class AbstractThread;
189 class StyleSheet;
190 class EditorBase;
191 class EditorCommand;
192 class Encoding;
193 class ErrorResult;
194 class EventListenerManager;
195 class FullscreenExit;
196 class FullscreenRequest;
197 class HTMLEditor;
198 struct LangGroupFontPrefs;
199 class PendingAnimationTracker;
200 class PermissionDelegateHandler;
201 class PresShell;
202 class ServoStyleSet;
203 enum class StyleOrigin : uint8_t;
204 class SMILAnimationController;
205 enum class StyleCursorKind : uint8_t;
206 enum class StylePrefersColorScheme : uint8_t;
207 enum class StyleRuleChangeKind : uint32_t;
208 template <typename>
209 class OwningNonNull;
210 struct URLExtraData;
212 namespace css {
213 class Loader;
214 class ImageLoader;
215 class Rule;
216 } // namespace css
218 namespace dom {
219 class AnonymousContent;
220 class Attr;
221 class XULBroadcastManager;
222 class XULPersist;
223 class BrowserBridgeChild;
224 class ChromeObserver;
225 class ClientInfo;
226 class ClientState;
227 class CDATASection;
228 class Comment;
229 class CSSImportRule;
230 class DocumentL10n;
231 class DocumentFragment;
232 class DocumentTimeline;
233 class DocumentType;
234 class DOMImplementation;
235 class DOMIntersectionObserver;
236 class DOMStringList;
237 class Event;
238 class EventListener;
239 struct FailedCertSecurityInfo;
240 class FeaturePolicy;
241 class FontFaceSet;
242 class FrameRequestCallback;
243 class ImageTracker;
244 class HTMLAllCollection;
245 class HTMLBodyElement;
246 class HTMLInputElement;
247 class HTMLMetaElement;
248 class HTMLDialogElement;
249 class HTMLSharedElement;
250 class HTMLImageElement;
251 struct LifecycleCallbackArgs;
252 class Link;
253 class Location;
254 class MediaQueryList;
255 struct NetErrorInfo;
256 class NodeFilter;
257 class NodeInfo;
258 class NodeIterator;
259 enum class OrientationType : uint8_t;
260 class ProcessingInstruction;
261 class Promise;
262 class ScriptLoader;
263 class Selection;
264 class ServiceWorkerDescriptor;
265 class ShadowRoot;
266 class SVGDocument;
267 class SVGElement;
268 class SVGSVGElement;
269 class SVGUseElement;
270 class Touch;
271 class TouchList;
272 class TreeWalker;
273 enum class ViewportFitType : uint8_t;
274 class WindowContext;
275 class WindowGlobalChild;
276 class WindowProxyHolder;
277 class XPathEvaluator;
278 class XPathExpression;
279 class XPathNSResolver;
280 class XPathResult;
281 class BrowsingContext;
283 class nsDocumentOnStack;
284 class nsUnblockOnloadEvent;
286 template <typename, typename>
287 class CallbackObjectHolder;
289 enum class CallerType : uint32_t;
291 enum BFCacheStatus {
292 NOT_ALLOWED = 1 << 0, // Status 0
293 EVENT_HANDLING_SUPPRESSED = 1 << 1, // Status 1
294 SUSPENDED = 1 << 2, // Status 2
295 UNLOAD_LISTENER = 1 << 3, // Status 3
296 REQUEST = 1 << 4, // Status 4
297 ACTIVE_GET_USER_MEDIA = 1 << 5, // Status 5
298 ACTIVE_PEER_CONNECTION = 1 << 6, // Status 6
299 CONTAINS_EME_CONTENT = 1 << 7, // Status 7
300 CONTAINS_MSE_CONTENT = 1 << 8, // Status 8
301 HAS_ACTIVE_SPEECH_SYNTHESIS = 1 << 9, // Status 9
302 HAS_USED_VR = 1 << 10, // Status 10
303 CONTAINS_REMOTE_SUBFRAMES = 1 << 11, // Status 11
304 NOT_ONLY_TOPLEVEL_IN_BCG = 1 << 12, // Status 12
305 ABOUT_PAGE = 1 << 13, // Status 13
306 RESTORING = 1 << 14, // Status 14
309 } // namespace dom
310 } // namespace mozilla
312 namespace mozilla {
313 namespace net {
314 class ChannelEventQueue;
315 } // namespace net
316 } // namespace mozilla
318 // Must be kept in sync with xpcom/rust/xpcom/src/interfaces/nonidl.rs
319 #define NS_IDOCUMENT_IID \
321 0xce1f7627, 0x7109, 0x4977, { \
322 0xba, 0x77, 0x49, 0x0f, 0xfd, 0xe0, 0x7a, 0xaa \
326 namespace mozilla {
327 namespace dom {
329 class Document;
330 class DOMStyleSheetSetList;
331 class ResizeObserver;
332 class ResizeObserverController;
333 class PostMessageEvent;
335 #define DEPRECATED_OPERATION(_op) e##_op,
336 enum class DeprecatedOperations : uint16_t {
337 #include "nsDeprecatedOperationList.h"
338 eDeprecatedOperationCount
340 #undef DEPRECATED_OPERATION
342 // Document states
344 // RTL locale: specific to the XUL localedir attribute
345 #define NS_DOCUMENT_STATE_RTL_LOCALE NS_DEFINE_EVENT_STATE_MACRO(0)
346 // Window activation status
347 #define NS_DOCUMENT_STATE_WINDOW_INACTIVE NS_DEFINE_EVENT_STATE_MACRO(1)
349 class DocHeaderData {
350 public:
351 DocHeaderData(nsAtom* aField, const nsAString& aData)
352 : mField(aField), mData(aData), mNext(nullptr) {}
354 ~DocHeaderData(void) { delete mNext; }
356 RefPtr<nsAtom> mField;
357 nsString mData;
358 DocHeaderData* mNext;
361 class ExternalResourceMap {
362 using SubDocEnumFunc = FunctionRef<CallState(Document&)>;
364 public:
366 * A class that represents an external resource load that has begun but
367 * doesn't have a document yet. Observers can be registered on this object,
368 * and will be notified after the document is created. Observers registered
369 * after the document has been created will NOT be notified. When observers
370 * are notified, the subject will be the newly-created document, the topic
371 * will be "external-resource-document-created", and the data will be null.
372 * If document creation fails for some reason, observers will still be
373 * notified, with a null document pointer.
375 class ExternalResourceLoad : public nsISupports {
376 public:
377 virtual ~ExternalResourceLoad() = default;
379 void AddObserver(nsIObserver* aObserver) {
380 MOZ_ASSERT(aObserver, "Must have observer");
381 mObservers.AppendElement(aObserver);
384 const nsTArray<nsCOMPtr<nsIObserver>>& Observers() { return mObservers; }
386 protected:
387 AutoTArray<nsCOMPtr<nsIObserver>, 8> mObservers;
390 ExternalResourceMap();
393 * Request an external resource document. This does exactly what
394 * Document::RequestExternalResource is documented to do.
396 Document* RequestResource(nsIURI* aURI, nsIReferrerInfo* aReferrerInfo,
397 nsINode* aRequestingNode,
398 Document* aDisplayDocument,
399 ExternalResourceLoad** aPendingLoad);
402 * Enumerate the resource documents. See
403 * Document::EnumerateExternalResources.
405 void EnumerateResources(SubDocEnumFunc aCallback);
408 * Traverse ourselves for cycle-collection
410 void Traverse(nsCycleCollectionTraversalCallback* aCallback) const;
413 * Shut ourselves down (used for cycle-collection unlink), as well
414 * as for document destruction.
416 void Shutdown() {
417 mPendingLoads.Clear();
418 mMap.Clear();
419 mHaveShutDown = true;
422 bool HaveShutDown() const { return mHaveShutDown; }
424 // Needs to be public so we can traverse them sanely
425 struct ExternalResource {
426 ~ExternalResource();
427 RefPtr<Document> mDocument;
428 nsCOMPtr<nsIContentViewer> mViewer;
429 nsCOMPtr<nsILoadGroup> mLoadGroup;
432 // Hide all our viewers
433 void HideViewers();
435 // Show all our viewers
436 void ShowViewers();
438 protected:
439 class PendingLoad : public ExternalResourceLoad, public nsIStreamListener {
440 ~PendingLoad() = default;
442 public:
443 explicit PendingLoad(Document* aDisplayDocument)
444 : mDisplayDocument(aDisplayDocument) {}
446 NS_DECL_ISUPPORTS
447 NS_DECL_NSISTREAMLISTENER
448 NS_DECL_NSIREQUESTOBSERVER
451 * Start aURI loading. This will perform the necessary security checks and
452 * so forth.
454 nsresult StartLoad(nsIURI* aURI, nsIReferrerInfo* aReferrerInfo,
455 nsINode* aRequestingNode);
457 * Set up an nsIContentViewer based on aRequest. This is guaranteed to
458 * put null in *aViewer and *aLoadGroup on all failures.
460 nsresult SetupViewer(nsIRequest* aRequest, nsIContentViewer** aViewer,
461 nsILoadGroup** aLoadGroup);
463 private:
464 RefPtr<Document> mDisplayDocument;
465 nsCOMPtr<nsIStreamListener> mTargetListener;
466 nsCOMPtr<nsIURI> mURI;
468 friend class PendingLoad;
470 class LoadgroupCallbacks final : public nsIInterfaceRequestor {
471 ~LoadgroupCallbacks() = default;
473 public:
474 explicit LoadgroupCallbacks(nsIInterfaceRequestor* aOtherCallbacks)
475 : mCallbacks(aOtherCallbacks) {}
476 NS_DECL_ISUPPORTS
477 NS_DECL_NSIINTERFACEREQUESTOR
478 private:
479 // The only reason it's safe to hold a strong ref here without leaking is
480 // that the notificationCallbacks on a loadgroup aren't the docshell itself
481 // but a shim that holds a weak reference to the docshell.
482 nsCOMPtr<nsIInterfaceRequestor> mCallbacks;
484 // Use shims for interfaces that docshell implements directly so that we
485 // don't hand out references to the docshell. The shims should all allow
486 // getInterface back on us, but other than that each one should only
487 // implement one interface.
489 // XXXbz I wish we could just derive the _allcaps thing from _i
490 #define DECL_SHIM(_i, _allcaps) \
491 class _i##Shim final : public nsIInterfaceRequestor, public _i { \
492 ~_i##Shim() {} \
494 public: \
495 _i##Shim(nsIInterfaceRequestor* aIfreq, _i* aRealPtr) \
496 : mIfReq(aIfreq), mRealPtr(aRealPtr) { \
497 NS_ASSERTION(mIfReq, "Expected non-null here"); \
498 NS_ASSERTION(mRealPtr, "Expected non-null here"); \
500 NS_DECL_ISUPPORTS \
501 NS_FORWARD_NSIINTERFACEREQUESTOR(mIfReq->) \
502 NS_FORWARD_##_allcaps(mRealPtr->) private \
503 : nsCOMPtr<nsIInterfaceRequestor> mIfReq; \
504 nsCOMPtr<_i> mRealPtr; \
507 DECL_SHIM(nsILoadContext, NSILOADCONTEXT)
508 DECL_SHIM(nsIProgressEventSink, NSIPROGRESSEVENTSINK)
509 DECL_SHIM(nsIChannelEventSink, NSICHANNELEVENTSINK)
510 #undef DECL_SHIM
514 * Add an ExternalResource for aURI. aViewer and aLoadGroup might be null
515 * when this is called if the URI didn't result in an XML document. This
516 * function makes sure to remove the pending load for aURI, if any, from our
517 * hashtable, and to notify its observers, if any.
519 nsresult AddExternalResource(nsIURI* aURI, nsIContentViewer* aViewer,
520 nsILoadGroup* aLoadGroup,
521 Document* aDisplayDocument);
523 nsClassHashtable<nsURIHashKey, ExternalResource> mMap;
524 nsRefPtrHashtable<nsURIHashKey, PendingLoad> mPendingLoads;
525 bool mHaveShutDown;
528 // The current status for a preload.
529 enum class SheetPreloadStatus : uint8_t {
530 // There's no need to preload anything, the sheet is already in-memory.
531 AlreadyComplete,
532 // The load is in-progress. There's no guarantee that a load was started, it
533 // could be coalesced with other redundant loads.
534 InProgress,
535 // Something went wrong, and we errored out.
536 Errored,
539 //----------------------------------------------------------------------
541 // Document interface. This is implemented by all document objects in
542 // Gecko.
543 class Document : public nsINode,
544 public DocumentOrShadowRoot,
545 public nsSupportsWeakReference,
546 public nsIRadioGroupContainer,
547 public nsIScriptObjectPrincipal,
548 public DispatcherTrait,
549 public SupportsWeakPtr {
550 friend class DocumentOrShadowRoot;
552 protected:
553 explicit Document(const char* aContentType);
554 virtual ~Document();
556 Document(const Document&) = delete;
557 Document& operator=(const Document&) = delete;
559 public:
560 using ExternalResourceLoad = dom::ExternalResourceMap::ExternalResourceLoad;
561 using ReferrerPolicyEnum = dom::ReferrerPolicy;
562 using AdoptedStyleSheetCloneCache =
563 nsRefPtrHashtable<nsPtrHashKey<const StyleSheet>, StyleSheet>;
565 // nsINode overrides the new operator for DOM Arena allocation.
566 // to use the default one, we need to bring it back again
567 void* operator new(size_t aSize) { return ::operator new(aSize); }
570 * Called when XPCOM shutdown.
572 static void Shutdown();
574 NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOCUMENT_IID)
576 NS_DECL_CYCLE_COLLECTING_ISUPPORTS
578 NS_DECL_ADDSIZEOFEXCLUDINGTHIS
580 NS_DECL_CYCLE_COLLECTION_SKIPPABLE_SCRIPT_HOLDER_CLASS_AMBIGUOUS(Document,
581 nsINode)
583 #define NS_DOCUMENT_NOTIFY_OBSERVERS(func_, params_) \
584 do { \
585 NS_OBSERVER_ARRAY_NOTIFY_XPCOM_OBSERVERS(mObservers, func_, params_); \
586 /* FIXME(emilio): Apparently we can keep observing from the BFCache? That \
587 looks bogus. */ \
588 if (PresShell* presShell = GetObservingPresShell()) { \
589 presShell->func_ params_; \
591 } while (0)
593 // nsIRadioGroupContainer
594 NS_IMETHOD WalkRadioGroup(const nsAString& aName,
595 nsIRadioVisitor* aVisitor) final {
596 return DocumentOrShadowRoot::WalkRadioGroup(aName, aVisitor);
599 void SetCurrentRadioButton(const nsAString& aName,
600 HTMLInputElement* aRadio) final {
601 DocumentOrShadowRoot::SetCurrentRadioButton(aName, aRadio);
604 HTMLInputElement* GetCurrentRadioButton(const nsAString& aName) final {
605 return DocumentOrShadowRoot::GetCurrentRadioButton(aName);
608 NS_IMETHOD
609 GetNextRadioButton(const nsAString& aName, const bool aPrevious,
610 HTMLInputElement* aFocusedRadio,
611 HTMLInputElement** aRadioOut) final {
612 return DocumentOrShadowRoot::GetNextRadioButton(aName, aPrevious,
613 aFocusedRadio, aRadioOut);
615 void AddToRadioGroup(const nsAString& aName, HTMLInputElement* aRadio) final {
616 DocumentOrShadowRoot::AddToRadioGroup(aName, aRadio);
618 void RemoveFromRadioGroup(const nsAString& aName,
619 HTMLInputElement* aRadio) final {
620 DocumentOrShadowRoot::RemoveFromRadioGroup(aName, aRadio);
622 uint32_t GetRequiredRadioCount(const nsAString& aName) const final {
623 return DocumentOrShadowRoot::GetRequiredRadioCount(aName);
625 void RadioRequiredWillChange(const nsAString& aName,
626 bool aRequiredAdded) final {
627 DocumentOrShadowRoot::RadioRequiredWillChange(aName, aRequiredAdded);
629 bool GetValueMissingState(const nsAString& aName) const final {
630 return DocumentOrShadowRoot::GetValueMissingState(aName);
632 void SetValueMissingState(const nsAString& aName, bool aValue) final {
633 return DocumentOrShadowRoot::SetValueMissingState(aName, aValue);
636 nsIPrincipal* EffectiveStoragePrincipal() const;
638 // nsIScriptObjectPrincipal
639 nsIPrincipal* GetPrincipal() final { return NodePrincipal(); }
641 nsIPrincipal* GetEffectiveStoragePrincipal() final {
642 return EffectiveStoragePrincipal();
645 // You should probably not be using this function, since it performs no checks
646 // to ensure that the partitioned principal should really be used here. It is
647 // only designed to be used in very specific circumstances, such as when
648 // inheriting the document/storage principal.
649 nsIPrincipal* PartitionedPrincipal() final { return mPartitionedPrincipal; }
651 // Gets the appropriate principal to check the URI against a blocklist /
652 // allowlist.
653 nsIPrincipal* GetPrincipalForPrefBasedHacks() const;
655 void ClearActiveStoragePrincipal() { mActiveStoragePrincipal = nullptr; }
657 // EventTarget
658 void GetEventTargetParent(EventChainPreVisitor& aVisitor) override;
659 EventListenerManager* GetOrCreateListenerManager() override;
660 EventListenerManager* GetExistingListenerManager() const override;
662 // This helper class must be set when we dispatch beforeunload and unload
663 // events in order to avoid unterminate sync XHRs.
664 class MOZ_RAII PageUnloadingEventTimeStamp {
665 RefPtr<Document> mDocument;
666 bool mSet;
668 public:
669 explicit PageUnloadingEventTimeStamp(Document* aDocument)
670 : mDocument(aDocument), mSet(false) {
671 MOZ_ASSERT(aDocument);
672 if (mDocument->mPageUnloadingEventTimeStamp.IsNull()) {
673 mDocument->SetPageUnloadingEventTimeStamp();
674 mSet = true;
678 ~PageUnloadingEventTimeStamp() {
679 if (mSet) {
680 mDocument->CleanUnloadEventsTimeStamp();
686 * Let the document know that we're starting to load data into it.
687 * @param aCommand The parser command. Must not be null.
688 * XXXbz It's odd to have that here.
689 * @param aChannel The channel the data will come from. The channel must be
690 * able to report its Content-Type.
691 * @param aLoadGroup The loadgroup this document should use from now on.
692 * Note that the document might not be the only thing using
693 * this loadgroup.
694 * @param aContainer The container this document is in. This may be null.
695 * XXXbz maybe we should make it more explicit (eg make the
696 * container an nsIWebNavigation or nsIDocShell or
697 * something)?
698 * @param [out] aDocListener the listener to pump data from the channel into.
699 * Generally this will be the parser this document
700 * sets up, or some sort of data-handler for media
701 * documents.
702 * @param aReset whether the document should call Reset() on itself. If this
703 * is false, the document will NOT set its principal to the
704 * channel's owner, will not clear any event listeners that are
705 * already set on it, etc.
706 * @param aSink The content sink to use for the data. If this is null and
707 * the document needs a content sink, it will create one based
708 * on whatever it knows about the data it's going to load.
709 * This MUST be null if the underlying document is an HTML
710 * document. Even in the XML case, please don't add new calls
711 * with non-null sink.
713 * Once this has been called, the document will return false for
714 * MayStartLayout() until SetMayStartLayout(true) is called on it. Making
715 * sure this happens is the responsibility of the caller of
716 * StartDocumentLoad().
718 * This function has an implementation, and does some setup, but does NOT set
719 * *aDocListener; this is the job of subclasses.
721 virtual nsresult StartDocumentLoad(const char* aCommand, nsIChannel* aChannel,
722 nsILoadGroup* aLoadGroup,
723 nsISupports* aContainer,
724 nsIStreamListener** aDocListener,
725 bool aReset,
726 nsIContentSink* aSink = nullptr) = 0;
727 void StopDocumentLoad();
729 virtual void SetSuppressParserErrorElement(bool aSuppress) {}
730 virtual bool SuppressParserErrorElement() { return false; }
732 virtual void SetSuppressParserErrorConsoleMessages(bool aSuppress) {}
733 virtual bool SuppressParserErrorConsoleMessages() { return false; }
735 // nsINode
736 bool IsNodeOfType(uint32_t aFlags) const final;
737 void InsertChildBefore(nsIContent* aKid, nsIContent* aBeforeThis,
738 bool aNotify, ErrorResult& aRv) override;
739 void RemoveChildNode(nsIContent* aKid, bool aNotify) final;
740 nsresult Clone(dom::NodeInfo* aNodeInfo, nsINode** aResult) const override {
741 return NS_ERROR_NOT_IMPLEMENTED;
743 nsresult CloneDocHelper(Document* clone) const;
745 Document* GetLatestStaticClone() const { return mLatestStaticClone; }
748 * Signal that the document title may have changed
749 * (see Document::GetTitle).
750 * @param aBoundTitleElement true if an HTML or SVG <title> element
751 * has just been bound to the document.
753 virtual void NotifyPossibleTitleChange(bool aBoundTitleElement);
756 * Return the URI for the document. May return null. If it ever stops being
757 * able to return null, we can make sure nsINode::GetBaseURI/GetBaseURIObject
758 * also never return null.
760 * The value returned corresponds to the "document's address" in
761 * HTML5. As such, it may change over the lifetime of the document, for
762 * instance as a result of the user navigating to a fragment identifier on
763 * the page, or as a result to a call to pushState() or replaceState().
765 * https://html.spec.whatwg.org/multipage/dom.html#the-document%27s-address
767 nsIURI* GetDocumentURI() const { return mDocumentURI; }
770 * Return the original URI of the document. This is the same as the
771 * document's URI unless that has changed from its original value (for
772 * example, due to history.pushState() or replaceState() being invoked on the
773 * document).
775 * This method corresponds to the "creation URL" in HTML5 and, once set,
776 * doesn't change over the lifetime of the document.
778 * https://html.spec.whatwg.org/multipage/webappapis.html#creation-url
780 nsIURI* GetOriginalURI() const { return mOriginalURI; }
783 * Return the base domain of the document. This has been computed using
784 * mozIThirdPartyUtil::GetBaseDomain() and can be used for third-party
785 * checks. When the URI of the document changes, this value is recomputed.
787 nsCString GetBaseDomain() const { return mBaseDomain; }
790 * Set the URI for the document. This also sets the document's original URI,
791 * if it's null.
793 void SetDocumentURI(nsIURI* aURI);
796 * Set the URI for the document loaded via XHR, when accessed from
797 * chrome privileged script.
799 void SetChromeXHRDocURI(nsIURI* aURI) { mChromeXHRDocURI = aURI; }
802 * Set the base URI for the document loaded via XHR, when accessed from
803 * chrome privileged script.
805 void SetChromeXHRDocBaseURI(nsIURI* aURI) { mChromeXHRDocBaseURI = aURI; }
808 * The CSP in general is stored in the ClientInfo, but we also cache
809 * the CSP on the document so subresources loaded within a document
810 * can query that cached CSP instead of having to deserialize the CSP
811 * from the Client.
813 * Please note that at the time of CSP parsing the Client is not
814 * available yet, hence we sync CSP of document and Client when the
815 * Client becomes available within nsGlobalWindowInner::EnsureClientSource().
817 nsIContentSecurityPolicy* GetCsp() const;
818 void SetCsp(nsIContentSecurityPolicy* aCSP);
820 nsIContentSecurityPolicy* GetPreloadCsp() const;
821 void SetPreloadCsp(nsIContentSecurityPolicy* aPreloadCSP);
823 void GetCspJSON(nsString& aJSON);
826 * Set referrer policy and upgrade-insecure-requests flags
828 void ApplySettingsFromCSP(bool aSpeculative);
830 already_AddRefed<nsIParser> CreatorParserOrNull() {
831 nsCOMPtr<nsIParser> parser = mParser;
832 return parser.forget();
836 * ReferrerInfo getter for Document.webidl.
838 nsIReferrerInfo* ReferrerInfo() const { return GetReferrerInfo(); }
840 nsIReferrerInfo* GetReferrerInfo() const { return mReferrerInfo; }
842 nsIReferrerInfo* GetPreloadReferrerInfo() const {
843 return mPreloadReferrerInfo;
846 * Return the referrer policy of the document. Return "default" if there's no
847 * valid meta referrer tag found in the document.
848 * Referrer policy should be inherited from parent if the iframe is srcdoc
850 ReferrerPolicyEnum GetReferrerPolicy() const;
853 * GetReferrerPolicy() for Document.webidl.
855 ReferrerPolicyEnum ReferrerPolicy() const { return GetReferrerPolicy(); }
858 * If true, this flag indicates that all mixed content subresource
859 * loads for this document (and also embeded browsing contexts) will
860 * be blocked.
862 bool GetBlockAllMixedContent(bool aPreload) const {
863 if (aPreload) {
864 return mBlockAllMixedContentPreloads;
866 return mBlockAllMixedContent;
870 * If true, this flag indicates that all subresource loads for this
871 * document need to be upgraded from http to https.
872 * This flag becomes true if the CSP of the document itself, or any
873 * of the document's ancestors up to the toplevel document makes use
874 * of the CSP directive 'upgrade-insecure-requests'.
876 bool GetUpgradeInsecureRequests(bool aPreload) const {
877 if (aPreload) {
878 return mUpgradeInsecurePreloads;
880 return mUpgradeInsecureRequests;
883 void SetReferrerInfo(nsIReferrerInfo* aReferrerInfo) {
884 mReferrerInfo = aReferrerInfo;
888 * Referrer policy from <meta name="referrer" content=`policy`>
889 * will have higher priority than referrer policy from Referrer-Policy
890 * header. So override the old ReferrerInfo if we get one from meta
892 void UpdateReferrerInfoFromMeta(const nsAString& aMetaReferrer,
893 bool aPreload);
896 * Set the principals responsible for this document. Chances are, you do not
897 * want to be using this.
899 void SetPrincipals(nsIPrincipal* aPrincipal,
900 nsIPrincipal* aPartitionedPrincipal);
903 * Returns true if exempt from HTTPS-Only Mode upgrade.
905 uint32_t HttpsOnlyStatus() const { return mHttpsOnlyStatus; }
908 * Return the LoadGroup for the document. May return null.
910 already_AddRefed<nsILoadGroup> GetDocumentLoadGroup() const {
911 nsCOMPtr<nsILoadGroup> group = do_QueryReferent(mDocumentLoadGroup);
912 return group.forget();
916 * Return the fallback base URL for this document, as defined in the HTML
917 * specification. Note that this can return null if there is no document URI.
919 * XXXbz: This doesn't implement the bits for about:blank yet.
921 nsIURI* GetFallbackBaseURI() const {
922 if (mIsSrcdocDocument && mParentDocument) {
923 return mParentDocument->GetDocBaseURI();
925 return mDocumentURI;
929 * Return the referrer from document URI as defined in the Referrer Policy
930 * specification.
931 * https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
932 * While document is an iframe srcdoc document, let document be document's
933 * browsing context's browsing context container's node document.
934 * Then referrer should be document's URL
937 nsIURI* GetDocumentURIAsReferrer() const {
938 if (mIsSrcdocDocument && mParentDocument) {
939 return mParentDocument->GetDocumentURIAsReferrer();
941 return mDocumentURI;
945 * Return the base URI for relative URIs in the document (the document uri
946 * unless it's overridden by SetBaseURI, HTML <base> tags, etc.). The
947 * returned URI could be null if there is no document URI. If the document is
948 * a srcdoc document and has no explicit base URL, return the parent
949 * document's base URL.
951 nsIURI* GetDocBaseURI() const {
952 if (mDocumentBaseURI) {
953 return mDocumentBaseURI;
955 return GetFallbackBaseURI();
958 nsIURI* GetBaseURI(bool aTryUseXHRDocBaseURI = false) const final;
960 void SetBaseURI(nsIURI* aURI);
963 * Resolves a URI based on the document's base URI.
965 Result<OwningNonNull<nsIURI>, nsresult> ResolveWithBaseURI(
966 const nsAString& aURI);
969 * Return the URL data which style system needs for resolving url value.
970 * This method attempts to use the cached object in mCachedURLData, but
971 * if the base URI, document URI, or principal has changed since last
972 * call to this function, or the function is called the first time for
973 * the document, a new one is created.
975 URLExtraData* DefaultStyleAttrURLData();
978 * Get/Set the base target of a link in a document.
980 void GetBaseTarget(nsAString& aBaseTarget) const {
981 aBaseTarget = mBaseTarget;
984 void SetBaseTarget(const nsString& aBaseTarget) { mBaseTarget = aBaseTarget; }
987 * Return a standard name for the document's character set.
989 NotNull<const Encoding*> GetDocumentCharacterSet() const {
990 return mCharacterSet;
994 * Set the document's character encoding.
996 void SetDocumentCharacterSet(NotNull<const Encoding*> aEncoding);
998 int32_t GetDocumentCharacterSetSource() const { return mCharacterSetSource; }
1000 // This method MUST be called before SetDocumentCharacterSet if
1001 // you're planning to call both.
1002 void SetDocumentCharacterSetSource(int32_t aCharsetSource) {
1003 mCharacterSetSource = aCharsetSource;
1007 * Get the Content-Type of this document.
1009 void GetContentType(nsAString& aContentType);
1012 * Set the Content-Type of this document.
1014 virtual void SetContentType(const nsAString& aContentType);
1017 * Return the language of this document.
1019 void GetContentLanguage(nsAString& aContentLanguage) const {
1020 CopyASCIItoUTF16(mContentLanguage, aContentLanguage);
1023 // The states BidiEnabled and MathMLEnabled should persist across multiple
1024 // views (screen, print) of the same document.
1027 * Check if the document contains bidi data.
1028 * If so, we have to apply the Unicode Bidi Algorithm.
1030 bool GetBidiEnabled() const { return mBidiEnabled; }
1033 * Indicate the document contains bidi data.
1034 * Currently, we cannot disable bidi, because once bidi is enabled,
1035 * it affects a frame model irreversibly, and plays even though
1036 * the document no longer contains bidi data.
1038 void SetBidiEnabled() { mBidiEnabled = true; }
1040 void SetMathMLEnabled() { mMathMLEnabled = true; }
1043 * Ask this document whether it's the initial document in its window.
1045 bool IsInitialDocument() const { return mIsInitialDocumentInWindow; }
1048 * Tell this document that it's the initial document in its window. See
1049 * comments on mIsInitialDocumentInWindow for when this should be called.
1051 void SetIsInitialDocument(bool aIsInitialDocument);
1053 void SetLoadedAsData(bool aLoadedAsData, bool aConsiderForMemoryReporting);
1056 * Normally we assert if a runnable labeled with one DocGroup touches data
1057 * from another DocGroup. Calling IgnoreDocGroupMismatches() on a document
1058 * means that we can touch that document from any DocGroup without asserting.
1060 void IgnoreDocGroupMismatches() { mIgnoreDocGroupMismatches = true; }
1063 * Get the bidi options for this document.
1064 * @see nsBidiUtils.h
1066 uint32_t GetBidiOptions() const { return mBidiOptions; }
1069 * Set the bidi options for this document. This just sets the bits;
1070 * callers are expected to take action as needed if they want this
1071 * change to actually change anything immediately.
1072 * @see nsBidiUtils.h
1074 void SetBidiOptions(uint32_t aBidiOptions) { mBidiOptions = aBidiOptions; }
1077 * Set CSP flag for this document.
1079 void SetHasCSP(bool aHasCSP) { mHasCSP = aHasCSP; }
1082 * Set unsafe-inline CSP flag for this document.
1084 void SetHasUnsafeInlineCSP(bool aHasUnsafeInlineCSP) {
1085 mHasUnsafeInlineCSP = aHasUnsafeInlineCSP;
1089 * Set unsafe-eval CSP flag for this document.
1091 void SetHasUnsafeEvalCSP(bool aHasUnsafeEvalCSP) {
1092 mHasUnsafeEvalCSP = aHasUnsafeEvalCSP;
1096 * Returns true if the document holds a CSP
1097 * delivered through an HTTP Header.
1099 bool GetHasCSPDeliveredThroughHeader() {
1100 return mHasCSPDeliveredThroughHeader;
1104 * Return a promise which resolves to the content blocking events.
1106 using GetContentBlockingEventsPromise = MozPromise<uint32_t, bool, true>;
1107 [[nodiscard]] RefPtr<GetContentBlockingEventsPromise>
1108 GetContentBlockingEvents();
1111 * Get the sandbox flags for this document.
1112 * @see nsSandboxFlags.h for the possible flags
1114 uint32_t GetSandboxFlags() const { return mSandboxFlags; }
1116 Maybe<nsILoadInfo::CrossOriginEmbedderPolicy> GetEmbedderPolicy() const {
1117 return mEmbedderPolicy;
1120 void SetEmbedderPolicy(
1121 const Maybe<nsILoadInfo::CrossOriginEmbedderPolicy>& aCOEP) {
1122 mEmbedderPolicy = aCOEP;
1126 * Get string representation of sandbox flags (null if no flags are set)
1128 void GetSandboxFlagsAsString(nsAString& aFlags);
1131 * Set the sandbox flags for this document.
1132 * @see nsSandboxFlags.h for the possible flags
1134 void SetSandboxFlags(uint32_t sandboxFlags) { mSandboxFlags = sandboxFlags; }
1137 * Called when the document was decoded as UTF-8 and decoder encountered no
1138 * errors.
1140 void EnableEncodingMenu() { mEncodingMenuDisabled = false; }
1143 * Called to disable client access to cookies through the document.cookie API
1144 * from user JavaScript code.
1146 void DisableCookieAccess() { mDisableCookieAccess = true; }
1148 void SetLinkHandlingEnabled(bool aValue) { mLinksEnabled = aValue; }
1149 bool LinkHandlingEnabled() { return mLinksEnabled; }
1152 * Set compatibility mode for this document
1154 void SetCompatibilityMode(nsCompatibility aMode);
1157 * Called to disable client access to document.write() API from user
1158 * JavaScript code.
1160 void SetDocWriteDisabled(bool aDisabled) { mDisableDocWrite = aDisabled; }
1163 * Whether a document.write() call is in progress.
1165 bool IsWriting() const { return mWriteLevel != uint32_t(0); }
1168 * Access HTTP header data (this may also get set from other
1169 * sources, like HTML META tags).
1171 void GetHeaderData(nsAtom* aHeaderField, nsAString& aData) const;
1172 void SetHeaderData(nsAtom* aheaderField, const nsAString& aData);
1175 * Create a new presentation shell that will use aContext for its
1176 * presentation context (presentation contexts <b>must not</b> be
1177 * shared among multiple presentation shells). The caller of this
1178 * method is responsible for calling BeginObservingDocument() on the
1179 * presshell if the presshell should observe document mutations.
1181 already_AddRefed<PresShell> CreatePresShell(nsPresContext* aContext,
1182 nsViewManager* aViewManager);
1183 void DeletePresShell();
1185 PresShell* GetPresShell() const {
1186 return GetBFCacheEntry() ? nullptr : mPresShell;
1189 inline PresShell* GetObservingPresShell() const;
1191 // Return whether the presshell for this document is safe to flush.
1192 bool IsSafeToFlush() const;
1194 inline nsPresContext* GetPresContext() const;
1196 bool HasShellOrBFCacheEntry() const { return mPresShell || mBFCacheEntry; }
1198 // Instead using this method, what you probably want is
1199 // RemoveFromBFCacheSync() as we do in MessagePort and BroadcastChannel.
1200 void DisallowBFCaching();
1202 bool IsBFCachingAllowed() const { return !mBFCacheDisallowed; }
1204 // Accepts null to clear the BFCache entry too.
1205 void SetBFCacheEntry(nsIBFCacheEntry* aEntry);
1207 nsIBFCacheEntry* GetBFCacheEntry() const { return mBFCacheEntry; }
1209 // Removes this document from the BFCache, if it is cached, and returns
1210 // true if it was.
1211 bool RemoveFromBFCacheSync();
1214 * Return the parent document of this document. Will return null
1215 * unless this document is within a compound document and has a
1216 * parent. Note that this parent chain may cross chrome boundaries.
1218 Document* GetInProcessParentDocument() const { return mParentDocument; }
1221 * Set the parent document of this document.
1223 void SetParentDocument(Document* aParent) {
1224 mParentDocument = aParent;
1225 if (aParent) {
1226 mIgnoreDocGroupMismatches = aParent->mIgnoreDocGroupMismatches;
1227 if (!mIsDevToolsDocument) {
1228 mIsDevToolsDocument = mParentDocument->IsDevToolsDocument();
1234 * Are plugins allowed in this document ?
1236 bool GetAllowPlugins();
1239 * Set the sub document for aContent to aSubDoc.
1241 nsresult SetSubDocumentFor(Element* aContent, Document* aSubDoc);
1244 * Get the sub document for aContent
1246 Document* GetSubDocumentFor(nsIContent* aContent) const;
1249 * Get the content node for which this document is a sub document.
1251 Element* GetEmbedderElement() const;
1254 * Return the doctype for this document.
1256 DocumentType* GetDoctype() const;
1259 * Return the root element for this document.
1261 Element* GetRootElement() const;
1263 Selection* GetSelection(ErrorResult& aRv);
1265 already_AddRefed<Promise> HasStorageAccess(ErrorResult& aRv);
1266 already_AddRefed<Promise> RequestStorageAccess(ErrorResult& aRv);
1268 bool UseRegularPrincipal() const;
1271 * Gets the event target to dispatch key events to if there is no focused
1272 * content in the document.
1274 virtual Element* GetUnfocusedKeyEventTarget();
1277 * Retrieve information about the viewport as a data structure.
1278 * This will return information in the viewport META data section
1279 * of the document. This can be used in lieu of ProcessViewportInfo(),
1280 * which places the viewport information in the document header instead
1281 * of returning it directly.
1283 * @param aDisplaySize size of the on-screen display area for this
1284 * document, in device pixels.
1286 * NOTE: If the site is optimized for mobile (via the doctype), this
1287 * will return viewport information that specifies default information.
1289 nsViewportInfo GetViewportInfo(const ScreenIntSize& aDisplaySize);
1291 void AddMetaViewportElement(HTMLMetaElement* aElement,
1292 ViewportMetaData&& aData);
1293 void RemoveMetaViewportElement(HTMLMetaElement* aElement);
1295 // Returns a ViewportMetaData for this document.
1296 ViewportMetaData GetViewportMetaData() const;
1299 * True iff this doc will ignore manual character encoding overrides.
1301 virtual bool WillIgnoreCharsetOverride() { return true; }
1304 * Return whether the document was created by a srcdoc iframe.
1306 bool IsSrcdocDocument() const { return mIsSrcdocDocument; }
1309 * Sets whether the document was created by a srcdoc iframe.
1311 void SetIsSrcdocDocument(bool aIsSrcdocDocument) {
1312 mIsSrcdocDocument = aIsSrcdocDocument;
1316 * Gets the srcdoc string from within the channel (assuming both exist).
1317 * Returns a void string if this isn't a srcdoc document or if
1318 * the channel has not been set.
1320 nsresult GetSrcdocData(nsAString& aSrcdocData);
1322 already_AddRefed<AnonymousContent> InsertAnonymousContent(
1323 Element& aElement, ErrorResult& aError);
1324 void RemoveAnonymousContent(AnonymousContent& aContent, ErrorResult& aError);
1326 * If aNode is a descendant of anonymous content inserted by
1327 * InsertAnonymousContent, this method returns the root element of the
1328 * inserted anonymous content (in other words, the clone of the aElement
1329 * that was passed to InsertAnonymousContent).
1331 Element* GetAnonRootIfInAnonymousContentContainer(nsINode* aNode) const;
1332 nsTArray<RefPtr<AnonymousContent>>& GetAnonymousContents() {
1333 return mAnonymousContents;
1336 TimeStamp GetPageUnloadingEventTimeStamp() const {
1337 if (!mParentDocument) {
1338 return mPageUnloadingEventTimeStamp;
1341 TimeStamp parentTimeStamp(
1342 mParentDocument->GetPageUnloadingEventTimeStamp());
1343 if (parentTimeStamp.IsNull()) {
1344 return mPageUnloadingEventTimeStamp;
1347 if (!mPageUnloadingEventTimeStamp ||
1348 parentTimeStamp < mPageUnloadingEventTimeStamp) {
1349 return parentTimeStamp;
1352 return mPageUnloadingEventTimeStamp;
1355 void NotifyLayerManagerRecreated();
1358 * Add an SVG element to the list of elements that need
1359 * their mapped attributes resolved to a Servo declaration block.
1361 * These are weak pointers, please manually unschedule them when an element
1362 * is removed.
1364 void ScheduleSVGForPresAttrEvaluation(SVGElement* aSVG) {
1365 mLazySVGPresElements.Insert(aSVG);
1368 // Unschedule an element scheduled by ScheduleFrameRequestCallback (e.g. for
1369 // when it is destroyed)
1370 void UnscheduleSVGForPresAttrEvaluation(SVGElement* aSVG) {
1371 mLazySVGPresElements.Remove(aSVG);
1374 // Resolve all SVG pres attrs scheduled in ScheduleSVGForPresAttrEvaluation
1375 void ResolveScheduledSVGPresAttrs();
1377 Maybe<ClientInfo> GetClientInfo() const;
1378 Maybe<ClientState> GetClientState() const;
1379 Maybe<ServiceWorkerDescriptor> GetController() const;
1381 // Returns the size of the mBlockedNodesByClassifier array.
1383 // This array contains nodes that have been blocked to prevent user tracking,
1384 // fingerprinting, cryptomining, etc. They most likely have had their
1385 // nsIChannel canceled by the URL classifier (Safebrowsing).
1387 // A script can subsequently use GetBlockedNodesByClassifier()
1388 // to get a list of references to these nodes.
1390 // Note:
1391 // This expresses how many tracking nodes have been blocked for this document
1392 // since its beginning, not how many of them are still around in the DOM tree.
1393 // Weak references to blocked nodes are added in the mBlockedNodesByClassifier
1394 // array but they are not removed when those nodes are removed from the tree
1395 // or even garbage collected.
1396 long BlockedNodeByClassifierCount() const {
1397 return mBlockedNodesByClassifier.Length();
1401 // Returns strong references to mBlockedNodesByClassifier. (Document.h)
1403 // This array contains nodes that have been blocked to prevent
1404 // user tracking. They most likely have had their nsIChannel
1405 // canceled by the URL classifier (Safebrowsing).
1407 already_AddRefed<nsSimpleContentList> BlockedNodesByClassifier() const;
1409 // Helper method that returns true if the document has storage-access sandbox
1410 // flag.
1411 bool StorageAccessSandboxed() const;
1413 // Helper method that returns true if storage access API is enabled and
1414 // the passed flag has storage-access sandbox flag.
1415 static bool StorageAccessSandboxed(uint32_t aSandboxFlags);
1417 // Returns the cookie jar settings for this and sub contexts.
1418 nsICookieJarSettings* CookieJarSettings();
1420 // Returns whether this document has the storage access permission.
1421 bool HasStorageAccessPermissionGranted();
1423 // Increments the document generation.
1424 inline void Changed() { ++mGeneration; }
1426 // Returns the current generation.
1427 inline int32_t GetGeneration() const { return mGeneration; }
1429 // Adds cached sizes values to aSizes if there's any
1430 // cached value and if the document generation hasn't
1431 // changed since the cache was created.
1432 // Returns true if sizes were added.
1433 bool GetCachedSizes(nsTabSizes* aSizes);
1435 // Sets the cache sizes for the current generation.
1436 void SetCachedSizes(nsTabSizes* aSizes);
1439 * Should be called when an element's editable changes as a result of
1440 * changing its contentEditable attribute/property.
1442 * The change should be +1 if the contentEditable attribute/property was
1443 * changed to true, -1 if it was changed to false.
1445 void ChangeContentEditableCount(Element*, int32_t aChange);
1446 void DeferredContentEditableCountChange(Element*);
1448 enum class EditingState : int8_t {
1449 eTearingDown = -2,
1450 eSettingUp = -1,
1451 eOff = 0,
1452 eDesignMode,
1453 eContentEditable
1457 * Returns the editing state of the document (not editable, contentEditable or
1458 * designMode).
1460 EditingState GetEditingState() const { return mEditingState; }
1463 * Returns whether the document is editable.
1465 bool IsEditingOn() const {
1466 return GetEditingState() == EditingState::eDesignMode ||
1467 GetEditingState() == EditingState::eContentEditable;
1470 class MOZ_STACK_CLASS nsAutoEditingState {
1471 public:
1472 nsAutoEditingState(Document* aDoc, EditingState aState)
1473 : mDoc(aDoc), mSavedState(aDoc->mEditingState) {
1474 aDoc->mEditingState = aState;
1476 ~nsAutoEditingState() { mDoc->mEditingState = mSavedState; }
1478 private:
1479 RefPtr<Document> mDoc;
1480 EditingState mSavedState;
1482 friend class nsAutoEditingState;
1485 * Set the editing state of the document. Don't use this if you want
1486 * to enable/disable editing, call EditingStateChanged() or
1487 * SetDesignMode().
1489 void SetEditingState(EditingState aState) { mEditingState = aState; }
1492 * Called when this Document's editor is destroyed.
1494 void TearingDownEditor();
1496 void SetKeyPressEventModel(uint16_t aKeyPressEventModel);
1498 // Gets the next form number.
1500 // Used by nsContentUtils::GenerateStateKey to get a unique number for each
1501 // parser inserted form element.
1502 int32_t GetNextFormNumber() { return mNextFormNumber++; }
1504 // Gets the next form control number.
1506 // Used by nsContentUtils::GenerateStateKey to get a unique number for each
1507 // parser inserted form control element.
1508 int32_t GetNextControlNumber() { return mNextControlNumber++; }
1510 PreloadService& Preloads() { return mPreloadService; }
1512 bool HasThirdPartyChannel();
1514 bool ShouldIncludeInTelemetry(bool aAllowExtensionURIs);
1516 void AddMediaElementWithMSE();
1517 void RemoveMediaElementWithMSE();
1519 void DoNotifyPossibleTitleChange();
1521 protected:
1522 friend class nsUnblockOnloadEvent;
1524 nsresult InitCSP(nsIChannel* aChannel);
1525 nsresult InitCOEP(nsIChannel* aChannel);
1527 nsresult InitFeaturePolicy(nsIChannel* aChannel);
1529 nsresult InitReferrerInfo(nsIChannel* aChannel);
1531 void PostUnblockOnloadEvent();
1533 void DoUnblockOnload();
1535 void RetrieveRelevantHeaders(nsIChannel* aChannel);
1537 void TryChannelCharset(nsIChannel* aChannel, int32_t& aCharsetSource,
1538 NotNull<const Encoding*>& aEncoding,
1539 nsHtml5TreeOpExecutor* aExecutor);
1541 void DispatchContentLoadedEvents();
1543 void DispatchPageTransition(EventTarget* aDispatchTarget,
1544 const nsAString& aType, bool aInFrameSwap,
1545 bool aPersisted, bool aOnlySystemGroup);
1547 // Call this before the document does something that will unbind all content.
1548 // That will stop us from doing a lot of work as each element is removed.
1549 void DestroyElementMaps();
1551 Element* GetRootElementInternal() const;
1553 void SetPageUnloadingEventTimeStamp() {
1554 MOZ_ASSERT(!mPageUnloadingEventTimeStamp);
1555 mPageUnloadingEventTimeStamp = TimeStamp::NowLoRes();
1558 void CleanUnloadEventsTimeStamp() {
1559 MOZ_ASSERT(mPageUnloadingEventTimeStamp);
1560 mPageUnloadingEventTimeStamp = TimeStamp();
1564 * Clears any Servo element data stored on Elements in the document.
1566 void ClearStaleServoData();
1569 * Do the tree-disconnection that ResetToURI and document.open need to do.
1571 void DisconnectNodeTree();
1574 * MaybeDispatchCheckKeyPressEventModelEvent() dispatches
1575 * "CheckKeyPressEventModel" event to check whether we should dispatch
1576 * keypress events in confluent model or split model. This should be
1577 * called only when mEditingState is changed to eDesignMode or
1578 * eConentEditable at first time.
1580 void MaybeDispatchCheckKeyPressEventModelEvent();
1582 /* Midas implementation */
1583 nsCommandManager* GetMidasCommandManager();
1585 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsresult TurnEditingOff();
1587 // MOZ_CAN_RUN_SCRIPT_BOUNDARY because this is called from all sorts
1588 // of places, and I'm pretty sure the exact ExecCommand call it
1589 // makes cannot actually run script.
1590 MOZ_CAN_RUN_SCRIPT_BOUNDARY nsresult EditingStateChanged();
1592 void MaybeEditingStateChanged();
1594 private:
1595 class SelectorCacheKey {
1596 public:
1597 explicit SelectorCacheKey(const nsACString& aString) : mKey(aString) {
1598 MOZ_COUNT_CTOR(SelectorCacheKey);
1601 nsCString mKey;
1602 nsExpirationState mState;
1604 nsExpirationState* GetExpirationState() { return &mState; }
1606 MOZ_COUNTED_DTOR(SelectorCacheKey)
1609 class SelectorCacheKeyDeleter;
1611 public:
1612 class SelectorCache final : public nsExpirationTracker<SelectorCacheKey, 4> {
1613 public:
1614 using SelectorList = UniquePtr<RawServoSelectorList>;
1615 using Table = nsTHashMap<nsCStringHashKey, SelectorList>;
1617 explicit SelectorCache(nsIEventTarget* aEventTarget);
1618 void NotifyExpired(SelectorCacheKey*) final;
1620 // We do not call MarkUsed because it would just slow down lookups and
1621 // because we're OK expiring things after a few seconds even if they're
1622 // being used. Returns whether we actually had an entry for aSelector.
1624 // If we have an entry and the selector list returned has a null
1625 // RawServoSelectorList*, that indicates that aSelector has already been
1626 // parsed and is not a syntactically valid selector.
1627 template <typename F>
1628 RawServoSelectorList* GetListOrInsertFrom(const nsACString& aSelector,
1629 F&& aFrom) {
1630 MOZ_ASSERT(NS_IsMainThread());
1631 return mTable.LookupOrInsertWith(aSelector, std::forward<F>(aFrom)).get();
1634 ~SelectorCache();
1636 private:
1637 Table mTable;
1640 SelectorCache& GetSelectorCache() {
1641 if (!mSelectorCache) {
1642 mSelectorCache =
1643 MakeUnique<SelectorCache>(EventTargetFor(TaskCategory::Other));
1645 return *mSelectorCache;
1647 // Get the root <html> element, or return null if there isn't one (e.g.
1648 // if the root isn't <html>)
1649 Element* GetHtmlElement() const;
1650 // Returns the first child of GetHtmlContent which has the given tag,
1651 // or nullptr if that doesn't exist.
1652 Element* GetHtmlChildElement(nsAtom* aTag);
1653 // Get the canonical <body> element, or return null if there isn't one (e.g.
1654 // if the root isn't <html> or if the <body> isn't there)
1655 HTMLBodyElement* GetBodyElement();
1656 // Get the canonical <head> element, or return null if there isn't one (e.g.
1657 // if the root isn't <html> or if the <head> isn't there)
1658 Element* GetHeadElement() { return GetHtmlChildElement(nsGkAtoms::head); }
1659 // Get the "body" in the sense of document.body: The first <body> or
1660 // <frameset> that's a child of a root <html>
1661 nsGenericHTMLElement* GetBody();
1662 // Set the "body" in the sense of document.body.
1663 void SetBody(nsGenericHTMLElement* aBody, ErrorResult& rv);
1664 // Get the "head" element in the sense of document.head.
1665 HTMLSharedElement* GetHead();
1667 ServoStyleSet* StyleSetForPresShellOrMediaQueryEvaluation() const {
1668 return mStyleSet.get();
1671 // ShadowRoot has APIs that can change styles. This notifies the shell that
1672 // stlyes applicable in the shadow tree have potentially changed.
1673 void RecordShadowStyleChange(ShadowRoot&);
1675 // Needs to be called any time the applicable style can has changed, in order
1676 // to schedule a style flush and setup all the relevant state.
1677 void ApplicableStylesChanged();
1679 // Whether we filled the style set with any style sheet. Only meant to be used
1680 // from DocumentOrShadowRoot::Traverse.
1681 bool StyleSetFilled() const { return mStyleSetFilled; }
1684 * Accessors to the collection of stylesheets owned by this document.
1685 * Style sheets are ordered, most significant last.
1688 void InsertSheetAt(size_t aIndex, StyleSheet&);
1691 * Add a stylesheet to the document
1693 * TODO(emilio): This is only used by parts of editor that are no longer in
1694 * use by m-c or c-c, so remove.
1696 void AddStyleSheet(StyleSheet* aSheet) {
1697 MOZ_ASSERT(aSheet);
1698 InsertSheetAt(SheetCount(), *aSheet);
1702 * Notify the document that the applicable state of the sheet changed
1703 * and that observers should be notified and style sets updated
1705 void StyleSheetApplicableStateChanged(StyleSheet&);
1707 void PostStyleSheetApplicableStateChangeEvent(StyleSheet&);
1709 enum additionalSheetType {
1710 eAgentSheet,
1711 eUserSheet,
1712 eAuthorSheet,
1713 AdditionalSheetTypeCount
1716 nsresult LoadAdditionalStyleSheet(additionalSheetType aType,
1717 nsIURI* aSheetURI);
1718 nsresult AddAdditionalStyleSheet(additionalSheetType aType,
1719 StyleSheet* aSheet);
1720 void RemoveAdditionalStyleSheet(additionalSheetType aType, nsIURI* sheetURI);
1722 StyleSheet* GetFirstAdditionalAuthorSheet() {
1723 return mAdditionalSheets[eAuthorSheet].SafeElementAt(0);
1727 * Returns the index that aSheet should be inserted at to maintain document
1728 * ordering.
1730 size_t FindDocStyleSheetInsertionPoint(const StyleSheet& aSheet);
1733 * Get this document's CSSLoader. This is guaranteed to not return null.
1735 css::Loader* CSSLoader() const { return mCSSLoader; }
1738 * Get this document's StyleImageLoader. This is guaranteed to not return
1739 * null.
1741 css::ImageLoader* StyleImageLoader() const { return mStyleImageLoader; }
1744 * Get the channel that was passed to StartDocumentLoad or Reset for this
1745 * document. Note that this may be null in some cases (eg if
1746 * StartDocumentLoad or Reset were never called)
1748 nsIChannel* GetChannel() const { return mChannel; }
1751 * Get this document's attribute stylesheet. May return null if
1752 * there isn't one.
1754 nsHTMLStyleSheet* GetAttributeStyleSheet() const { return mAttrStyleSheet; }
1757 * Get this document's inline style sheet. May return null if there
1758 * isn't one
1760 nsHTMLCSSStyleSheet* GetInlineStyleSheet() const {
1761 return mStyleAttrStyleSheet;
1764 virtual void SetScriptGlobalObject(nsIScriptGlobalObject* aGlobalObject);
1767 * Get/set the object from which the context for the event/script handling can
1768 * be got. Normally GetScriptHandlingObject() returns the same object as
1769 * GetScriptGlobalObject(), but if the document is loaded as data,
1770 * non-null may be returned, even if GetScriptGlobalObject() returns null.
1771 * aHasHadScriptHandlingObject is set true if document has had the object
1772 * for event/script handling. Do not process any events/script if the method
1773 * returns null, but aHasHadScriptHandlingObject is true.
1775 nsIScriptGlobalObject* GetScriptHandlingObject(
1776 bool& aHasHadScriptHandlingObject) const {
1777 aHasHadScriptHandlingObject = mHasHadScriptHandlingObject;
1778 return mScriptGlobalObject ? mScriptGlobalObject.get()
1779 : GetScriptHandlingObjectInternal();
1781 void SetScriptHandlingObject(nsIScriptGlobalObject* aScriptObject);
1784 * Get the object that is used as the scope for all of the content
1785 * wrappers whose owner document is this document. Unlike the script global
1786 * object, this will only return null when the global object for this
1787 * document is truly gone. Use this object when you're trying to find a
1788 * content wrapper in XPConnect.
1790 nsIGlobalObject* GetScopeObject() const;
1791 void SetScopeObject(nsIGlobalObject* aGlobal);
1794 * Return the cross-origin-isolated state from browsing context. If it's a
1795 * data document, we get its creator's state.
1797 bool CrossOriginIsolated() const;
1800 * Return the window containing the document (the outer window).
1802 nsPIDOMWindowOuter* GetWindow() const {
1803 return mWindow ? mWindow->GetOuterWindow() : GetWindowInternal();
1806 bool IsInBackgroundWindow() const {
1807 auto* outer = mWindow ? mWindow->GetOuterWindow() : nullptr;
1808 return outer && outer->IsBackground();
1812 * Return the inner window used as the script compilation scope for
1813 * this document. If you're not absolutely sure you need this, use
1814 * GetWindow().
1816 nsPIDOMWindowInner* GetInnerWindow() const {
1817 return mRemovedFromDocShell ? nullptr : mWindow;
1821 * Return the outer window ID.
1823 uint64_t OuterWindowID() const {
1824 nsPIDOMWindowOuter* window = GetWindow();
1825 return window ? window->WindowID() : 0;
1829 * Return the inner window ID.
1831 uint64_t InnerWindowID() const {
1832 nsPIDOMWindowInner* window = GetInnerWindow();
1833 return window ? window->WindowID() : 0;
1837 * Return WindowGlobalChild that is associated with the inner window.
1839 WindowGlobalChild* GetWindowGlobalChild() {
1840 return GetInnerWindow() ? GetInnerWindow()->GetWindowGlobalChild()
1841 : nullptr;
1845 * Return WindowContext associated with the inner window.
1847 WindowContext* GetWindowContext() const {
1848 return GetInnerWindow() ? GetInnerWindow()->GetWindowContext() : nullptr;
1851 bool IsTopLevelWindowInactive() const;
1854 * Get the script loader for this document
1856 dom::ScriptLoader* ScriptLoader() { return mScriptLoader; }
1859 * Add/Remove an element to the document's id and name hashes
1861 void AddToIdTable(Element* aElement, nsAtom* aId);
1862 void RemoveFromIdTable(Element* aElement, nsAtom* aId);
1863 void AddToNameTable(Element* aElement, nsAtom* aName);
1864 void RemoveFromNameTable(Element* aElement, nsAtom* aName);
1867 * Returns all elements in the top layer in the insertion order.
1869 nsTArray<Element*> GetTopLayer() const;
1872 * Asynchronously requests that the document make aElement the fullscreen
1873 * element, and move into fullscreen mode. The current fullscreen element
1874 * (if any) is pushed onto the top layer, and it can be
1875 * returned to fullscreen status by calling RestorePreviousFullscreenState().
1877 * Note that requesting fullscreen in a document also makes the element which
1878 * contains this document in this document's parent document fullscreen. i.e.
1879 * the <iframe> or <browser> that contains this document is also mode
1880 * fullscreen. This happens recursively in all ancestor documents.
1882 void AsyncRequestFullscreen(UniquePtr<FullscreenRequest>);
1884 // Do the "fullscreen element ready check" from the fullscreen spec.
1885 // It returns true if the given element is allowed to go into fullscreen.
1886 // It is responsive to dispatch "fullscreenerror" event when necessary.
1887 bool FullscreenElementReadyCheck(FullscreenRequest&);
1889 // This is called asynchronously by Document::AsyncRequestFullscreen()
1890 // to move this document into fullscreen mode if allowed.
1891 void RequestFullscreen(UniquePtr<FullscreenRequest> aRequest,
1892 bool applyFullScreenDirectly = false);
1894 private:
1895 void RequestFullscreenInContentProcess(UniquePtr<FullscreenRequest> aRequest,
1896 bool applyFullScreenDirectly);
1897 void RequestFullscreenInParentProcess(UniquePtr<FullscreenRequest> aRequest,
1898 bool applyFullScreenDirectly);
1900 public:
1901 // Removes all the elements with fullscreen flag set from the top layer, and
1902 // clears their fullscreen flag.
1903 void CleanupFullscreenState();
1905 // Pushes aElement onto the top layer
1906 void TopLayerPush(Element* aElement);
1908 // Removes the topmost element which have aPredicate return true from the top
1909 // layer. The removed element, if any, is returned.
1910 Element* TopLayerPop(FunctionRef<bool(Element*)> aPredicateFunc);
1912 // Pops the fullscreen element from the top layer and clears its
1913 // fullscreen flag.
1914 void UnsetFullscreenElement();
1916 // Pushes the given element into the top of top layer and set fullscreen
1917 // flag.
1918 void SetFullscreenElement(Element* aElement);
1920 // Cancel the dialog element if the document is blocked by the dialog
1921 void TryCancelDialog();
1923 void SetBlockedByModalDialog(HTMLDialogElement&);
1925 void UnsetBlockedByModalDialog(HTMLDialogElement&);
1928 * Called when a frame in a child process has entered fullscreen or when a
1929 * fullscreen frame in a child process changes to another origin.
1930 * aFrameElement is the frame element which contains the child-process
1931 * fullscreen document.
1933 void RemoteFrameFullscreenChanged(Element* aFrameElement);
1936 * Called when a frame in a remote child document has rolled back fullscreen
1937 * so that all its top layer are empty; we must continue the
1938 * rollback in this parent process' doc tree branch which is fullscreen.
1939 * Note that only one branch of the document tree can have its documents in
1940 * fullscreen state at one time. We're in inconsistent state if a
1941 * fullscreen document has a parent and that parent isn't fullscreen. We
1942 * preserve this property across process boundaries.
1944 void RemoteFrameFullscreenReverted();
1947 * Restores the previous fullscreen element to fullscreen status. If there
1948 * is no former fullscreen element, this exits fullscreen, moving the
1949 * top-level browser window out of fullscreen mode.
1951 void RestorePreviousFullscreenState(UniquePtr<FullscreenExit>);
1954 * Returns true if this document is a fullscreen leaf document, i.e. it
1955 * is in fullscreen mode and has no fullscreen children.
1957 bool IsFullscreenLeaf();
1960 * Returns the document which is at the root of this document's branch
1961 * in the in-process document tree. Returns nullptr if the document isn't
1962 * fullscreen.
1964 Document* GetFullscreenRoot();
1966 size_t CountFullscreenElements() const;
1969 * Sets the fullscreen root to aRoot. This stores a weak reference to aRoot
1970 * in this document.
1972 void SetFullscreenRoot(Document* aRoot);
1975 * Synchronously cleans up the fullscreen state on the given document.
1977 * Calling this without performing fullscreen transition could lead
1978 * to undesired effect (the transition happens after document state
1979 * flips), hence it should only be called either by nsGlobalWindow
1980 * when we have performed the transition, or when it is necessary to
1981 * clean up the state immediately. Otherwise, AsyncExitFullscreen()
1982 * should be called instead.
1984 * aDocument must not be null.
1986 static void ExitFullscreenInDocTree(Document* aDocument);
1989 * Ask the document to exit fullscreen state asynchronously.
1991 * Different from ExitFullscreenInDocTree(), this allows the window
1992 * to perform fullscreen transition first if any.
1994 * If aDocument is null, it will exit fullscreen from all documents
1995 * in all windows.
1997 static void AsyncExitFullscreen(Document* aDocument);
2000 * Handles any pending fullscreen in aDocument or its subdocuments.
2002 * Returns whether there is any fullscreen request handled.
2004 static bool HandlePendingFullscreenRequests(Document* aDocument);
2006 // ScreenOrientation related APIs
2008 void ClearOrientationPendingPromise();
2009 bool SetOrientationPendingPromise(Promise* aPromise);
2010 Promise* GetOrientationPendingPromise() const {
2011 return mOrientationPendingPromise;
2014 //----------------------------------------------------------------------
2016 // Document notification API's
2019 * Add a new observer of document change notifications. Whenever
2020 * content is changed, appended, inserted or removed the observers are
2021 * informed. An observer that is already observing the document must
2022 * not be added without being removed first.
2024 void AddObserver(nsIDocumentObserver* aObserver);
2027 * Remove an observer of document change notifications. This will
2028 * return false if the observer cannot be found.
2030 bool RemoveObserver(nsIDocumentObserver* aObserver);
2032 // Observation hooks used to propagate notifications to document observers.
2033 // BeginUpdate must be called before any batch of modifications of the
2034 // content model or of style data, EndUpdate must be called afterward.
2035 // To make this easy and painless, use the mozAutoDocUpdate helper class.
2036 void BeginUpdate();
2037 void EndUpdate();
2038 uint32_t UpdateNestingLevel() { return mUpdateNestLevel; }
2040 void BeginLoad();
2041 virtual void EndLoad();
2043 enum ReadyState {
2044 READYSTATE_UNINITIALIZED = 0,
2045 READYSTATE_LOADING = 1,
2046 READYSTATE_INTERACTIVE = 3,
2047 READYSTATE_COMPLETE = 4
2049 // Set the readystate of the document. If aUpdateTimingInformation is true,
2050 // this will record relevant timestamps in the document's performance timing.
2051 // Some consumers (document.open is the only one right now, actually) don't
2052 // want to do that, though.
2053 void SetReadyStateInternal(ReadyState, bool aUpdateTimingInformation = true);
2054 ReadyState GetReadyStateEnum() { return mReadyState; }
2056 void NotifyLoading(bool aNewParentIsLoading, const ReadyState& aCurrentState,
2057 ReadyState aNewState);
2059 void NotifyAbortedLoad();
2061 // notify that a content node changed state. This must happen under
2062 // a scriptblocker but NOT within a begin/end update.
2063 void ContentStateChanged(nsIContent* aContent, EventStates aStateMask);
2065 // Update a set of document states that may have changed.
2066 // This should only be called by callers whose state is also reflected in the
2067 // implementation of Document::GetDocumentState.
2069 // aNotify controls whether we notify our DocumentStatesChanged observers.
2070 void UpdateDocumentStates(EventStates aStateMask, bool aNotify);
2072 void ResetDocumentDirection();
2074 // Observation hooks for style data to propagate notifications
2075 // to document observers
2076 void RuleChanged(StyleSheet&, css::Rule*, StyleRuleChangeKind);
2077 void RuleAdded(StyleSheet&, css::Rule&);
2078 void RuleRemoved(StyleSheet&, css::Rule&);
2079 void SheetCloned(StyleSheet&) {}
2080 void ImportRuleLoaded(CSSImportRule&, StyleSheet&);
2083 * Flush notifications for this document and its parent documents
2084 * (since those may affect the layout of this one).
2086 void FlushPendingNotifications(FlushType aType);
2089 * Another variant of the above FlushPendingNotifications. This function
2090 * takes a ChangesToFlush to specify whether throttled animations are flushed
2091 * or not.
2092 * If in doubt, use the above FlushPendingNotifications.
2094 MOZ_CAN_RUN_SCRIPT_BOUNDARY
2095 void FlushPendingNotifications(ChangesToFlush aFlush);
2098 * Calls FlushPendingNotifications on any external resources this document
2099 * has. If this document has no external resources or is an external resource
2100 * itself this does nothing. This should only be called with
2101 * aType >= FlushType::Style.
2103 void FlushExternalResources(FlushType aType);
2105 // Triggers an update of <svg:use> element shadow trees.
2106 void UpdateSVGUseElementShadowTrees() {
2107 if (mSVGUseElementsNeedingShadowTreeUpdate.IsEmpty()) {
2108 return;
2110 DoUpdateSVGUseElementShadowTrees();
2114 * Only to be used inside Gecko, you can't really do anything with the
2115 * pointer outside Gecko anyway.
2117 nsNodeInfoManager* NodeInfoManager() const { return mNodeInfoManager; }
2120 * Reset the document using the given channel and loadgroup. This works
2121 * like ResetToURI, but also sets the document's channel to aChannel.
2122 * The principal of the document will be set from the channel.
2124 virtual void Reset(nsIChannel* aChannel, nsILoadGroup* aLoadGroup);
2127 * Reset this document to aURI, aLoadGroup, aPrincipal and
2128 * aPartitionedPrincipal. aURI must not be null. If aPrincipal is null, a
2129 * content principal based on aURI will be used.
2131 virtual void ResetToURI(nsIURI* aURI, nsILoadGroup* aLoadGroup,
2132 nsIPrincipal* aPrincipal,
2133 nsIPrincipal* aPartitionedPrincipal);
2136 * Set the container (docshell) for this document. Virtual so that
2137 * docshell can call it.
2139 virtual void SetContainer(nsDocShell* aContainer);
2142 * Get the container (docshell) for this document.
2144 nsISupports* GetContainer() const;
2147 * Get the container's load context for this document.
2149 nsILoadContext* GetLoadContext() const;
2152 * Get docshell the for this document.
2154 nsIDocShell* GetDocShell() const;
2157 * Set and get XML declaration. If aVersion is null there is no declaration.
2158 * aStandalone takes values -1, 0 and 1 indicating respectively that there
2159 * was no standalone parameter in the declaration, that it was given as no,
2160 * or that it was given as yes.
2162 void SetXMLDeclaration(const char16_t* aVersion, const char16_t* aEncoding,
2163 const int32_t aStandalone);
2164 void GetXMLDeclaration(nsAString& aVersion, nsAString& aEncoding,
2165 nsAString& Standalone);
2168 * Returns the bits for the color-scheme specified by the
2169 * <meta name="color-scheme">.
2171 * TODO(emilio): Actually process the meta tag.
2173 uint8_t GetColorSchemeBits() const { return mColorSchemeBits; }
2176 * Returns true if this is what HTML 5 calls an "HTML document" (for example
2177 * regular HTML document with Content-Type "text/html", image documents and
2178 * media documents). Returns false for XHTML and any other documents parsed
2179 * by the XML parser.
2181 bool IsHTMLDocument() const { return mType == eHTML; }
2182 bool IsHTMLOrXHTML() const { return mType == eHTML || mType == eXHTML; }
2183 bool IsXMLDocument() const { return !IsHTMLDocument(); }
2184 bool IsSVGDocument() const { return mType == eSVG; }
2185 bool IsUnstyledDocument() { return IsLoadedAsData(); }
2186 bool LoadsFullXULStyleSheetUpFront() {
2187 if (IsSVGDocument()) {
2188 return false;
2190 return AllowXULXBL();
2193 bool IsScriptEnabled();
2196 * Returns true if this document was created from a nsXULPrototypeDocument.
2198 bool LoadedFromPrototype() const { return mPrototypeDocument; }
2200 * Returns the prototype the document was created from, or null if it was not
2201 * created from a prototype.
2203 nsXULPrototypeDocument* GetPrototype() const { return mPrototypeDocument; }
2205 bool IsTopLevelContentDocument() const { return mIsTopLevelContentDocument; }
2206 void SetIsTopLevelContentDocument(bool aIsTopLevelContentDocument) {
2207 mIsTopLevelContentDocument = aIsTopLevelContentDocument;
2210 bool IsContentDocument() const { return mIsContentDocument; }
2211 void SetIsContentDocument(bool aIsContentDocument) {
2212 mIsContentDocument = aIsContentDocument;
2215 void ProcessMETATag(HTMLMetaElement* aMetaElement);
2217 * Create an element with the specified name, prefix and namespace ID.
2218 * Returns null if element name parsing failed.
2220 already_AddRefed<Element> CreateElem(const nsAString& aName, nsAtom* aPrefix,
2221 int32_t aNamespaceID,
2222 const nsAString* aIs = nullptr);
2225 * Get the security info (i.e. SSL state etc) that the document got
2226 * from the channel/document that created the content of the
2227 * document.
2229 * @see nsIChannel
2231 nsISupports* GetSecurityInfo() { return mSecurityInfo; }
2234 * Get the channel that failed to load and resulted in an error page, if it
2235 * exists. This is only relevant to error pages.
2237 nsIChannel* GetFailedChannel() const { return mFailedChannel; }
2240 * This function checks if the document that is trying to access
2241 * GetNetErrorInfo is a trusted about net error page or not.
2243 static bool CallerIsTrustedAboutNetError(JSContext* aCx, JSObject* aObject);
2246 * Get security info like error code for a failed channel. This
2247 * property is only exposed to about:neterror documents.
2249 void GetNetErrorInfo(mozilla::dom::NetErrorInfo& aInfo, ErrorResult& aRv);
2252 * This function checks if the document that is trying to access
2253 * GetFailedCertSecurityInfo is a trusted cert error page or not.
2255 static bool CallerIsTrustedAboutCertError(JSContext* aCx, JSObject* aObject);
2258 * Get the security info (i.e. certificate validity, errorCode, etc) for a
2259 * failed Channel. This property is only exposed for about:certerror
2260 * documents.
2262 void GetFailedCertSecurityInfo(mozilla::dom::FailedCertSecurityInfo& aInfo,
2263 ErrorResult& aRv);
2266 * Controls whether or not we allow TLS 1.0/1.1. Only exposed to error pages.
2268 bool AllowDeprecatedTls();
2269 void SetAllowDeprecatedTls(bool aResult);
2272 * Set the channel that failed to load and resulted in an error page.
2273 * This is only relevant to error pages.
2275 void SetFailedChannel(nsIChannel* aChannel) { mFailedChannel = aChannel; }
2278 * Returns the default namespace ID used for elements created in this
2279 * document.
2281 int32_t GetDefaultNamespaceID() const { return mDefaultElementType; }
2283 void RemoveAllProperties();
2284 void RemoveAllPropertiesFor(nsINode* aNode);
2286 nsPropertyTable& PropertyTable() { return mPropertyTable; }
2289 * Sets the ID used to identify this part of the multipart document
2291 void SetPartID(uint32_t aID) { mPartID = aID; }
2294 * Return the ID used to identify this part of the multipart document
2296 uint32_t GetPartID() const { return mPartID; }
2299 * Sanitize the document by resetting all input elements and forms that have
2300 * autocomplete=off to their default values.
2302 void Sanitize();
2305 * Enumerate all subdocuments.
2306 * The enumerator callback should return CallState::Continue to continue
2307 * enumerating, or CallState::Stop to stop. This will never get passed a null
2308 * aDocument.
2310 using SubDocEnumFunc = FunctionRef<CallState(Document&)>;
2311 void EnumerateSubDocuments(SubDocEnumFunc aCallback);
2314 * Collect all the descendant documents for which |aCalback| returns true.
2315 * The callback function must not mutate any state for the given document.
2317 using nsDocTestFunc = bool (*)(const Document* aDocument);
2318 void CollectDescendantDocuments(nsTArray<RefPtr<Document>>& aDescendants,
2319 nsDocTestFunc aCallback) const;
2322 * Check whether it is safe to cache the presentation of this document
2323 * and all of its subdocuments (depending on the 3rd param). This method
2324 * checks the following conditions recursively:
2325 * - Some document types, such as plugin documents, cannot be safely cached.
2326 * - If there are any pending requests, we don't allow the presentation
2327 * to be cached. Ideally these requests would be suspended and resumed,
2328 * but that is difficult in some cases, such as XMLHttpRequest.
2329 * - If there are any beforeunload or unload listeners, we must fire them
2330 * for correctness, but this likely puts the document into a state where
2331 * it would not function correctly if restored.
2333 * |aNewRequest| should be the request for a new document which will
2334 * replace this document in the docshell. The new document's request
2335 * will be ignored when checking for active requests. If there is no
2336 * request associated with the new document, this parameter may be null.
2338 * |aBFCacheCombo| is used as a bitmask to indicate what the status
2339 * combination is when we try to BFCache aNewRequest
2341 virtual bool CanSavePresentation(nsIRequest* aNewRequest,
2342 uint16_t& aBFCacheCombo,
2343 bool aIncludeSubdocuments,
2344 bool aAllowUnloadListeners = true);
2346 virtual nsresult Init();
2349 * Notify the document that its associated ContentViewer is being destroyed.
2350 * This releases circular references so that the document can go away.
2351 * Destroy() is only called on documents that have a content viewer.
2353 virtual void Destroy();
2356 * Notify the document that its associated ContentViewer is no longer
2357 * the current viewer for the docshell. The document might still
2358 * be rendered in "zombie state" until the next document is ready.
2359 * The document should save form control state.
2361 void RemovedFromDocShell();
2364 * Get the layout history state that should be used to save and restore state
2365 * for nodes in this document. This may return null; if that happens state
2366 * saving and restoration is not possible.
2368 already_AddRefed<nsILayoutHistoryState> GetLayoutHistoryState() const;
2371 * Methods that can be used to prevent onload firing while an event that
2372 * should block onload is posted. onload is guaranteed to not fire until
2373 * either all calls to BlockOnload() have been matched by calls to
2374 * UnblockOnload() or the load has been stopped altogether (by the user
2375 * pressing the Stop button, say).
2377 void BlockOnload();
2379 * @param aFireSync whether to fire onload synchronously. If false,
2380 * onload will fire asynchronously after all onload blocks have been
2381 * removed. It will NOT fire from inside UnblockOnload. If true,
2382 * onload may fire from inside UnblockOnload.
2384 void UnblockOnload(bool aFireSync);
2386 // Only BlockOnload should call this!
2387 void AsyncBlockOnload();
2389 void BlockDOMContentLoaded() { ++mBlockDOMContentLoaded; }
2391 void UnblockDOMContentLoaded();
2394 * Notification that the page has been shown, for documents which are loaded
2395 * into a DOM window. This corresponds to the completion of document load,
2396 * or to the page's presentation being restored into an existing DOM window.
2397 * This notification fires applicable DOM events to the content window. See
2398 * PageTransitionEvent.webidl for a description of the |aPersisted|
2399 * parameter. If aDispatchStartTarget is null, the pageshow event is
2400 * dispatched on the ScriptGlobalObject for this document, otherwise it's
2401 * dispatched on aDispatchStartTarget. If |aOnlySystemGroup| is true, the
2402 * event is only dispatched to listeners in the system group.
2403 * Note: if aDispatchStartTarget isn't null, the showing state of the
2404 * document won't be altered.
2406 virtual void OnPageShow(bool aPersisted, EventTarget* aDispatchStartTarget,
2407 bool aOnlySystemGroup = false);
2410 * Notification that the page has been hidden, for documents which are loaded
2411 * into a DOM window. This corresponds to the unloading of the document, or
2412 * to the document's presentation being saved but removed from an existing
2413 * DOM window. This notification fires applicable DOM events to the content
2414 * window. See PageTransitionEvent.webidl for a description of the
2415 * |aPersisted| parameter. If aDispatchStartTarget is null, the pagehide
2416 * event is dispatched on the ScriptGlobalObject for this document,
2417 * otherwise it's dispatched on aDispatchStartTarget. If |aOnlySystemGroup| is
2418 * true, the event is only dispatched to listeners in the system group.
2419 * Note: if aDispatchStartTarget isn't null, the showing state of the
2420 * document won't be altered.
2422 void OnPageHide(bool aPersisted, EventTarget* aDispatchStartTarget,
2423 bool aOnlySystemGroup = false);
2426 * We record the set of links in the document that are relevant to
2427 * style.
2430 * Notification that an element is a link that is relevant to style.
2432 void AddStyleRelevantLink(Link* aLink) {
2433 NS_ASSERTION(aLink, "Passing in a null link. Expect crashes RSN!");
2434 #ifdef DEBUG
2435 NS_ASSERTION(!mStyledLinks.Contains(aLink),
2436 "Document already knows about this Link!");
2437 mStyledLinksCleared = false;
2438 #endif
2439 mStyledLinks.Insert(aLink);
2443 * Notification that an element is a link and its URI might have been
2444 * changed or the element removed. If the element is still a link relevant
2445 * to style, then someone must ensure that AddStyleRelevantLink is
2446 * (eventually) called on it again.
2448 void ForgetLink(Link* aLink) {
2449 NS_ASSERTION(aLink, "Passing in a null link. Expect crashes RSN!");
2450 #ifdef DEBUG
2451 bool linkContained = mStyledLinks.Contains(aLink);
2452 NS_ASSERTION(linkContained || mStyledLinksCleared,
2453 "Document knows nothing about this Link!");
2454 #endif
2455 mStyledLinks.Remove(aLink);
2458 // Refreshes the hrefs of all the links in the document.
2459 void RefreshLinkHrefs();
2462 * Support for window.matchMedia()
2465 already_AddRefed<MediaQueryList> MatchMedia(const nsACString& aMediaQueryList,
2466 CallerType aCallerType);
2468 LinkedList<MediaQueryList>& MediaQueryLists() { return mDOMMediaQueryLists; }
2471 * Get the compatibility mode for this document
2473 nsCompatibility GetCompatibilityMode() const { return mCompatMode; }
2476 * Check whether we've ever fired a DOMTitleChanged event for this
2477 * document.
2479 bool HaveFiredDOMTitleChange() const { return mHaveFiredTitleChange; }
2482 * To batch DOMSubtreeModified, document needs to be informed when
2483 * a mutation event might be dispatched, even if the event isn't actually
2484 * created because there are no listeners for it.
2486 * @param aTarget is the target for the mutation event.
2488 void MayDispatchMutationEvent(nsINode* aTarget) {
2489 if (mSubtreeModifiedDepth > 0) {
2490 mSubtreeModifiedTargets.AppendObject(aTarget);
2495 * Marks as not-going-to-be-collected for the given generation of
2496 * cycle collection.
2498 void MarkUncollectableForCCGeneration(uint32_t aGeneration) {
2499 mMarkedCCGeneration = aGeneration;
2503 * Gets the cycle collector generation this document is marked for.
2505 uint32_t GetMarkedCCGeneration() { return mMarkedCCGeneration; }
2508 * Returns whether this document is cookie averse. See
2509 * https://html.spec.whatwg.org/multipage/dom.html#cookie-averse-document-object
2511 bool IsCookieAverse() const {
2512 // If we are a document that "has no browsing context."
2513 if (!GetInnerWindow()) {
2514 return true;
2517 // If we are a document "whose URL's scheme is not a network scheme."
2518 // NB: Explicitly allow file: URIs to store cookies.
2520 return !NodePrincipal()->SchemeIs("http") &&
2521 !NodePrincipal()->SchemeIs("https") &&
2522 !NodePrincipal()->SchemeIs("file");
2525 bool IsLoadedAsData() { return mLoadedAsData; }
2527 void SetAddedToMemoryReportAsDataDocument() {
2528 mAddedToMemoryReportingAsDataDocument = true;
2531 void UnregisterFromMemoryReportingForDataDocument();
2533 bool MayStartLayout() { return mMayStartLayout; }
2535 void SetMayStartLayout(bool aMayStartLayout);
2537 already_AddRefed<nsIDocumentEncoder> GetCachedEncoder();
2539 void SetCachedEncoder(already_AddRefed<nsIDocumentEncoder> aEncoder);
2541 // In case of failure, the document really can't initialize the frame loader.
2542 nsresult InitializeFrameLoader(nsFrameLoader* aLoader);
2543 // In case of failure, the caller must handle the error, for example by
2544 // finalizing frame loader asynchronously.
2545 nsresult FinalizeFrameLoader(nsFrameLoader* aLoader, nsIRunnable* aFinalizer);
2546 // Removes the frame loader of aShell from the initialization list.
2547 void TryCancelFrameLoaderInitialization(nsIDocShell* aShell);
2550 * Check whether this document is a root document that is not an
2551 * external resource.
2553 bool IsRootDisplayDocument() const {
2554 return !mParentDocument && !mDisplayDocument;
2557 bool IsDocumentURISchemeChrome() const { return mDocURISchemeIsChrome; }
2559 bool IsInChromeDocShell() const {
2560 const Document* root = this;
2561 while (const Document* displayDoc = root->GetDisplayDocument()) {
2562 root = displayDoc;
2564 return root->mInChromeDocShell;
2567 bool IsDevToolsDocument() const { return mIsDevToolsDocument; }
2569 bool IsBeingUsedAsImage() const { return mIsBeingUsedAsImage; }
2571 void SetIsBeingUsedAsImage() { mIsBeingUsedAsImage = true; }
2573 bool IsSVGGlyphsDocument() const { return mIsSVGGlyphsDocument; }
2575 void SetIsSVGGlyphsDocument() { mIsSVGGlyphsDocument = true; }
2577 bool IsResourceDoc() const {
2578 return IsBeingUsedAsImage() || // Are we a helper-doc for an SVG image?
2579 mHasDisplayDocument; // Are we an external resource doc?
2583 * Get the document for which this document is an external resource. This
2584 * will be null if this document is not an external resource. Otherwise,
2585 * GetDisplayDocument() will return a non-null document, and
2586 * GetDisplayDocument()->GetDisplayDocument() is guaranteed to be null.
2588 Document* GetDisplayDocument() const { return mDisplayDocument; }
2591 * Set the display document for this document. aDisplayDocument must not be
2592 * null.
2594 void SetDisplayDocument(Document* aDisplayDocument) {
2595 MOZ_ASSERT(!GetPresShell() && !GetContainer() && !GetWindow(),
2596 "Shouldn't set mDisplayDocument on documents that already "
2597 "have a presentation or a docshell or a window");
2598 MOZ_ASSERT(aDisplayDocument, "Must not be null");
2599 MOZ_ASSERT(aDisplayDocument != this, "Should be different document");
2600 MOZ_ASSERT(!aDisplayDocument->GetDisplayDocument(),
2601 "Display documents should not nest");
2602 mDisplayDocument = aDisplayDocument;
2603 mHasDisplayDocument = !!aDisplayDocument;
2607 * Request an external resource document for aURI. This will return the
2608 * resource document if available. If one is not available yet, it will
2609 * start loading as needed, and the pending load object will be returned in
2610 * aPendingLoad so that the caller can register an observer to wait for the
2611 * load. If this function returns null and doesn't return a pending load,
2612 * that means that there is no resource document for this URI and won't be
2613 * one in the future.
2615 * @param aURI the URI to get
2616 * @param aReferrerInfo the referrerInfo of the request
2617 * @param aRequestingNode the node making the request
2618 * @param aPendingLoad the pending load for this request, if any
2620 Document* RequestExternalResource(nsIURI* aURI,
2621 nsIReferrerInfo* aReferrerInfo,
2622 nsINode* aRequestingNode,
2623 ExternalResourceLoad** aPendingLoad);
2626 * Enumerate the external resource documents associated with this document.
2627 * The enumerator callback should return CallState::Continue to continue
2628 * enumerating, or CallState::Stop to stop. This callback will never get
2629 * passed a null aDocument.
2631 void EnumerateExternalResources(SubDocEnumFunc aCallback);
2633 dom::ExternalResourceMap& ExternalResourceMap() {
2634 return mExternalResourceMap;
2638 * Return whether the document is currently showing (in the sense of
2639 * OnPageShow() having been called already and OnPageHide() not having been
2640 * called yet.
2642 bool IsShowing() const { return mIsShowing; }
2644 * Return whether the document is currently visible (in the sense of
2645 * OnPageHide having been called and OnPageShow not yet having been called)
2647 bool IsVisible() const { return mVisible; }
2649 void SetSuppressedEventListener(EventListener* aListener);
2651 EventListener* GetSuppressedEventListener() {
2652 return mSuppressedEventListener;
2656 * Return true when this document is active, i.e., an active document
2657 * in a content viewer. Note that this will return true for bfcached
2658 * documents, so this does NOT match the "active document" concept in
2659 * the WHATWG spec - see IsCurrentActiveDocument.
2661 bool IsActive() const { return mDocumentContainer && !mRemovedFromDocShell; }
2664 * Return true if this is the current active document for its
2665 * docshell. Note that a docshell may have multiple active documents
2666 * due to the bfcache -- this should be used when you need to
2667 * differentiate the *current* active document from any active
2668 * documents.
2670 bool IsCurrentActiveDocument() const {
2671 nsPIDOMWindowInner* inner = GetInnerWindow();
2672 return inner && inner->IsCurrentInnerWindow() && inner->GetDoc() == this;
2676 * Returns whether this document should perform image loads.
2678 bool ShouldLoadImages() const {
2679 // We check IsBeingUsedAsImage() so that SVG documents loaded as
2680 // images can themselves have data: URL image references.
2681 return IsCurrentActiveDocument() || IsBeingUsedAsImage() ||
2682 IsStaticDocument();
2685 void SetHasPrintCallbacks() {
2686 MOZ_DIAGNOSTIC_ASSERT(IsStaticDocument());
2687 mHasPrintCallbacks = true;
2690 bool HasPrintCallbacks() const { return mHasPrintCallbacks; }
2693 * Register/Unregister the ActivityObserver into mActivityObservers to listen
2694 * the document's activity changes such as OnPageHide, visibility, activity.
2695 * The ActivityObserver objects can be nsIObjectLoadingContent or
2696 * nsIDocumentActivity or HTMLMEdiaElement.
2698 void RegisterActivityObserver(nsISupports* aSupports);
2699 bool UnregisterActivityObserver(nsISupports* aSupports);
2700 // Enumerate all the observers in mActivityObservers by the aEnumerator.
2701 using ActivityObserverEnumerator = FunctionRef<void(nsISupports*)>;
2702 void EnumerateActivityObservers(ActivityObserverEnumerator aEnumerator);
2704 // Indicates whether mAnimationController has been (lazily) initialized.
2705 // If this returns true, we're promising that GetAnimationController()
2706 // will have a non-null return value.
2707 bool HasAnimationController() { return !!mAnimationController; }
2709 // Getter for this document's SMIL Animation Controller. Performs lazy
2710 // initialization, if this document supports animation and if
2711 // mAnimationController isn't yet initialized.
2713 // If HasAnimationController is true, this is guaranteed to return non-null.
2714 SMILAnimationController* GetAnimationController();
2716 // Gets the tracker for animations that are waiting to start.
2717 // Returns nullptr if there is no pending animation tracker for this document
2718 // which will be the case if there have never been any CSS animations or
2719 // transitions on elements in the document.
2720 PendingAnimationTracker* GetPendingAnimationTracker() {
2721 return mPendingAnimationTracker;
2724 // Gets the tracker for animations that are waiting to start and
2725 // creates it if it doesn't already exist. As a result, the return value
2726 // will never be nullptr.
2727 PendingAnimationTracker* GetOrCreatePendingAnimationTracker();
2730 * Prevents user initiated events from being dispatched to the document and
2731 * subdocuments.
2733 void SuppressEventHandling(uint32_t aIncrease = 1);
2736 * Unsuppress event handling.
2737 * @param aFireEvents If true, delayed events (focus/blur) will be fired
2738 * asynchronously.
2740 void UnsuppressEventHandlingAndFireEvents(bool aFireEvents);
2742 uint32_t EventHandlingSuppressed() const { return mEventsSuppressed; }
2744 bool IsEventHandlingEnabled() const {
2745 return !EventHandlingSuppressed() && mScriptGlobalObject;
2748 bool WouldScheduleFrameRequestCallbacks() const {
2749 // If this function changes to depend on some other variable, make sure to
2750 // call UpdateFrameRequestCallbackSchedulingState() calls to the places
2751 // where that variable can change.
2752 return mPresShell && IsEventHandlingEnabled();
2755 void DecreaseEventSuppression() {
2756 MOZ_ASSERT(mEventsSuppressed);
2757 --mEventsSuppressed;
2758 UpdateFrameRequestCallbackSchedulingState();
2762 * Some clipboard commands are unconditionally enabled on some documents, so
2763 * as to always dispatch copy / paste events even though you'd normally not be
2764 * able to copy.
2766 bool AreClipboardCommandsUnconditionallyEnabled() const;
2769 * Note a ChannelEventQueue which has been suspended on the document's behalf
2770 * to prevent XHRs from running content scripts while event handling is
2771 * suppressed. The document is responsible for resuming the queue after
2772 * event handling is unsuppressed.
2774 void AddSuspendedChannelEventQueue(net::ChannelEventQueue* aQueue);
2777 * Returns true if a postMessage event should be suspended instead of running.
2778 * The document is responsible for running the event later, in the order they
2779 * were received.
2781 bool SuspendPostMessageEvent(PostMessageEvent* aEvent);
2784 * Run any suspended postMessage events, or clear them.
2786 void FireOrClearPostMessageEvents(bool aFireEvents);
2788 void SetHasDelayedRefreshEvent() { mHasDelayedRefreshEvent = true; }
2791 * Flag whether we're about to fire the window's load event for this document.
2793 void SetLoadEventFiring(bool aFiring) { mLoadEventFiring = aFiring; }
2796 * Test whether we should be firing a load event for this document after a
2797 * document.close(). This is public and on Document, instead of being private
2798 * to Document, because we need to go through the normal docloader logic
2799 * for the readystate change to READYSTATE_COMPLETE with the normal timing and
2800 * semantics of firing the load event; we just don't want to fire the load
2801 * event if this tests true. So we need the docloader to be able to access
2802 * this state.
2804 * This method should only be called at the point when the load event is about
2805 * to be fired. It resets the "skip" flag, so it is not idempotent.
2807 bool SkipLoadEventAfterClose() {
2808 bool skip = mSkipLoadEventAfterClose;
2809 mSkipLoadEventAfterClose = false;
2810 return skip;
2814 * Increment https://html.spec.whatwg.org/#ignore-destructive-writes-counter
2816 void IncrementIgnoreDestructiveWritesCounter() {
2817 ++mIgnoreDestructiveWritesCounter;
2821 * Decrement https://html.spec.whatwg.org/#ignore-destructive-writes-counter
2823 void DecrementIgnoreDestructiveWritesCounter() {
2824 --mIgnoreDestructiveWritesCounter;
2827 bool IsDNSPrefetchAllowed() const { return mAllowDNSPrefetch; }
2830 * Returns true if this document is allowed to contain XUL element and
2831 * use non-builtin XBL bindings.
2833 bool AllowXULXBL() {
2834 return mAllowXULXBL == eTriTrue ? true
2835 : mAllowXULXBL == eTriFalse ? false
2836 : InternalAllowXULXBL();
2840 * Returns true if this document is allowed to load DTDs from UI resources
2841 * no matter what.
2843 bool SkipDTDSecurityChecks() { return mSkipDTDSecurityChecks; }
2845 void ForceEnableXULXBL() { mAllowXULXBL = eTriTrue; }
2847 void ForceSkipDTDSecurityChecks() { mSkipDTDSecurityChecks = true; }
2850 * Returns the template content owner document that owns the content of
2851 * HTMLTemplateElement.
2853 Document* GetTemplateContentsOwner();
2856 * Returns true if this document is a static clone of a normal document.
2858 * We create static clones for print preview and printing (possibly other
2859 * things in future).
2861 * Note that static documents are also "loaded as data" (if this method
2862 * returns true, IsLoadedAsData() will also return true).
2864 bool IsStaticDocument() const { return mIsStaticDocument; }
2867 * Clones the document along with any subdocuments, stylesheet, etc.
2869 * The resulting document and everything it contains (including any
2870 * sub-documents) are created purely via cloning. The returned documents and
2871 * any sub-documents are "loaded as data" documents to preserve the state as
2872 * it was during the clone process (we don't want external resources to load
2873 * and replace the cloned resources).
2875 * @param aCloneContainer The container for the clone document.
2876 * @param aContentViewer The viewer for the clone document. Must be the viewer
2877 * of aCloneContainer, but callers must have a reference
2878 * to it already and ensure it's not null.
2879 * @param aPrintSettings The print settings for this clone.
2880 * @param aOutHasInProcessPrintCallbacks Self-descriptive.
2882 already_AddRefed<Document> CreateStaticClone(
2883 nsIDocShell* aCloneContainer, nsIContentViewer* aContentViewer,
2884 nsIPrintSettings* aPrintSettings, bool* aOutHasInProcessPrintCallbacks);
2887 * If this document is a static clone, this returns the original
2888 * document.
2890 Document* GetOriginalDocument() const {
2891 MOZ_ASSERT(!mOriginalDocument || !mOriginalDocument->GetOriginalDocument());
2892 return mOriginalDocument;
2896 * If this document is a static clone, let the original document know that
2897 * we're going away and then release our reference to it.
2899 void UnlinkOriginalDocumentIfStatic();
2902 * These are called by the parser as it encounters <picture> tags, the end of
2903 * said tags, and possible picture <source srcset> sources respectively. These
2904 * are used to inform ResolvePreLoadImage() calls. Unset attributes are
2905 * expected to be marked void.
2907 * NOTE that the parser does not attempt to track the current picture nesting
2908 * level or whether the given <source> tag is within a picture -- it is only
2909 * guaranteed to order these calls properly with respect to
2910 * ResolvePreLoadImage.
2913 void PreloadPictureOpened() { mPreloadPictureDepth++; }
2915 void PreloadPictureClosed();
2917 void PreloadPictureImageSource(const nsAString& aSrcsetAttr,
2918 const nsAString& aSizesAttr,
2919 const nsAString& aTypeAttr,
2920 const nsAString& aMediaAttr);
2923 * Called by the parser to resolve an image for preloading. The parser will
2924 * call the PreloadPicture* functions to inform us of possible <picture>
2925 * nesting and possible sources, which are used to inform URL selection
2926 * responsive <picture> or <img srcset> images. Unset attributes are expected
2927 * to be marked void.
2928 * If this image is for <picture> or <img srcset>, aIsImgSet will be set to
2929 * true, false otherwise.
2931 already_AddRefed<nsIURI> ResolvePreloadImage(nsIURI* aBaseURI,
2932 const nsAString& aSrcAttr,
2933 const nsAString& aSrcsetAttr,
2934 const nsAString& aSizesAttr,
2935 bool* aIsImgSet);
2937 * Called by nsParser to preload images. Can be removed and code moved
2938 * to nsPreloadURIs::PreloadURIs() in file nsParser.cpp whenever the
2939 * parser-module is linked with gklayout-module. aCrossOriginAttr should
2940 * be a void string if the attr is not present.
2941 * aIsImgSet is the value got from calling ResolvePreloadImage, it is true
2942 * when this image is for loading <picture> or <img srcset> images.
2944 void MaybePreLoadImage(nsIURI* uri, const nsAString& aCrossOriginAttr,
2945 ReferrerPolicyEnum aReferrerPolicy, bool aIsImgSet,
2946 bool aLinkPreload, const TimeStamp& aInitTimestamp);
2947 void PreLoadImage(nsIURI* uri, const nsAString& aCrossOriginAttr,
2948 ReferrerPolicyEnum aReferrerPolicy, bool aIsImgSet,
2949 bool aLinkPreload);
2952 * Called by images to forget an image preload when they start doing
2953 * the real load.
2955 void ForgetImagePreload(nsIURI* aURI);
2958 * Called by the parser or the preload service to preload style sheets.
2959 * aCrossOriginAttr should be a void string if the attr is not present.
2961 SheetPreloadStatus PreloadStyle(nsIURI* aURI, const Encoding* aEncoding,
2962 const nsAString& aCrossOriginAttr,
2963 ReferrerPolicyEnum aReferrerPolicy,
2964 const nsAString& aIntegrity,
2965 css::StylePreloadKind);
2968 * Called by the chrome registry to load style sheets.
2970 * This always does a synchronous load, and parses as a normal document sheet.
2972 RefPtr<StyleSheet> LoadChromeSheetSync(nsIURI* aURI);
2975 * Returns true if the locale used for the document specifies a direction of
2976 * right to left. For chrome documents, this comes from the chrome registry.
2977 * This is used to determine the current state for the :-moz-locale-dir
2978 * pseudoclass so once can know whether a document is expected to be rendered
2979 * left-to-right or right-to-left.
2981 bool IsDocumentRightToLeft();
2984 * Called by Parser for link rel=preconnect
2986 void MaybePreconnect(nsIURI* uri, CORSMode aCORSMode);
2988 enum DocumentTheme {
2989 Doc_Theme_Uninitialized, // not determined yet
2990 Doc_Theme_None,
2991 Doc_Theme_Neutral,
2992 Doc_Theme_Dark,
2993 Doc_Theme_Bright
2997 * Set the document's pending state object (as serialized using structured
2998 * clone).
3000 void SetStateObject(nsIStructuredCloneContainer* scContainer);
3003 * Set the document's pending state object to the same state object as
3004 * aDocument.
3006 void SetStateObjectFrom(Document* aDocument) {
3007 SetStateObject(aDocument->mStateObjectContainer);
3011 * Returns Doc_Theme_None if there is no lightweight theme specified,
3012 * Doc_Theme_Dark for a dark theme, Doc_Theme_Bright for a light theme, and
3013 * Doc_Theme_Neutral for any other theme. This is used to determine the state
3014 * of the pseudoclasses :-moz-lwtheme and :-moz-lwtheme-text.
3016 DocumentTheme GetDocumentLWTheme();
3017 DocumentTheme ThreadSafeGetDocumentLWTheme() const;
3018 void ResetDocumentLWTheme() { mDocLWTheme = Doc_Theme_Uninitialized; }
3020 // Whether we're a media document or not.
3021 enum class MediaDocumentKind {
3022 NotMedia,
3023 Video,
3024 Image,
3025 Plugin,
3028 virtual enum MediaDocumentKind MediaDocumentKind() const {
3029 return MediaDocumentKind::NotMedia;
3033 * Returns the document state.
3034 * Document state bits have the form NS_DOCUMENT_STATE_* and are declared in
3035 * Document.h.
3037 EventStates GetDocumentState() const { return mDocumentState; }
3039 nsISupports* GetCurrentContentSink();
3041 void SetAutoFocusElement(Element* aAutoFocusElement);
3042 void TriggerAutoFocus();
3043 void SetAutoFocusFired();
3044 bool IsAutoFocusFired();
3046 void SetScrollToRef(nsIURI* aDocumentURI);
3047 MOZ_CAN_RUN_SCRIPT void ScrollToRef();
3048 void ResetScrolledToRefAlready() { mScrolledToRefAlready = false; }
3050 void SetChangeScrollPosWhenScrollingToRef(bool aValue) {
3051 mChangeScrollPosWhenScrollingToRef = aValue;
3054 using DocumentOrShadowRoot::GetElementById;
3055 using DocumentOrShadowRoot::GetElementsByClassName;
3056 using DocumentOrShadowRoot::GetElementsByTagName;
3057 using DocumentOrShadowRoot::GetElementsByTagNameNS;
3059 DocumentTimeline* Timeline();
3060 LinkedList<DocumentTimeline>& Timelines() { return mTimelines; }
3062 SVGSVGElement* GetSVGRootElement() const;
3064 struct FrameRequest {
3065 FrameRequest(FrameRequestCallback& aCallback, int32_t aHandle);
3066 ~FrameRequest();
3068 // Comparator operators to allow RemoveElementSorted with an
3069 // integer argument on arrays of FrameRequest
3070 bool operator==(int32_t aHandle) const { return mHandle == aHandle; }
3071 bool operator<(int32_t aHandle) const { return mHandle < aHandle; }
3073 RefPtr<FrameRequestCallback> mCallback;
3074 int32_t mHandle;
3077 nsresult ScheduleFrameRequestCallback(FrameRequestCallback& aCallback,
3078 int32_t* aHandle);
3079 void CancelFrameRequestCallback(int32_t aHandle);
3082 * Returns true if the handle refers to a callback that was canceled that
3083 * we did not find in our list of callbacks (e.g. because it is one of those
3084 * in the set of callbacks currently queued to be run).
3086 bool IsCanceledFrameRequestCallback(int32_t aHandle) const;
3089 * Put this document's frame request callbacks into the provided
3090 * list, and forget about them.
3092 void TakeFrameRequestCallbacks(nsTArray<FrameRequest>& aCallbacks);
3095 * @return true if this document's frame request callbacks should be
3096 * throttled. We throttle requestAnimationFrame for documents which aren't
3097 * visible (e.g. scrolled out of the viewport).
3099 bool ShouldThrottleFrameRequests() const;
3101 // This returns true when the document tree is being teared down.
3102 bool InUnlinkOrDeletion() { return mInUnlinkOrDeletion; }
3104 dom::ImageTracker* ImageTracker();
3106 // Adds an element to mResponsiveContent when the element is
3107 // added to the tree.
3108 void AddResponsiveContent(HTMLImageElement* aContent) {
3109 MOZ_ASSERT(aContent);
3110 mResponsiveContent.Insert(aContent);
3113 // Removes an element from mResponsiveContent when the element is
3114 // removed from the tree.
3115 void RemoveResponsiveContent(HTMLImageElement* aContent) {
3116 MOZ_ASSERT(aContent);
3117 mResponsiveContent.Remove(aContent);
3120 void ScheduleSVGUseElementShadowTreeUpdate(SVGUseElement&);
3121 void UnscheduleSVGUseElementShadowTreeUpdate(SVGUseElement& aElement) {
3122 mSVGUseElementsNeedingShadowTreeUpdate.Remove(&aElement);
3125 bool SVGUseElementNeedsShadowTreeUpdate(SVGUseElement& aElement) const {
3126 return mSVGUseElementsNeedingShadowTreeUpdate.Contains(&aElement);
3129 using ShadowRootSet = nsTHashSet<ShadowRoot*>;
3131 void AddComposedDocShadowRoot(ShadowRoot& aShadowRoot) {
3132 mComposedShadowRoots.Insert(&aShadowRoot);
3135 void RemoveComposedDocShadowRoot(ShadowRoot& aShadowRoot) {
3136 mComposedShadowRoots.Remove(&aShadowRoot);
3139 // If you're considering using this, you probably want to use
3140 // ShadowRoot::IsComposedDocParticipant instead. This is just for
3141 // sanity-checking.
3142 bool IsComposedDocShadowRoot(ShadowRoot& aShadowRoot) {
3143 return mComposedShadowRoots.Contains(&aShadowRoot);
3146 const ShadowRootSet& ComposedShadowRoots() const {
3147 return mComposedShadowRoots;
3150 // WebIDL method for chrome code.
3151 void GetConnectedShadowRoots(nsTArray<RefPtr<ShadowRoot>>&) const;
3153 // Notifies any responsive content added by AddResponsiveContent upon media
3154 // features values changing.
3155 void NotifyMediaFeatureValuesChanged();
3157 nsresult GetStateObject(nsIVariant** aResult);
3159 nsDOMNavigationTiming* GetNavigationTiming() const { return mTiming; }
3161 void SetNavigationTiming(nsDOMNavigationTiming* aTiming);
3163 nsContentList* ImageMapList();
3165 // Add aLink to the set of links that need their status resolved.
3166 void RegisterPendingLinkUpdate(Link* aLink);
3168 // Update state on links in mLinksToUpdate.
3169 void FlushPendingLinkUpdates();
3171 bool HasWarnedAbout(DeprecatedOperations aOperation) const;
3172 void WarnOnceAbout(
3173 DeprecatedOperations aOperation, bool asError = false,
3174 const nsTArray<nsString>& aParams = nsTArray<nsString>()) const;
3176 #define DOCUMENT_WARNING(_op) e##_op,
3177 enum DocumentWarnings {
3178 #include "nsDocumentWarningList.h"
3179 eDocumentWarningCount
3181 #undef DOCUMENT_WARNING
3182 bool HasWarnedAbout(DocumentWarnings aWarning) const;
3183 void WarnOnceAbout(
3184 DocumentWarnings aWarning, bool asError = false,
3185 const nsTArray<nsString>& aParams = nsTArray<nsString>()) const;
3187 // This method may fire a DOM event; if it does so it will happen
3188 // synchronously.
3190 // Whether the event fires is controlled by the argument.
3191 enum class DispatchVisibilityChange { No, Yes };
3192 void UpdateVisibilityState(
3193 DispatchVisibilityChange = DispatchVisibilityChange::Yes);
3195 // Posts an event to call UpdateVisibilityState.
3196 void PostVisibilityUpdateEvent();
3198 bool IsSyntheticDocument() const { return mIsSyntheticDocument; }
3200 // Adds the size of a given node, which must not be a document node, to the
3201 // window sizes passed-in.
3202 static void AddSizeOfNodeTree(nsINode&, nsWindowSizes&);
3204 // Note: Document is a sub-class of nsINode, which has a
3205 // SizeOfExcludingThis function. However, because Document objects can
3206 // only appear at the top of the DOM tree, we have a specialized measurement
3207 // function which returns multiple sizes.
3208 virtual void DocAddSizeOfExcludingThis(nsWindowSizes& aWindowSizes) const;
3209 // DocAddSizeOfIncludingThis doesn't need to be overridden by sub-classes
3210 // because Document inherits from nsINode; see the comment above the
3211 // declaration of nsINode::SizeOfIncludingThis.
3212 virtual void DocAddSizeOfIncludingThis(nsWindowSizes& aWindowSizes) const;
3214 void ConstructUbiNode(void* storage) override;
3216 bool MayHaveDOMMutationObservers() { return mMayHaveDOMMutationObservers; }
3218 void SetMayHaveDOMMutationObservers() { mMayHaveDOMMutationObservers = true; }
3220 bool MayHaveAnimationObservers() { return mMayHaveAnimationObservers; }
3222 void SetMayHaveAnimationObservers() { mMayHaveAnimationObservers = true; }
3224 bool IsInSyncOperation() { return mInSyncOperationCount != 0; }
3226 void SetIsInSyncOperation(bool aSync);
3228 bool CreatingStaticClone() const { return mCreatingStaticClone; }
3231 * Creates a new element in the HTML namespace with a local name given by
3232 * aTag.
3234 already_AddRefed<Element> CreateHTMLElement(nsAtom* aTag);
3236 // WebIDL API
3237 nsIGlobalObject* GetParentObject() const { return GetScopeObject(); }
3238 static already_AddRefed<Document> Constructor(const GlobalObject& aGlobal,
3239 ErrorResult& rv);
3240 DOMImplementation* GetImplementation(ErrorResult& rv);
3241 [[nodiscard]] nsresult GetURL(nsString& retval) const;
3242 [[nodiscard]] nsresult GetDocumentURI(nsString& retval) const;
3243 // Return the URI for the document.
3244 // The returned value may differ if the document is loaded via XHR, and
3245 // when accessed from chrome privileged script and
3246 // from content privileged script for compatibility.
3247 void GetDocumentURIFromJS(nsString& aDocumentURI, CallerType aCallerType,
3248 ErrorResult& aRv) const;
3249 void GetCompatMode(nsString& retval) const;
3250 void GetCharacterSet(nsAString& retval) const;
3251 // Skip GetContentType, because our NS_IMETHOD version above works fine here.
3252 // GetDoctype defined above
3253 Element* GetDocumentElement() const { return GetRootElement(); }
3255 WindowContext* GetTopLevelWindowContext() const;
3257 // If the top-level ancestor content document for this document is in the same
3258 // process, returns it. Otherwise, returns null. This function is not
3259 // Fission-compatible, and should not be used in new code.
3260 Document* GetTopLevelContentDocumentIfSameProcess();
3261 const Document* GetTopLevelContentDocumentIfSameProcess() const;
3263 // Returns the associated app window if this is a top-level chrome document,
3264 // null otherwise.
3265 already_AddRefed<nsIAppWindow> GetAppWindowIfToplevelChrome() const;
3267 already_AddRefed<Element> CreateElement(
3268 const nsAString& aTagName, const ElementCreationOptionsOrString& aOptions,
3269 ErrorResult& rv);
3270 already_AddRefed<Element> CreateElementNS(
3271 const nsAString& aNamespaceURI, const nsAString& aQualifiedName,
3272 const ElementCreationOptionsOrString& aOptions, ErrorResult& rv);
3273 already_AddRefed<Element> CreateXULElement(
3274 const nsAString& aTagName, const ElementCreationOptionsOrString& aOptions,
3275 ErrorResult& aRv);
3276 already_AddRefed<DocumentFragment> CreateDocumentFragment() const;
3277 already_AddRefed<nsTextNode> CreateTextNode(const nsAString& aData) const;
3278 already_AddRefed<nsTextNode> CreateEmptyTextNode() const;
3279 already_AddRefed<Comment> CreateComment(const nsAString& aData) const;
3280 already_AddRefed<ProcessingInstruction> CreateProcessingInstruction(
3281 const nsAString& target, const nsAString& data, ErrorResult& rv) const;
3282 already_AddRefed<nsINode> ImportNode(nsINode& aNode, bool aDeep,
3283 ErrorResult& rv) const;
3284 nsINode* AdoptNode(nsINode& aNode, ErrorResult& rv);
3285 already_AddRefed<Event> CreateEvent(const nsAString& aEventType,
3286 CallerType aCallerType,
3287 ErrorResult& rv) const;
3288 already_AddRefed<nsRange> CreateRange(ErrorResult& rv);
3289 already_AddRefed<NodeIterator> CreateNodeIterator(nsINode& aRoot,
3290 uint32_t aWhatToShow,
3291 NodeFilter* aFilter,
3292 ErrorResult& rv) const;
3293 already_AddRefed<TreeWalker> CreateTreeWalker(nsINode& aRoot,
3294 uint32_t aWhatToShow,
3295 NodeFilter* aFilter,
3296 ErrorResult& rv) const;
3297 // Deprecated WebIDL bits
3298 already_AddRefed<CDATASection> CreateCDATASection(const nsAString& aData,
3299 ErrorResult& rv);
3300 already_AddRefed<Attr> CreateAttribute(const nsAString& aName,
3301 ErrorResult& rv);
3302 already_AddRefed<Attr> CreateAttributeNS(const nsAString& aNamespaceURI,
3303 const nsAString& aQualifiedName,
3304 ErrorResult& rv);
3305 void GetInputEncoding(nsAString& aInputEncoding) const;
3306 already_AddRefed<Location> GetLocation() const;
3307 void GetDomain(nsAString& aDomain);
3308 void SetDomain(const nsAString& aDomain, mozilla::ErrorResult& rv);
3309 void GetCookie(nsAString& aCookie, mozilla::ErrorResult& rv);
3310 void SetCookie(const nsAString& aCookie, mozilla::ErrorResult& rv);
3311 void GetReferrer(nsAString& aReferrer) const;
3312 void GetLastModified(nsAString& aLastModified) const;
3313 void GetReadyState(nsAString& aReadyState) const;
3315 void GetTitle(nsAString& aTitle);
3316 void SetTitle(const nsAString& aTitle, ErrorResult& rv);
3317 void GetDir(nsAString& aDirection) const;
3318 void SetDir(const nsAString& aDirection);
3319 nsIHTMLCollection* Images();
3320 nsIHTMLCollection* Embeds();
3321 nsIHTMLCollection* Plugins() { return Embeds(); }
3322 nsIHTMLCollection* Links();
3323 nsIHTMLCollection* Forms();
3324 nsIHTMLCollection* Scripts();
3325 already_AddRefed<nsContentList> GetElementsByName(const nsAString& aName) {
3326 return GetFuncStringContentList<nsCachableElementsByNameNodeList>(
3327 this, MatchNameAttribute, nullptr, UseExistingNameString, aName);
3329 Document* Open(const mozilla::dom::Optional<nsAString>& /* unused */,
3330 const mozilla::dom::Optional<nsAString>& /* unused */,
3331 mozilla::ErrorResult& aError);
3332 mozilla::dom::Nullable<mozilla::dom::WindowProxyHolder> Open(
3333 const nsAString& aURL, const nsAString& aName, const nsAString& aFeatures,
3334 mozilla::ErrorResult& rv);
3335 void Close(mozilla::ErrorResult& rv);
3336 void Write(const mozilla::dom::Sequence<nsString>& aText,
3337 mozilla::ErrorResult& rv);
3338 void Writeln(const mozilla::dom::Sequence<nsString>& aText,
3339 mozilla::ErrorResult& rv);
3340 Nullable<WindowProxyHolder> GetDefaultView() const;
3341 Element* GetActiveElement();
3342 nsIContent* GetUnretargetedFocusedContent() const;
3343 bool HasFocus(ErrorResult& rv) const;
3344 void GetDesignMode(nsAString& aDesignMode);
3345 void SetDesignMode(const nsAString& aDesignMode,
3346 nsIPrincipal& aSubjectPrincipal, mozilla::ErrorResult& rv);
3347 void SetDesignMode(const nsAString& aDesignMode,
3348 const mozilla::Maybe<nsIPrincipal*>& aSubjectPrincipal,
3349 mozilla::ErrorResult& rv);
3350 MOZ_CAN_RUN_SCRIPT
3351 bool ExecCommand(const nsAString& aHTMLCommandName, bool aShowUI,
3352 const nsAString& aValue, nsIPrincipal& aSubjectPrincipal,
3353 mozilla::ErrorResult& aRv);
3354 MOZ_CAN_RUN_SCRIPT bool QueryCommandEnabled(const nsAString& aHTMLCommandName,
3355 nsIPrincipal& aSubjectPrincipal,
3356 mozilla::ErrorResult& aRv);
3357 MOZ_CAN_RUN_SCRIPT bool QueryCommandIndeterm(
3358 const nsAString& aHTMLCommandName, mozilla::ErrorResult& aRv);
3359 MOZ_CAN_RUN_SCRIPT bool QueryCommandState(const nsAString& aHTMLCommandName,
3360 mozilla::ErrorResult& aRv);
3361 MOZ_CAN_RUN_SCRIPT bool QueryCommandSupported(
3362 const nsAString& aHTMLCommandName, mozilla::dom::CallerType aCallerType,
3363 mozilla::ErrorResult& aRv);
3364 MOZ_CAN_RUN_SCRIPT void QueryCommandValue(const nsAString& aHTMLCommandName,
3365 nsAString& aValue,
3366 mozilla::ErrorResult& aRv);
3367 nsIHTMLCollection* Applets();
3368 nsIHTMLCollection* Anchors();
3369 TimeStamp LastFocusTime() const;
3370 void SetLastFocusTime(const TimeStamp& aFocusTime);
3371 // Event handlers are all on nsINode already
3372 bool MozSyntheticDocument() const { return IsSyntheticDocument(); }
3373 Element* GetCurrentScript();
3374 void ReleaseCapture() const;
3375 void MozSetImageElement(const nsAString& aImageElementId, Element* aElement);
3376 nsIURI* GetDocumentURIObject() const;
3377 // Not const because all the fullscreen goop is not const
3378 const char* GetFullscreenError(CallerType);
3379 bool FullscreenEnabled(CallerType aCallerType) {
3380 return !GetFullscreenError(aCallerType);
3383 Element* GetTopLayerTop();
3384 // Return the fullscreen element in the top layer
3385 Element* GetUnretargetedFullScreenElement() const;
3386 bool Fullscreen() const { return !!GetUnretargetedFullScreenElement(); }
3387 already_AddRefed<Promise> ExitFullscreen(ErrorResult&);
3388 void ExitPointerLock() { PointerLockManager::Unlock(this); }
3389 void GetFgColor(nsAString& aFgColor);
3390 void SetFgColor(const nsAString& aFgColor);
3391 void GetLinkColor(nsAString& aLinkColor);
3392 void SetLinkColor(const nsAString& aLinkColor);
3393 void GetVlinkColor(nsAString& aAvlinkColor);
3394 void SetVlinkColor(const nsAString& aVlinkColor);
3395 void GetAlinkColor(nsAString& aAlinkColor);
3396 void SetAlinkColor(const nsAString& aAlinkColor);
3397 void GetBgColor(nsAString& aBgColor);
3398 void SetBgColor(const nsAString& aBgColor);
3399 void Clear() const {
3400 // Deprecated
3402 void CaptureEvents();
3403 void ReleaseEvents();
3405 mozilla::dom::HTMLAllCollection* All();
3407 static bool DocumentSupportsL10n(JSContext* aCx, JSObject* aObject);
3408 static bool IsWebAnimationsEnabled(JSContext* aCx, JSObject* aObject);
3409 static bool IsWebAnimationsEnabled(CallerType aCallerType);
3410 static bool IsWebAnimationsGetAnimationsEnabled(JSContext* aCx,
3411 JSObject* aObject);
3412 static bool AreWebAnimationsImplicitKeyframesEnabled(JSContext* aCx,
3413 JSObject* aObject);
3414 static bool AreWebAnimationsTimelinesEnabled(JSContext* aCx,
3415 JSObject* aObject);
3416 // Checks that the caller is either chrome or some addon.
3417 static bool IsCallerChromeOrAddon(JSContext* aCx, JSObject* aObject);
3419 bool Hidden() const { return mVisibilityState != VisibilityState::Visible; }
3420 dom::VisibilityState VisibilityState() const { return mVisibilityState; }
3422 private:
3423 int32_t mPictureInPictureChildElementCount = 0;
3425 public:
3426 void EnableChildElementInPictureInPictureMode();
3427 void DisableChildElementInPictureInPictureMode();
3429 // True if any child element is being used in picture in picture mode.
3430 bool HasPictureInPictureChildElement() const;
3432 void GetSelectedStyleSheetSet(nsAString& aSheetSet);
3433 void SetSelectedStyleSheetSet(const nsAString& aSheetSet);
3434 void GetLastStyleSheetSet(nsAString& aSheetSet) {
3435 aSheetSet = mLastStyleSheetSet;
3437 const nsString& GetCurrentStyleSheetSet() const {
3438 return mLastStyleSheetSet.IsEmpty() ? mPreferredStyleSheetSet
3439 : mLastStyleSheetSet;
3441 void SetPreferredStyleSheetSet(const nsAString&);
3442 void GetPreferredStyleSheetSet(nsAString& aSheetSet) {
3443 aSheetSet = mPreferredStyleSheetSet;
3445 DOMStringList* StyleSheetSets();
3446 void EnableStyleSheetsForSet(const nsAString& aSheetSet);
3449 * Retrieve the location of the caret position (DOM node and character
3450 * offset within that node), given a point.
3452 * @param aX Horizontal point at which to determine the caret position, in
3453 * page coordinates.
3454 * @param aY Vertical point at which to determine the caret position, in
3455 * page coordinates.
3457 already_AddRefed<nsDOMCaretPosition> CaretPositionFromPoint(float aX,
3458 float aY);
3460 Element* GetScrollingElement();
3461 // A way to check whether a given element is what would get returned from
3462 // GetScrollingElement. It can be faster than comparing to the return value
3463 // of GetScrollingElement() due to being able to avoid flushes in various
3464 // cases. This method assumes that null is NOT passed.
3465 bool IsScrollingElement(Element* aElement);
3467 // QuerySelector and QuerySelectorAll already defined on nsINode
3469 XPathExpression* CreateExpression(const nsAString& aExpression,
3470 XPathNSResolver* aResolver,
3471 ErrorResult& rv);
3472 nsINode* CreateNSResolver(nsINode& aNodeResolver);
3473 already_AddRefed<XPathResult> Evaluate(
3474 JSContext* aCx, const nsAString& aExpression, nsINode& aContextNode,
3475 XPathNSResolver* aResolver, uint16_t aType, JS::Handle<JSObject*> aResult,
3476 ErrorResult& rv);
3477 // Touch event handlers already on nsINode
3478 already_AddRefed<Touch> CreateTouch(nsGlobalWindowInner* aView,
3479 EventTarget* aTarget, int32_t aIdentifier,
3480 int32_t aPageX, int32_t aPageY,
3481 int32_t aScreenX, int32_t aScreenY,
3482 int32_t aClientX, int32_t aClientY,
3483 int32_t aRadiusX, int32_t aRadiusY,
3484 float aRotationAngle, float aForce);
3485 already_AddRefed<TouchList> CreateTouchList();
3486 already_AddRefed<TouchList> CreateTouchList(
3487 Touch& aTouch, const Sequence<OwningNonNull<Touch>>& aTouches);
3488 already_AddRefed<TouchList> CreateTouchList(
3489 const Sequence<OwningNonNull<Touch>>& aTouches);
3491 void SetStyleSheetChangeEventsEnabled(bool aValue) {
3492 mStyleSheetChangeEventsEnabled = aValue;
3495 bool StyleSheetChangeEventsEnabled() const {
3496 return mStyleSheetChangeEventsEnabled;
3499 void SetShadowRootAttachedEventEnabled(bool aValue) {
3500 mShadowRootAttachedEventEnabled = aValue;
3502 bool ShadowRootAttachedEventEnabled() const {
3503 return mShadowRootAttachedEventEnabled;
3506 already_AddRefed<Promise> BlockParsing(Promise& aPromise,
3507 const BlockParsingOptions& aOptions,
3508 ErrorResult& aRv);
3510 already_AddRefed<nsIURI> GetMozDocumentURIIfNotForErrorPages();
3512 Promise* GetDocumentReadyForIdle(ErrorResult& aRv);
3514 void BlockUnblockOnloadForPDFJS(bool aBlock) {
3515 if (aBlock) {
3516 BlockOnload();
3517 } else {
3518 UnblockOnload(/* aFireSync = */ false);
3522 nsIDOMXULCommandDispatcher* GetCommandDispatcher();
3523 bool HasXULBroadcastManager() const { return mXULBroadcastManager; };
3524 void InitializeXULBroadcastManager();
3525 XULBroadcastManager* GetXULBroadcastManager() const {
3526 return mXULBroadcastManager;
3528 nsINode* GetPopupRangeParent(ErrorResult& aRv);
3529 int32_t GetPopupRangeOffset(ErrorResult& aRv);
3531 bool DevToolsWatchingDOMMutations() const {
3532 return mDevToolsWatchingDOMMutations;
3534 void SetDevToolsWatchingDOMMutations(bool aValue);
3536 void MaybeWarnAboutZoom();
3538 // ParentNode
3539 nsIHTMLCollection* Children();
3540 uint32_t ChildElementCount();
3543 * Asserts IsHTMLOrXHTML, and can't return null.
3544 * Defined inline in nsHTMLDocument.h
3546 inline nsHTMLDocument* AsHTMLDocument();
3547 inline const nsHTMLDocument* AsHTMLDocument() const;
3550 * Asserts IsSVGDocument, and can't return null.
3551 * Defined inline in SVGDocument.h
3553 inline SVGDocument* AsSVGDocument();
3554 inline const SVGDocument* AsSVGDocument() const;
3557 * Given a node, get a weak reference to it and append that reference to
3558 * mBlockedNodesByClassifier. Can be used later on to look up a node in it.
3559 * (e.g., by the UI)
3561 void AddBlockedNodeByClassifier(nsINode* node) {
3562 if (!node) {
3563 return;
3566 nsWeakPtr weakNode = do_GetWeakReference(node);
3568 if (weakNode) {
3569 mBlockedNodesByClassifier.AppendElement(weakNode);
3573 gfxUserFontSet* GetUserFontSet();
3574 void FlushUserFontSet();
3575 void MarkUserFontSetDirty();
3576 FontFaceSet* GetFonts() { return mFontFaceSet; }
3578 // FontFaceSource
3579 FontFaceSet* Fonts();
3581 bool DidFireDOMContentLoaded() const { return mDidFireDOMContentLoaded; }
3583 bool IsSynthesized();
3585 // Records whether we will track use counters for this document, and if so,
3586 // which top-level document that page counters will be accumulated to.
3588 // Informs the parent process that page use counters will be sent once the
3589 // document goes away.
3590 void InitUseCounters();
3592 // Reports document use counters via telemetry. This method only has an
3593 // effect once per document, and so is called during document destruction.
3594 void ReportDocumentUseCounters();
3596 // Report how lazyload performs for this document.
3597 void ReportDocumentLazyLoadCounters();
3599 // Sends page use counters to the parent process to accumulate against the
3600 // top-level document. Must be called while we still have access to our
3601 // WindowContext. This method has an effect each time it is called, and we
3602 // call it just before the document loses its window.
3603 void SendPageUseCounters();
3605 void SetUseCounter(UseCounter aUseCounter) {
3606 mUseCounters[aUseCounter] = true;
3609 const StyleUseCounters* GetStyleUseCounters() {
3610 return mStyleUseCounters.get();
3613 // Propagate our use counters explicitly into the specified referencing
3614 // document.
3616 // This is used for SVG image documents, which cannot be enumerated in the
3617 // referencing document's ReportUseCounters() like external resource documents
3618 // can.
3619 void PropagateImageUseCounters(Document* aReferencingDocument);
3621 // Called to track whether this document has had any interaction.
3622 // This is used to track whether we should permit "beforeunload".
3623 void SetUserHasInteracted();
3624 bool UserHasInteracted() { return mUserHasInteracted; }
3625 void ResetUserInteractionTimer();
3627 // This method would return current autoplay policy, it would be "allowed"
3628 // , "allowed-muted" or "disallowed".
3629 DocumentAutoplayPolicy AutoplayPolicy() const;
3631 // This should be called when this document receives events which are likely
3632 // to be user interaction with the document, rather than the byproduct of
3633 // interaction with the browser (i.e. a keypress to scroll the view port,
3634 // keyboard shortcuts, etc). This is used to decide whether we should
3635 // permit autoplay audible media. This also gesture activates all other
3636 // content documents in this tab.
3637 void NotifyUserGestureActivation();
3639 // This function is used for mochitest only.
3640 void ClearUserGestureActivation();
3642 // Return true if NotifyUserGestureActivation() has been called on any
3643 // document in the document tree.
3644 bool HasBeenUserGestureActivated();
3646 // Return true if there is transient user gesture activation and it hasn't yet
3647 // timed out.
3648 bool HasValidTransientUserGestureActivation() const;
3650 // Return true.
3651 bool ConsumeTransientUserGestureActivation();
3653 BrowsingContext* GetBrowsingContext() const;
3655 // This document is a WebExtension page, it might be a background page, a
3656 // popup, a visible tab, a visible iframe ...e.t.c.
3657 bool IsExtensionPage() const;
3659 bool HasScriptsBlockedBySandbox();
3661 void ReportHasScrollLinkedEffect();
3662 bool HasScrollLinkedEffect() const { return mHasScrollLinkedEffect; }
3664 #ifdef DEBUG
3665 void AssertDocGroupMatchesKey() const;
3666 #endif
3668 DocGroup* GetDocGroup() const {
3669 #ifdef DEBUG
3670 AssertDocGroupMatchesKey();
3671 #endif
3672 return mDocGroup;
3675 DocGroup* GetDocGroupOrCreate();
3678 * If we're a sub-document, the parent document's layout can affect our style
3679 * and layout (due to the viewport size, viewport units, media queries...).
3681 * This function returns true if our parent document and our child document
3682 * can observe each other. If they cannot, then we don't need to synchronously
3683 * update the parent document layout every time the child document may need
3684 * up-to-date layout information.
3686 bool StyleOrLayoutObservablyDependsOnParentDocumentLayout() const {
3687 return GetInProcessParentDocument() &&
3688 GetDocGroup() == GetInProcessParentDocument()->GetDocGroup();
3691 void AddIntersectionObserver(DOMIntersectionObserver* aObserver) {
3692 MOZ_ASSERT(!mIntersectionObservers.Contains(aObserver),
3693 "Intersection observer already in the list");
3694 mIntersectionObservers.Insert(aObserver);
3697 void RemoveIntersectionObserver(DOMIntersectionObserver* aObserver) {
3698 mIntersectionObservers.Remove(aObserver);
3701 bool HasIntersectionObservers() const {
3702 return !mIntersectionObservers.IsEmpty();
3705 void UpdateIntersectionObservations(TimeStamp aNowTime);
3706 void ScheduleIntersectionObserverNotification();
3707 MOZ_CAN_RUN_SCRIPT void NotifyIntersectionObservers();
3709 DOMIntersectionObserver* GetLazyLoadImageObserver() {
3710 return mLazyLoadImageObserver;
3712 DOMIntersectionObserver* GetLazyLoadImageObserverViewport() {
3713 return mLazyLoadImageObserverViewport;
3715 DOMIntersectionObserver& EnsureLazyLoadImageObserver();
3716 DOMIntersectionObserver& EnsureLazyLoadImageObserverViewport();
3717 void IncLazyLoadImageCount();
3718 void DecLazyLoadImageCount() {
3719 MOZ_DIAGNOSTIC_ASSERT(mLazyLoadImageCount > 0);
3720 --mLazyLoadImageCount;
3722 void IncLazyLoadImageStarted() { ++mLazyLoadImageStarted; }
3723 void IncLazyLoadImageReachViewport(bool aLoading);
3725 // Dispatch a runnable related to the document.
3726 nsresult Dispatch(TaskCategory aCategory,
3727 already_AddRefed<nsIRunnable>&& aRunnable) final;
3729 virtual nsISerialEventTarget* EventTargetFor(
3730 TaskCategory aCategory) const override;
3732 virtual AbstractThread* AbstractMainThreadFor(
3733 TaskCategory aCategory) override;
3735 // The URLs passed to this function should match what
3736 // JS::DescribeScriptedCaller() returns, since this API is used to
3737 // determine whether some code is being called from a tracking script.
3738 void NoteScriptTrackingStatus(const nsACString& aURL, bool isTracking);
3739 // The JSContext passed to this method represents the context that we want to
3740 // determine if it belongs to a tracker.
3741 bool IsScriptTracking(JSContext* aCx) const;
3743 // For more information on Flash classification, see
3744 // toolkit/components/url-classifier/flash-block-lists.rst
3745 FlashClassification DocumentFlashClassification();
3747 // ResizeObserver usage.
3748 void AddResizeObserver(ResizeObserver&);
3749 void RemoveResizeObserver(ResizeObserver&);
3750 void ScheduleResizeObserversNotification() const;
3752 // Getter for PermissionDelegateHandler. Performs lazy initialization.
3753 PermissionDelegateHandler* GetPermissionDelegateHandler();
3755 // Notify the document that a fetch or a XHR request has completed
3756 // succesfully in this document. This is used by the password manager to infer
3757 // whether a form is submitted.
3758 void NotifyFetchOrXHRSuccess();
3760 // Set whether NotifyFetchOrXHRSuccess should dispatch an event.
3761 void SetNotifyFetchSuccess(bool aShouldNotify);
3763 // When this is set, removing a form or a password field from DOM
3764 // sends a Chrome-only event. This is now only used by the password manager.
3765 void SetNotifyFormOrPasswordRemoved(bool aShouldNotify);
3767 // This function is used by HTMLFormElement and HTMLInputElement to determin
3768 // whether to send an event when it is removed from DOM.
3769 bool ShouldNotifyFormOrPasswordRemoved() const {
3770 return mShouldNotifyFormOrPasswordRemoved;
3774 * Localization
3776 * For more information on DocumentL10n see
3777 * intl/l10n/docs/fluent_tutorial.rst
3780 public:
3782 * This is a public method exposed on Document WebIDL
3783 * to chrome only documents.
3785 DocumentL10n* GetL10n();
3788 * This method should be called when the container
3789 * of l10n resources parsing is completed.
3791 * It triggers initial async fetch of the resources
3792 * as early as possible.
3794 * In HTML case this is </head>.
3795 * In XUL case this is </linkset>.
3797 void OnL10nResourceContainerParsed();
3800 * This method should be called when a link element
3801 * with rel="localization" is being added to the
3802 * l10n resource container element.
3804 void LocalizationLinkAdded(Element* aLinkElement);
3807 * This method should be called when a link element
3808 * with rel="localization" is being removed.
3810 void LocalizationLinkRemoved(Element* aLinkElement);
3813 * This method should be called as soon as the
3814 * parsing of the document is completed.
3816 * In HTML/XHTML this happens when we finish parsing
3817 * the document element.
3818 * In XUL it happens at `DoneWalking`, during
3819 * `MozBeforeInitialXULLayout`.
3821 void OnParsingCompleted();
3824 * This method is called when the initial translation
3825 * of the document is completed.
3827 * It unblocks the load event if translation was blocking it.
3829 * If the `aL10nCached` is set to `true`, and the document has
3830 * a prototype, it will set the `isL10nCached` flag on it.
3832 void InitialTranslationCompleted(bool aL10nCached);
3835 * Returns whether the document allows localization.
3837 bool AllowsL10n() const;
3839 protected:
3840 RefPtr<DocumentL10n> mDocumentL10n;
3843 * Return true when you want a document without explicitly specified viewport
3844 * dimensions/scale to be treated as if "width=device-width" had in fact been
3845 * specified.
3847 virtual bool UseWidthDeviceWidthFallbackViewport() const;
3849 private:
3850 bool IsErrorPage() const;
3852 // Takes the bits from mStyleUseCounters if appropriate, and sets them in
3853 // mUseCounters.
3854 void SetCssUseCounterBits();
3856 void ParseWidthAndHeightInMetaViewport(const nsAString& aWidthString,
3857 const nsAString& aHeightString,
3858 bool aIsAutoScale);
3860 // Parse scale values in viewport meta tag for a given |aHeaderField| which
3861 // represents the scale property and returns the scale value if it's valid.
3862 Maybe<LayoutDeviceToScreenScale> ParseScaleInHeader(nsAtom* aHeaderField);
3864 // Parse scale values in |aViewportMetaData| and set the values in
3865 // mScaleMinFloat, mScaleMaxFloat and mScaleFloat respectively.
3866 void ParseScalesInViewportMetaData(const ViewportMetaData& aViewportMetaData);
3868 // Get parent FeaturePolicy from container. The parent FeaturePolicy is
3869 // stored in parent iframe or container's browsingContext (cross process)
3870 already_AddRefed<mozilla::dom::FeaturePolicy> GetParentFeaturePolicy();
3872 FlashClassification DocumentFlashClassificationInternal();
3874 public:
3875 bool IsThirdPartyForFlashClassifier();
3877 private:
3878 void DoCacheAllKnownLangPrefs();
3879 void RecomputeLanguageFromCharset();
3880 bool GetSHEntryHasUserInteraction();
3882 public:
3883 void SetMayNeedFontPrefsUpdate() { mMayNeedFontPrefsUpdate = true; }
3885 bool MayNeedFontPrefsUpdate() { return mMayNeedFontPrefsUpdate; }
3887 void SetSHEntryHasUserInteraction(bool aHasInteraction);
3889 already_AddRefed<nsAtom> GetContentLanguageAsAtomForStyle() const;
3890 already_AddRefed<nsAtom> GetLanguageForStyle() const;
3893 * Fetch the user's font preferences for the given aLanguage's
3894 * language group.
3896 const LangGroupFontPrefs* GetFontPrefsForLang(
3897 nsAtom* aLanguage, bool* aNeedsToCache = nullptr) const;
3899 void ForceCacheLang(nsAtom* aLanguage) {
3900 if (!mLanguagesUsed.EnsureInserted(aLanguage)) {
3901 return;
3903 GetFontPrefsForLang(aLanguage);
3906 void CacheAllKnownLangPrefs() {
3907 if (!mMayNeedFontPrefsUpdate) {
3908 return;
3910 DoCacheAllKnownLangPrefs();
3913 nsINode* GetServoRestyleRoot() const { return mServoRestyleRoot; }
3915 uint32_t GetServoRestyleRootDirtyBits() const {
3916 MOZ_ASSERT(mServoRestyleRoot);
3917 MOZ_ASSERT(mServoRestyleRootDirtyBits);
3918 return mServoRestyleRootDirtyBits;
3921 void ClearServoRestyleRoot() {
3922 mServoRestyleRoot = nullptr;
3923 mServoRestyleRootDirtyBits = 0;
3926 inline void SetServoRestyleRoot(nsINode* aRoot, uint32_t aDirtyBits);
3927 inline void SetServoRestyleRootDirtyBits(uint32_t aDirtyBits);
3929 bool ShouldThrowOnDynamicMarkupInsertion() {
3930 return mThrowOnDynamicMarkupInsertionCounter;
3933 void IncrementThrowOnDynamicMarkupInsertionCounter() {
3934 ++mThrowOnDynamicMarkupInsertionCounter;
3937 void DecrementThrowOnDynamicMarkupInsertionCounter() {
3938 MOZ_ASSERT(mThrowOnDynamicMarkupInsertionCounter);
3939 --mThrowOnDynamicMarkupInsertionCounter;
3942 bool ShouldIgnoreOpens() const { return mIgnoreOpensDuringUnloadCounter; }
3944 void IncrementIgnoreOpensDuringUnloadCounter() {
3945 ++mIgnoreOpensDuringUnloadCounter;
3948 void DecrementIgnoreOpensDuringUnloadCounter() {
3949 MOZ_ASSERT(mIgnoreOpensDuringUnloadCounter);
3950 --mIgnoreOpensDuringUnloadCounter;
3953 mozilla::dom::FeaturePolicy* FeaturePolicy() const;
3955 bool ModuleScriptsEnabled();
3958 * Find the (non-anonymous) content in this document for aFrame. It will
3959 * be aFrame's content node if that content is in this document and not
3960 * anonymous. Otherwise, when aFrame is in a subdocument, we use the frame
3961 * element containing the subdocument containing aFrame, and/or find the
3962 * nearest non-anonymous ancestor in this document.
3963 * Returns null if there is no such element.
3965 nsIContent* GetContentInThisDocument(nsIFrame* aFrame) const;
3967 void ReportShadowDOMUsage();
3969 // Sets flags for media telemetry.
3970 void SetDocTreeHadMedia();
3972 dom::XPathEvaluator* XPathEvaluator();
3974 void MaybeInitializeFinalizeFrameLoaders();
3976 void SetDelayFrameLoaderInitialization(bool aDelayFrameLoaderInitialization) {
3977 mDelayFrameLoaderInitialization = aDelayFrameLoaderInitialization;
3980 void SetPrototypeDocument(nsXULPrototypeDocument* aPrototype);
3982 nsIPermissionDelegateHandler* PermDelegateHandler();
3984 // CSS prefers-color-scheme media feature for this document.
3985 enum class IgnoreRFP { No, Yes };
3986 StylePrefersColorScheme PrefersColorScheme(IgnoreRFP = IgnoreRFP::No) const;
3988 // Returns true if we use overlay scrollbars on the system wide or on the
3989 // given document.
3990 static bool UseOverlayScrollbars(const Document* aDocument);
3992 static bool HasRecentlyStartedForegroundLoads();
3994 static bool AutomaticStorageAccessPermissionCanBeGranted(
3995 nsIPrincipal* aPrincipal);
3997 already_AddRefed<Promise> AddCertException(bool aIsTemporary);
3999 // Subframes need to be static cloned after the main document has been
4000 // embedded within a script global. A `PendingFrameStaticClone` is a static
4001 // clone which has not yet been performed.
4003 // The getter returns a direct reference to an internal array which is
4004 // manipulated from within printing code.
4005 struct PendingFrameStaticClone {
4006 PendingFrameStaticClone() = default;
4007 PendingFrameStaticClone(PendingFrameStaticClone&&) = default;
4008 PendingFrameStaticClone& operator=(PendingFrameStaticClone&&) = default;
4009 ~PendingFrameStaticClone();
4011 RefPtr<nsFrameLoaderOwner> mElement;
4012 RefPtr<nsFrameLoader> mStaticCloneOf;
4014 void AddPendingFrameStaticClone(nsFrameLoaderOwner* aElement,
4015 nsFrameLoader* aStaticCloneOf);
4017 bool ShouldAvoidNativeTheme() const;
4019 static bool IsValidDomain(nsIURI* aOrigHost, nsIURI* aNewURI);
4021 // Inform a parent document that a BrowserBridgeChild has been created for
4022 // an OOP sub-document.
4023 // (This is the OOP counterpart to nsDocLoader::ChildEnteringOnload)
4024 void OOPChildLoadStarted(BrowserBridgeChild* aChild);
4026 // Inform a parent document that the BrowserBridgeChild for one of its
4027 // OOP sub-documents is done calling its onload handler.
4028 // (This is the OOP counterpart to nsDocLoader::ChildDoneWithOnload)
4029 void OOPChildLoadDone(BrowserBridgeChild* aChild);
4031 void ClearOOPChildrenLoading();
4033 bool HasOOPChildrenLoading() { return !mOOPChildrenLoading.IsEmpty(); }
4035 protected:
4036 // Returns the WindowContext for the document that we will contribute
4037 // page use counters to.
4038 WindowContext* GetWindowContextForPageUseCounters() const;
4040 void DoUpdateSVGUseElementShadowTrees();
4042 already_AddRefed<nsIPrincipal> MaybeDowngradePrincipal(
4043 nsIPrincipal* aPrincipal);
4045 void EnsureOnloadBlocker();
4047 void SendToConsole(nsCOMArray<nsISecurityConsoleMessage>& aMessages);
4049 // Returns true if the scheme for the url for this document is "about".
4050 bool IsAboutPage() const;
4052 bool ContainsEMEContent();
4053 bool ContainsMSEContent();
4056 * Returns the title element of the document as defined by the HTML
4057 * specification, or null if there isn't one. For documents whose root
4058 * element is an <svg:svg>, this is the first <svg:title> element that's a
4059 * child of the root. For other documents, it's the first HTML title element
4060 * in the document.
4062 Element* GetTitleElement();
4064 void RecordNavigationTiming(ReadyState aReadyState);
4066 // Recomputes the visibility state but doesn't set the new value.
4067 dom::VisibilityState ComputeVisibilityState() const;
4069 // Since we wouldn't automatically play media from non-visited page, we need
4070 // to notify window when the page was first visited.
4071 void MaybeActiveMediaComponents();
4073 // Apply the fullscreen state to the document, and trigger related
4074 // events. It returns false if the fullscreen element ready check
4075 // fails and nothing gets changed.
4076 bool ApplyFullscreen(UniquePtr<FullscreenRequest>);
4078 void RemoveDocStyleSheetsFromStyleSets();
4079 void ResetStylesheetsToURI(nsIURI* aURI);
4080 void FillStyleSet();
4081 void FillStyleSetUserAndUASheets();
4082 void FillStyleSetDocumentSheets();
4083 void CompatibilityModeChanged();
4084 bool NeedsQuirksSheet() const {
4085 // SVG documents never load quirk.css.
4086 // FIXME(emilio): Can SVG documents be in quirks mode anyway?
4087 return mCompatMode == eCompatibility_NavQuirks && !IsSVGDocument();
4089 void AddContentEditableStyleSheetsToStyleSet(bool aDesignMode);
4090 void RemoveContentEditableStyleSheets();
4091 void AddStyleSheetToStyleSets(StyleSheet&);
4092 void RemoveStyleSheetFromStyleSets(StyleSheet&);
4093 void NotifyStyleSheetApplicableStateChanged();
4094 // Just like EnableStyleSheetsForSet, but doesn't check whether
4095 // aSheetSet is null and allows the caller to control whether to set
4096 // aSheetSet as the preferred set in the CSSLoader.
4097 void EnableStyleSheetsForSetInternal(const nsAString& aSheetSet,
4098 bool aUpdateCSSLoader);
4100 already_AddRefed<nsIURI> GetDomainURI();
4101 already_AddRefed<nsIURI> CreateInheritingURIForHost(
4102 const nsACString& aHostString);
4103 already_AddRefed<nsIURI> RegistrableDomainSuffixOfInternal(
4104 const nsAString& aHostSuffixString, nsIURI* aOrigHost);
4106 void WriteCommon(const nsAString& aText, bool aNewlineTerminate,
4107 mozilla::ErrorResult& aRv);
4108 // A version of WriteCommon used by WebIDL bindings
4109 void WriteCommon(const mozilla::dom::Sequence<nsString>& aText,
4110 bool aNewlineTerminate, mozilla::ErrorResult& rv);
4112 void* GenerateParserKey(void);
4114 private:
4115 // ExecCommandParam indicates how HTMLDocument.execCommand() treats given the
4116 // parameter.
4117 enum class ExecCommandParam : uint8_t {
4118 // Always ignore it.
4119 Ignore,
4120 // Treat the given parameter as-is. If the command requires it, use it.
4121 // Otherwise, ignore it.
4122 String,
4123 // Always treat it as boolean parameter.
4124 Boolean,
4125 // Always treat it as boolean, but inverted.
4126 InvertedBoolean,
4129 using GetEditorCommandFunc = mozilla::EditorCommand*();
4131 struct InternalCommandData {
4132 const char* mXULCommandName;
4133 mozilla::Command mCommand; // uint8_t
4134 // How ConvertToInternalCommand() to treats aValue.
4135 // Its callers don't need to check this.
4136 ExecCommandParam mExecCommandParam; // uint8_t
4137 GetEditorCommandFunc* mGetEditorCommandFunc;
4138 enum class CommandOnTextEditor : uint8_t {
4139 Disabled,
4140 Enabled,
4141 FallThrough, // Not disabled, but handled by HTMLEditor if there is one
4143 CommandOnTextEditor mCommandOnTextEditor;
4145 InternalCommandData()
4146 : mXULCommandName(nullptr),
4147 mCommand(mozilla::Command::DoNothing),
4148 mExecCommandParam(ExecCommandParam::Ignore),
4149 mGetEditorCommandFunc(nullptr),
4150 mCommandOnTextEditor(CommandOnTextEditor::Disabled) {}
4151 InternalCommandData(const char* aXULCommandName, mozilla::Command aCommand,
4152 ExecCommandParam aExecCommandParam,
4153 GetEditorCommandFunc aGetEditorCommandFunc,
4154 CommandOnTextEditor aCommandOnTextEditor)
4155 : mXULCommandName(aXULCommandName),
4156 mCommand(aCommand),
4157 mExecCommandParam(aExecCommandParam),
4158 mGetEditorCommandFunc(aGetEditorCommandFunc),
4159 mCommandOnTextEditor(aCommandOnTextEditor) {}
4161 bool IsAvailableOnlyWhenEditable() const {
4162 return mCommand != mozilla::Command::Cut &&
4163 mCommand != mozilla::Command::Copy &&
4164 mCommand != mozilla::Command::Paste &&
4165 mCommand != mozilla::Command::SetDocumentReadOnly &&
4166 mCommand != mozilla::Command::GetHTML &&
4167 mCommand != mozilla::Command::SelectAll;
4169 bool IsCutOrCopyCommand() const {
4170 return mCommand == mozilla::Command::Cut ||
4171 mCommand == mozilla::Command::Copy;
4173 bool IsPasteCommand() const { return mCommand == mozilla::Command::Paste; }
4177 * AutoEditorCommandTarget considers which editor or global command manager
4178 * handles given command.
4180 class MOZ_RAII AutoEditorCommandTarget {
4181 public:
4182 MOZ_CAN_RUN_SCRIPT AutoEditorCommandTarget(
4183 nsPresContext* aPresContext, const InternalCommandData& aCommandData);
4184 AutoEditorCommandTarget() = delete;
4185 explicit AutoEditorCommandTarget(const AutoEditorCommandTarget& aOther) =
4186 delete;
4188 bool DoNothing() const { return mDoNothing; }
4189 MOZ_CAN_RUN_SCRIPT bool IsEditable(Document* aDocument) const;
4190 bool IsEditor() const {
4191 MOZ_ASSERT_IF(mEditorCommand, mActiveEditor || mHTMLEditor);
4192 return !!mEditorCommand;
4195 MOZ_CAN_RUN_SCRIPT bool IsCommandEnabled() const;
4196 MOZ_CAN_RUN_SCRIPT nsresult DoCommand(nsIPrincipal* aPrincipal) const;
4197 template <typename ParamType>
4198 MOZ_CAN_RUN_SCRIPT nsresult DoCommandParam(const ParamType& aParam,
4199 nsIPrincipal* aPrincipal) const;
4200 MOZ_CAN_RUN_SCRIPT nsresult
4201 GetCommandStateParams(nsCommandParams& aParams) const;
4203 private:
4204 // The returned editor's life is guaranteed while this instance is alive.
4205 EditorBase* GetTargetEditor() const;
4207 RefPtr<EditorBase> mActiveEditor;
4208 RefPtr<HTMLEditor> mHTMLEditor;
4209 RefPtr<EditorCommand> mEditorCommand;
4210 const InternalCommandData& mCommandData;
4211 bool mDoNothing = false;
4215 * Helper method to initialize sInternalCommandDataHashtable.
4217 static void EnsureInitializeInternalCommandDataHashtable();
4220 * ConvertToInternalCommand() returns a copy of InternalCommandData instance.
4221 * Note that if aAdjustedValue is non-nullptr, this method checks whether
4222 * aValue is proper value or not unless InternalCommandData::mExecCommandParam
4223 * is ExecCommandParam::Ignore. For example, if aHTMLCommandName is
4224 * "defaultParagraphSeparator", the value has to be one of "div", "p" or
4225 * "br". If aValue is invalid value for InternalCommandData::mCommand, this
4226 * returns a copy of instance created with default constructor. I.e., its
4227 * mCommand is set to Command::DoNothing. So, this treats aHTMLCommandName
4228 * is unsupported in such case.
4230 * @param aHTMLCommandName Command name in HTML, e.g., used by
4231 * execCommand().
4232 * @param aValue The value which is set to the 3rd parameter
4233 * of execCommand().
4234 * @param aAdjustedValue [out] Must be empty string if set non-nullptr.
4235 * Will be set to adjusted value for executing
4236 * the internal command.
4237 * @return Returns a copy of instance created with the
4238 * default constructor if there is no
4239 * corresponding internal command for
4240 * aHTMLCommandName or aValue is invalid for
4241 * found internal command when aAdjustedValue
4242 * is not nullptr. Otherwise, returns a copy of
4243 * instance registered in
4244 * sInternalCommandDataHashtable.
4246 static InternalCommandData ConvertToInternalCommand(
4247 const nsAString& aHTMLCommandName, const nsAString& aValue = u""_ns,
4248 nsAString* aAdjustedValue = nullptr);
4251 * AutoRunningExecCommandMarker is AutoRestorer for mIsRunningExecCommand.
4252 * Since it's a bit field, not a bool member, therefore, we cannot use
4253 * AutoRestorer for it.
4255 class MOZ_STACK_CLASS AutoRunningExecCommandMarker final {
4256 public:
4257 AutoRunningExecCommandMarker() = delete;
4258 explicit AutoRunningExecCommandMarker(const AutoRunningExecCommandMarker&) =
4259 delete;
4260 // Guaranteeing the document's lifetime with `MOZ_CAN_RUN_SCRIPT`.
4261 MOZ_CAN_RUN_SCRIPT explicit AutoRunningExecCommandMarker(
4262 Document& aDocument)
4263 : mDocument(aDocument),
4264 mHasBeenRunning(aDocument.mIsRunningExecCommand) {
4265 aDocument.mIsRunningExecCommand = true;
4267 ~AutoRunningExecCommandMarker() {
4268 if (!mHasBeenRunning) {
4269 mDocument.mIsRunningExecCommand = false;
4273 private:
4274 Document& mDocument;
4275 bool mHasBeenRunning;
4278 // Mapping table from HTML command name to internal command.
4279 using InternalCommandDataHashtable =
4280 nsTHashMap<nsStringCaseInsensitiveHashKey, InternalCommandData>;
4281 static InternalCommandDataHashtable* sInternalCommandDataHashtable;
4283 mutable std::bitset<static_cast<size_t>(
4284 DeprecatedOperations::eDeprecatedOperationCount)>
4285 mDeprecationWarnedAbout;
4286 mutable std::bitset<eDocumentWarningCount> mDocWarningWarnedAbout;
4288 // Lazy-initialization to have mDocGroup initialized in prior to the
4289 // SelectorCaches.
4290 UniquePtr<SelectorCache> mSelectorCache;
4291 UniquePtr<ServoStyleSet> mStyleSet;
4293 protected:
4294 friend class nsDocumentOnStack;
4296 void IncreaseStackRefCnt() { ++mStackRefCnt; }
4298 void DecreaseStackRefCnt() {
4299 if (--mStackRefCnt == 0 && mNeedsReleaseAfterStackRefCntRelease) {
4300 mNeedsReleaseAfterStackRefCntRelease = false;
4301 NS_RELEASE_THIS();
4305 // Never ever call this. Only call GetWindow!
4306 nsPIDOMWindowOuter* GetWindowInternal() const;
4308 // Never ever call this. Only call GetScriptHandlingObject!
4309 nsIScriptGlobalObject* GetScriptHandlingObjectInternal() const;
4311 // Never ever call this. Only call AllowXULXBL!
4312 bool InternalAllowXULXBL();
4315 * These methods should be called before and after dispatching
4316 * a mutation event.
4317 * To make this easy and painless, use the mozAutoSubtreeModified helper
4318 * class.
4320 void WillDispatchMutationEvent(nsINode* aTarget);
4321 void MutationEventDispatched(nsINode* aTarget);
4322 friend class mozAutoSubtreeModified;
4324 virtual Element* GetNameSpaceElement() override { return GetRootElement(); }
4326 void SetContentTypeInternal(const nsACString& aType);
4328 nsCString GetContentTypeInternal() const { return mContentType; }
4330 // Update our frame request callback scheduling state, if needed. This will
4331 // schedule or unschedule them, if necessary, and update
4332 // mFrameRequestCallbacksScheduled. aOldShell should only be passed when
4333 // mPresShell is becoming null; in that case it will be used to get hold of
4334 // the relevant refresh driver.
4335 void UpdateFrameRequestCallbackSchedulingState(
4336 PresShell* aOldPresShell = nullptr);
4338 // Helper for GetScrollingElement/IsScrollingElement.
4339 bool IsPotentiallyScrollable(HTMLBodyElement* aBody);
4341 void MaybeAllowStorageForOpenerAfterUserInteraction();
4343 void MaybeStoreUserInteractionAsPermission();
4345 // Helpers for GetElementsByName.
4346 static bool MatchNameAttribute(Element* aElement, int32_t aNamespaceID,
4347 nsAtom* aAtom, void* aData);
4348 static void* UseExistingNameString(nsINode* aRootNode, const nsString* aName);
4350 void MaybeResolveReadyForIdle();
4352 using AutomaticStorageAccessPermissionGrantPromise =
4353 MozPromise<bool, bool, true>;
4354 [[nodiscard]] RefPtr<AutomaticStorageAccessPermissionGrantPromise>
4355 AutomaticStorageAccessPermissionCanBeGranted();
4357 static void AddToplevelLoadingDocument(Document* aDoc);
4358 static void RemoveToplevelLoadingDocument(Document* aDoc);
4359 static AutoTArray<Document*, 8>* sLoadingForegroundTopLevelContentDocument;
4360 friend class cycleCollection;
4362 nsCOMPtr<nsIReferrerInfo> mPreloadReferrerInfo;
4363 nsCOMPtr<nsIReferrerInfo> mReferrerInfo;
4365 nsString mLastModified;
4367 nsCOMPtr<nsIURI> mDocumentURI;
4368 nsCOMPtr<nsIURI> mOriginalURI;
4369 nsCOMPtr<nsIURI> mChromeXHRDocURI;
4370 nsCOMPtr<nsIURI> mDocumentBaseURI;
4371 nsCOMPtr<nsIURI> mChromeXHRDocBaseURI;
4373 // The base domain of the document for third-party checks.
4374 nsCString mBaseDomain;
4376 // A lazily-constructed URL data for style system to resolve URL value.
4377 RefPtr<URLExtraData> mCachedURLData;
4378 nsCOMPtr<nsIReferrerInfo> mCachedReferrerInfo;
4380 nsWeakPtr mDocumentLoadGroup;
4382 WeakPtr<nsDocShell> mDocumentContainer;
4384 NotNull<const Encoding*> mCharacterSet;
4385 int32_t mCharacterSetSource;
4387 // This is just a weak pointer; the parent document owns its children.
4388 Document* mParentDocument;
4390 // A reference to the element last returned from GetRootElement().
4391 Element* mCachedRootElement;
4393 // This is a weak reference, but we hold a strong reference to mNodeInfo,
4394 // which in turn holds a strong reference to this mNodeInfoManager.
4395 nsNodeInfoManager* mNodeInfoManager;
4396 RefPtr<css::Loader> mCSSLoader;
4397 RefPtr<css::ImageLoader> mStyleImageLoader;
4398 RefPtr<nsHTMLStyleSheet> mAttrStyleSheet;
4399 RefPtr<nsHTMLCSSStyleSheet> mStyleAttrStyleSheet;
4401 // Tracking for images in the document.
4402 RefPtr<dom::ImageTracker> mImageTracker;
4404 // A hashtable of ShadowRoots belonging to the composed doc.
4406 // See ShadowRoot::Bind and ShadowRoot::Unbind.
4407 ShadowRootSet mComposedShadowRoots;
4409 using SVGUseElementSet = nsTHashSet<SVGUseElement*>;
4411 // The set of <svg:use> elements that need a shadow tree reclone because the
4412 // tree they map to has changed.
4413 SVGUseElementSet mSVGUseElementsNeedingShadowTreeUpdate;
4415 // The set of all object, embed, video/audio elements or
4416 // nsIObjectLoadingContent or DocumentActivity for which this is
4417 // the owner document. (They might not be in the document.)
4419 // These are non-owning pointers, the elements are responsible for removing
4420 // themselves when they go away.
4421 UniquePtr<nsTHashSet<nsISupports*>> mActivityObservers;
4423 // A hashtable of styled links keyed by address pointer.
4424 nsTHashSet<Link*> mStyledLinks;
4425 #ifdef DEBUG
4426 // Indicates whether mStyledLinks was cleared or not. This is used to track
4427 // state so we can provide useful assertions to consumers of ForgetLink and
4428 // AddStyleRelevantLink.
4429 bool mStyledLinksCleared;
4430 #endif
4432 // The array of all links that need their status resolved. Links must add
4433 // themselves to this set by calling RegisterPendingLinkUpdate when added to a
4434 // document.
4435 static const size_t kSegmentSize = 128;
4437 using LinksToUpdateList =
4438 SegmentedVector<nsCOMPtr<Link>, kSegmentSize, InfallibleAllocPolicy>;
4440 LinksToUpdateList mLinksToUpdate;
4442 // SMIL Animation Controller, lazily-initialized in GetAnimationController
4443 RefPtr<SMILAnimationController> mAnimationController;
4445 // Table of element properties for this document.
4446 nsPropertyTable mPropertyTable;
4448 // Our cached .children collection
4449 nsCOMPtr<nsIHTMLCollection> mChildrenCollection;
4451 // Various DOM lists
4452 RefPtr<nsContentList> mImages;
4453 RefPtr<nsContentList> mEmbeds;
4454 RefPtr<nsContentList> mLinks;
4455 RefPtr<nsContentList> mForms;
4456 RefPtr<nsContentList> mScripts;
4457 nsCOMPtr<nsIHTMLCollection> mApplets;
4458 RefPtr<nsContentList> mAnchors;
4460 // container for per-context fonts (downloadable, SVG, etc.)
4461 RefPtr<FontFaceSet> mFontFaceSet;
4463 // Last time this document or a one of its sub-documents was focused. If
4464 // focus has never occurred then mLastFocusTime.IsNull() will be true.
4465 TimeStamp mLastFocusTime;
4467 EventStates mDocumentState;
4469 RefPtr<Promise> mReadyForIdle;
4471 RefPtr<mozilla::dom::FeaturePolicy> mFeaturePolicy;
4473 UniquePtr<ResizeObserverController> mResizeObserverController;
4475 // Permission Delegate Handler, lazily-initialized in
4476 // GetPermissionDelegateHandler
4477 RefPtr<PermissionDelegateHandler> mPermissionDelegateHandler;
4479 bool mBlockAllMixedContent : 1;
4480 bool mBlockAllMixedContentPreloads : 1;
4481 bool mUpgradeInsecureRequests : 1;
4482 bool mUpgradeInsecurePreloads : 1;
4483 bool mDevToolsWatchingDOMMutations : 1;
4485 // True if BIDI is enabled.
4486 bool mBidiEnabled : 1;
4487 // True if we may need to recompute the language prefs for this document.
4488 bool mMayNeedFontPrefsUpdate : 1;
4489 // True if a MathML element has ever been owned by this document.
4490 bool mMathMLEnabled : 1;
4492 // True if this document is the initial document for a window. This should
4493 // basically be true only for documents that exist in newly-opened windows or
4494 // documents created to satisfy a GetDocument() on a window when there's no
4495 // document in it.
4496 bool mIsInitialDocumentInWindow : 1;
4498 bool mIgnoreDocGroupMismatches : 1;
4500 // True if we're loaded as data and therefor has any dangerous stuff, such
4501 // as scripts and plugins, disabled.
4502 bool mLoadedAsData : 1;
4504 // True if the document is considered for memory reporting as a
4505 // data document
4506 bool mAddedToMemoryReportingAsDataDocument : 1;
4508 // If true, whoever is creating the document has gotten it to the
4509 // point where it's safe to start layout on it.
4510 bool mMayStartLayout : 1;
4512 // True iff we've ever fired a DOMTitleChanged event for this document
4513 bool mHaveFiredTitleChange : 1;
4515 // State for IsShowing(). mIsShowing starts off false. It becomes true when
4516 // OnPageShow happens and becomes false when OnPageHide happens. So it's false
4517 // before the initial load completes and when we're in bfcache or unloaded,
4518 // true otherwise.
4519 bool mIsShowing : 1;
4521 // State for IsVisible(). mVisible starts off true. It becomes false when
4522 // OnPageHide happens, and becomes true again when OnPageShow happens. So
4523 // it's false only when we're in bfcache or unloaded.
4524 bool mVisible : 1;
4526 // True if our content viewer has been removed from the docshell
4527 // (it may still be displayed, but in zombie state). Form control data
4528 // has been saved.
4529 bool mRemovedFromDocShell : 1;
4531 // True iff DNS prefetch is allowed for this document. Note that if the
4532 // document has no window, DNS prefetch won't be performed no matter what.
4533 bool mAllowDNSPrefetch : 1;
4535 // True when this document is a static clone of a normal document
4536 bool mIsStaticDocument : 1;
4538 // True while this document is being cloned to a static document.
4539 bool mCreatingStaticClone : 1;
4541 // True if this static document has any <canvas> element with a
4542 // mozPrintCallback property at the time of the clone.
4543 bool mHasPrintCallbacks : 1;
4545 // True iff the document is being unlinked or deleted.
4546 bool mInUnlinkOrDeletion : 1;
4548 // True if document has ever had script handling object.
4549 bool mHasHadScriptHandlingObject : 1;
4551 // True if we're an SVG document being used as an image.
4552 bool mIsBeingUsedAsImage : 1;
4554 // True if our current document URI's scheme is chrome://
4555 bool mDocURISchemeIsChrome : 1;
4557 // True if we're loaded in a chrome docshell.
4558 bool mInChromeDocShell : 1;
4560 // True if our current document is a DevTools document. Either the url is
4561 // about:devtools-toolbox or the parent document already has
4562 // mIsDevToolsDocument set to true.
4563 // This is used to avoid applying High Contrast mode to DevTools documents.
4564 // See Bug 1575766.
4565 bool mIsDevToolsDocument : 1;
4567 // True is this document is synthetic : stand alone image, video, audio
4568 // file, etc.
4569 bool mIsSyntheticDocument : 1;
4571 // True is there is a pending runnable which will call
4572 // FlushPendingLinkUpdates().
4573 bool mHasLinksToUpdateRunnable : 1;
4575 // True if we're flushing pending link updates.
4576 bool mFlushingPendingLinkUpdates : 1;
4578 // True if a DOMMutationObserver is perhaps attached to a node in the
4579 // document.
4580 bool mMayHaveDOMMutationObservers : 1;
4582 // True if an nsIAnimationObserver is perhaps attached to a node in the
4583 // document.
4584 bool mMayHaveAnimationObservers : 1;
4586 // True if a document load has a CSP attached.
4587 bool mHasCSP : 1;
4589 // True if a document load has a CSP with unsafe-eval attached.
4590 bool mHasUnsafeEvalCSP : 1;
4592 // True if a document load has a CSP with unsafe-inline attached.
4593 bool mHasUnsafeInlineCSP : 1;
4595 // True if the document has a CSP delivered throuh a header
4596 bool mHasCSPDeliveredThroughHeader : 1;
4598 // True if DisallowBFCaching has been called on this document.
4599 bool mBFCacheDisallowed : 1;
4601 bool mHasHadDefaultView : 1;
4603 // Whether style sheet change events will be dispatched for this document
4604 bool mStyleSheetChangeEventsEnabled : 1;
4606 // Whether shadowrootattached events will be dispatched for this document.
4607 bool mShadowRootAttachedEventEnabled : 1;
4609 // Whether the document was created by a srcdoc iframe.
4610 bool mIsSrcdocDocument : 1;
4612 // Whether this document has a display document and thus is considered to
4613 // be a resource document. Normally this is the same as !!mDisplayDocument,
4614 // but mDisplayDocument is cleared during Unlink. mHasDisplayDocument is
4615 // valid in the document's destructor.
4616 bool mHasDisplayDocument : 1;
4618 // Is the current mFontFaceSet valid?
4619 bool mFontFaceSetDirty : 1;
4621 // True if we have fired the DOMContentLoaded event, or don't plan to fire one
4622 // (e.g. we're not being parsed at all).
4623 bool mDidFireDOMContentLoaded : 1;
4625 // True if ReportHasScrollLinkedEffect() has been called.
4626 bool mHasScrollLinkedEffect : 1;
4628 // True if we have frame request callbacks scheduled with the refresh driver.
4629 // This should generally be updated only via
4630 // UpdateFrameRequestCallbackSchedulingState.
4631 bool mFrameRequestCallbacksScheduled : 1;
4633 bool mIsTopLevelContentDocument : 1;
4635 bool mIsContentDocument : 1;
4637 // True if we have called BeginLoad and are expecting a paired EndLoad call.
4638 bool mDidCallBeginLoad : 1;
4640 // True if the encoding menu should be disabled.
4641 bool mEncodingMenuDisabled : 1;
4643 // False if we've disabled link handling for elements inside this document,
4644 // true otherwise.
4645 bool mLinksEnabled : 1;
4647 // True if this document is for an SVG-in-OpenType font.
4648 bool mIsSVGGlyphsDocument : 1;
4650 // True if the document is being destroyed.
4651 bool mInDestructor : 1;
4653 // True if the document has been detached from its content viewer.
4654 bool mIsGoingAway : 1;
4656 bool mInXBLUpdate : 1;
4658 bool mNeedsReleaseAfterStackRefCntRelease : 1;
4660 // Whether we have filled our style set with all the stylesheets.
4661 bool mStyleSetFilled : 1;
4663 // Whether we have a quirks mode stylesheet in the style set.
4664 bool mQuirkSheetAdded : 1;
4666 // Whether we have a contenteditable.css stylesheet in the style set.
4667 bool mContentEditableSheetAdded : 1;
4669 // Whether we have a designmode.css stylesheet in the style set.
4670 bool mDesignModeSheetAdded : 1;
4672 // Keeps track of whether we have a pending
4673 // 'style-sheet-applicable-state-changed' notification.
4674 bool mSSApplicableStateNotificationPending : 1;
4676 // True if this document has ever had an HTML or SVG <title> element
4677 // bound to it
4678 bool mMayHaveTitleElement : 1;
4680 bool mDOMLoadingSet : 1;
4681 bool mDOMInteractiveSet : 1;
4682 bool mDOMCompleteSet : 1;
4683 bool mAutoFocusFired : 1;
4685 bool mScrolledToRefAlready : 1;
4686 bool mChangeScrollPosWhenScrollingToRef : 1;
4688 bool mDelayFrameLoaderInitialization : 1;
4690 bool mSynchronousDOMContentLoaded : 1;
4692 // Set to true when the document is possibly controlled by the ServiceWorker.
4693 // Used to prevent multiple requests to ServiceWorkerManager.
4694 bool mMaybeServiceWorkerControlled : 1;
4696 // These member variables cache information about the viewport so we don't
4697 // have to recalculate it each time.
4698 bool mAllowZoom : 1;
4699 bool mValidScaleFloat : 1;
4700 bool mValidMinScale : 1;
4701 bool mValidMaxScale : 1;
4702 bool mWidthStrEmpty : 1;
4704 // Parser aborted. True if the parser of this document was forcibly
4705 // terminated instead of letting it finish at its own pace.
4706 bool mParserAborted : 1;
4708 // Whether we have reported document use counters for this document with
4709 // Telemetry yet. Normally this is only done at document destruction time,
4710 // but for image documents (SVG documents) that are not guaranteed to be
4711 // destroyed, we report use counters when the image cache no longer has any
4712 // imgRequestProxys pointing to them. We track whether we ever reported use
4713 // counters so that we only report them once for the document.
4714 bool mReportedDocumentUseCounters : 1;
4716 bool mHasReportedShadowDOMUsage : 1;
4718 // Whether an event triggered by the refresh driver was delayed because this
4719 // document has suppressed events.
4720 bool mHasDelayedRefreshEvent : 1;
4722 // The HTML spec has a "iframe load in progress" flag, but that doesn't seem
4723 // to have the right semantics. See
4724 // <https://github.com/whatwg/html/issues/4292>. What we have instead is a
4725 // flag that is set while the window's 'load' event is firing if this document
4726 // is the window's document.
4727 bool mLoadEventFiring : 1;
4729 // The HTML spec has a "mute iframe load" flag, but that doesn't seem to have
4730 // the right semantics. See <https://github.com/whatwg/html/issues/4292>.
4731 // What we have instead is a flag that is set if completion of our document
4732 // via document.close() should skip firing the load event. Note that this
4733 // flag is only relevant for HTML documents, but lives here for reasons that
4734 // are documented above on SkipLoadEventAfterClose().
4735 bool mSkipLoadEventAfterClose : 1;
4737 // When false, the .cookies property is completely disabled
4738 bool mDisableCookieAccess : 1;
4740 // When false, the document.write() API is disabled.
4741 bool mDisableDocWrite : 1;
4743 // Has document.write() been called with a recursion depth higher than
4744 // allowed?
4745 bool mTooDeepWriteRecursion : 1;
4748 * Temporary flag that is set in EndUpdate() to ignore
4749 * MaybeEditingStateChanged() script runners from a nested scope.
4751 bool mPendingMaybeEditingStateChanged : 1;
4753 // mHasBeenEditable is set to true when mEditingState is firstly set to
4754 // eDesignMode or eContentEditable.
4755 bool mHasBeenEditable : 1;
4757 // Whether we've warned about the CSS zoom property.
4759 // We don't use the general deprecated operation mechanism for this because we
4760 // also record this as a `CountedUnknownProperty`.
4761 bool mHasWarnedAboutZoom : 1;
4763 // While we're handling an execCommand call, set to true.
4764 bool mIsRunningExecCommand : 1;
4766 // True if we should change the readystate to complete after we fire
4767 // DOMContentLoaded. This happens when we abort a load and
4768 // nsDocumentViewer::EndLoad runs while we still have things blocking
4769 // DOMContentLoaded. We wait for those to complete, and then update the
4770 // readystate when they finish.
4771 bool mSetCompleteAfterDOMContentLoaded : 1;
4773 uint8_t mPendingFullscreenRequests;
4775 uint8_t mXMLDeclarationBits;
4777 // NOTE(emilio): Technically, this should be a StyleColorSchemeFlags, but we
4778 // use uint8_t to avoid having to include a bunch of style system headers
4779 // everywhere.
4780 uint8_t mColorSchemeBits = 0;
4782 // Currently active onload blockers.
4783 uint32_t mOnloadBlockCount;
4785 // Onload blockers which haven't been activated yet.
4786 uint32_t mAsyncOnloadBlockCount;
4788 // Tracks if we are currently processing any document.write calls (either
4789 // implicit or explicit). Note that if a write call writes out something which
4790 // would block the parser, then mWriteLevel will be incorrect until the parser
4791 // finishes processing that script.
4792 uint32_t mWriteLevel;
4794 // The amount of images that have `loading="lazy"` on the page or have loaded
4795 // lazily already.
4796 uint32_t mLazyLoadImageCount;
4797 // Number of lazy-loaded images that we've started loading as a result of
4798 // triggering the lazy-load observer threshold.
4799 uint32_t mLazyLoadImageStarted;
4800 // Number of lazy-loaded images that reached the viewport which were not done
4801 // loading when they did so.
4802 uint32_t mLazyLoadImageReachViewportLoading;
4803 // Number of lazy-loaded images that reached the viewport and were done
4804 // loading when they did so.
4805 uint32_t mLazyLoadImageReachViewportLoaded;
4807 uint32_t mContentEditableCount;
4808 EditingState mEditingState;
4810 // Compatibility mode
4811 nsCompatibility mCompatMode;
4813 // Our readyState
4814 ReadyState mReadyState;
4816 // Ancestor's loading state
4817 bool mAncestorIsLoading;
4819 // Our visibility state
4820 dom::VisibilityState mVisibilityState;
4822 enum Type {
4823 eUnknown, // should never be used
4824 eHTML,
4825 eXHTML,
4826 eGenericXML,
4827 eSVG
4830 Type mType;
4832 uint8_t mDefaultElementType;
4834 enum Tri { eTriUnset = 0, eTriFalse, eTriTrue };
4836 Tri mAllowXULXBL;
4838 bool mSkipDTDSecurityChecks;
4840 // The document's script global object, the object from which the
4841 // document can get its script context and scope. This is the
4842 // *inner* window object.
4843 nsCOMPtr<nsIScriptGlobalObject> mScriptGlobalObject;
4845 // If mIsStaticDocument is true, mOriginalDocument points to the original
4846 // document.
4847 RefPtr<Document> mOriginalDocument;
4849 // The bidi options for this document. What this bitfield means is
4850 // defined in nsBidiUtils.h
4851 uint32_t mBidiOptions;
4853 // The sandbox flags on the document. These reflect the value of the sandbox
4854 // attribute of the associated IFRAME or CSP-protectable content, if existent.
4855 // These are set at load time and are immutable - see nsSandboxFlags.h for the
4856 // possible flags.
4857 uint32_t mSandboxFlags;
4859 // The embedder policy obtained from parsing the HTTP response header or from
4860 // our opener if this is the initial about:blank document.
4861 Maybe<nsILoadInfo::CrossOriginEmbedderPolicy> mEmbedderPolicy;
4863 nsCString mContentLanguage;
4865 // The channel that got passed to Document::StartDocumentLoad(), if any.
4866 nsCOMPtr<nsIChannel> mChannel;
4868 // The CSP for every load lives in the Client within the LoadInfo. For all
4869 // document-initiated subresource loads we can use that cached version of the
4870 // CSP so we do not have to deserialize the CSP from the Client all the time.
4871 nsCOMPtr<nsIContentSecurityPolicy> mCSP;
4872 nsCOMPtr<nsIContentSecurityPolicy> mPreloadCSP;
4874 private:
4875 nsCString mContentType;
4877 protected:
4878 // The document's security info
4879 nsCOMPtr<nsISupports> mSecurityInfo;
4881 // The channel that failed to load and resulted in an error page.
4882 // This only applies to error pages. Might be null.
4883 nsCOMPtr<nsIChannel> mFailedChannel;
4885 // if this document is part of a multipart document,
4886 // the ID can be used to distinguish it from the other parts.
4887 uint32_t mPartID;
4889 // Cycle collector generation in which we're certain that this document
4890 // won't be collected
4891 uint32_t mMarkedCCGeneration;
4893 PresShell* mPresShell;
4895 nsCOMArray<nsINode> mSubtreeModifiedTargets;
4896 uint32_t mSubtreeModifiedDepth;
4898 // All images in process of being preloaded. This is a hashtable so
4899 // we can remove them as the real image loads start; that way we
4900 // make sure to not keep the image load going when no one cares
4901 // about it anymore.
4902 nsRefPtrHashtable<nsURIHashKey, imgIRequest> mPreloadingImages;
4904 // A list of preconnects initiated by the preloader. This prevents
4905 // the same uri from being used more than once, and allows the dom
4906 // builder to not repeat the work of the preloader.
4907 nsTHashMap<nsURIHashKey, bool> mPreloadedPreconnects;
4909 // Current depth of picture elements from parser
4910 uint32_t mPreloadPictureDepth;
4912 // Set if we've found a URL for the current picture
4913 nsString mPreloadPictureFoundSource;
4915 // If we're an external resource document, this will be non-null and will
4916 // point to our "display document": the one that all resource lookups should
4917 // go to.
4918 RefPtr<Document> mDisplayDocument;
4920 uint32_t mEventsSuppressed;
4922 // Any XHR ChannelEventQueues that were suspended on this document while
4923 // events were suppressed.
4924 nsTArray<RefPtr<net::ChannelEventQueue>> mSuspendedQueues;
4926 // Any postMessage events that were suspended on this document while events
4927 // were suppressed.
4928 nsTArray<RefPtr<PostMessageEvent>> mSuspendedPostMessageEvents;
4930 RefPtr<EventListener> mSuppressedEventListener;
4933 * https://html.spec.whatwg.org/#ignore-destructive-writes-counter
4935 uint32_t mIgnoreDestructiveWritesCounter;
4938 * The current frame request callback handle
4940 int32_t mFrameRequestCallbackCounter;
4942 // Count of live static clones of this document.
4943 uint32_t mStaticCloneCount;
4945 // If the document is currently printing (or in print preview) this will point
4946 // to the current static clone of this document. This is weak since the clone
4947 // also has a reference to this document.
4948 WeakPtr<Document> mLatestStaticClone;
4950 // Array of nodes that have been blocked to prevent user tracking.
4951 // They most likely have had their nsIChannel canceled by the URL
4952 // classifier. (Safebrowsing)
4954 // Weak nsINode pointers are used to allow nodes to disappear.
4955 nsTArray<nsWeakPtr> mBlockedNodesByClassifier;
4957 // Weak reference to mScriptGlobalObject QI:d to nsPIDOMWindow,
4958 // updated on every set of mScriptGlobalObject.
4959 nsPIDOMWindowInner* mWindow;
4961 nsCOMPtr<nsIDocumentEncoder> mCachedEncoder;
4963 nsTArray<FrameRequest> mFrameRequestCallbacks;
4965 // The set of frame request callbacks that were canceled but which we failed
4966 // to find in mFrameRequestCallbacks.
4967 HashSet<int32_t> mCanceledFrameRequestCallbacks;
4969 // This object allows us to evict ourself from the back/forward cache. The
4970 // pointer is non-null iff we're currently in the bfcache.
4971 nsIBFCacheEntry* mBFCacheEntry;
4973 // Our base target.
4974 nsString mBaseTarget;
4976 nsCOMPtr<nsIStructuredCloneContainer> mStateObjectContainer;
4977 nsCOMPtr<nsIVariant> mStateObjectCached;
4979 uint32_t mInSyncOperationCount;
4981 UniquePtr<dom::XPathEvaluator> mXPathEvaluator;
4983 nsTArray<RefPtr<AnonymousContent>> mAnonymousContents;
4985 uint32_t mBlockDOMContentLoaded;
4987 // Our live MediaQueryLists
4988 LinkedList<MediaQueryList> mDOMMediaQueryLists;
4990 // Array of observers
4991 nsTObserverArray<nsIDocumentObserver*> mObservers;
4993 // Flags for use counters used directly by this document.
4994 UseCounters mUseCounters;
4995 // Flags for use counters from resource documents, static clones,
4996 // and SVG images referenced by this document. Those documents propagate
4997 // their use counters up to here, which then count towards the top-level
4998 // document's page use counters.
4999 UseCounters mChildDocumentUseCounters;
5001 // The CSS property use counters.
5002 UniquePtr<StyleUseCounters> mStyleUseCounters;
5004 // Whether we have initialized mShouldReportUseCounters and
5005 // mShouldSendPageUseCounters, and sent any needed message to the parent
5006 // process to indicate that use counter data will be sent at some later point.
5007 bool mUseCountersInitialized : 1;
5009 // Whether this document should report use counters.
5010 bool mShouldReportUseCounters : 1;
5012 // Whether this document should send page use counters. Set to true after
5013 // we've called SendExpectPageUseCounters on the top-level WindowGlobal.
5014 bool mShouldSendPageUseCounters : 1;
5016 // Whether the user has interacted with the document or not:
5017 bool mUserHasInteracted;
5019 // We constantly update the user-interaction anti-tracking permission at any
5020 // user-interaction using a timer. This boolean value is set to true when this
5021 // timer is scheduled.
5022 bool mHasUserInteractionTimerScheduled;
5024 TimeStamp mPageUnloadingEventTimeStamp;
5026 RefPtr<DocGroup> mDocGroup;
5028 RefPtr<nsCommandManager> mMidasCommandManager;
5030 // The set of all the tracking script URLs. URLs are added to this set by
5031 // calling NoteScriptTrackingStatus(). Currently we assume that a URL not
5032 // existing in the set means the corresponding script isn't a tracking script.
5033 nsTHashSet<nsCString> mTrackingScripts;
5035 // Pointer to our parser if we're currently in the process of being
5036 // parsed into.
5037 nsCOMPtr<nsIParser> mParser;
5039 // If the document was created from the the prototype cache there will be a
5040 // reference to the prototype document to allow tracing.
5041 RefPtr<nsXULPrototypeDocument> mPrototypeDocument;
5043 nsrefcnt mStackRefCnt;
5045 // Weak reference to our sink for in case we no longer have a parser. This
5046 // will allow us to flush out any pending stuff from the sink even if
5047 // EndLoad() has already happened.
5048 nsWeakPtr mWeakSink;
5050 // Our update nesting level
5051 uint32_t mUpdateNestLevel;
5053 // HTTPS-Only Mode Status
5054 // Constants are defined at nsILoadInfo::HTTPS_ONLY_*
5055 uint32_t mHttpsOnlyStatus;
5057 enum ViewportType : uint8_t {
5058 DisplayWidthHeight,
5059 Specified,
5060 Unknown,
5063 ViewportType mViewportType;
5065 // viewport-fit described by
5066 // https://drafts.csswg.org/css-round-display/#viewport-fit-descriptor
5067 ViewportFitType mViewportFit;
5069 PLDHashTable* mSubDocuments;
5071 DocHeaderData* mHeaderData;
5073 // For determining if this is a flash document which should be
5074 // blocked based on its principal.
5075 FlashClassification mFlashClassification;
5077 // Do not use this value directly. Call the |IsThirdPartyForFlashClassifier()|
5078 // method, which caches its result here.
5079 Maybe<bool> mIsThirdPartyForFlashClassifier;
5081 nsRevocableEventPtr<nsRunnableMethod<Document, void, false>>
5082 mPendingTitleChangeEvent;
5084 RefPtr<nsDOMNavigationTiming> mTiming;
5086 // Recorded time of change to 'loading' state.
5087 TimeStamp mLoadingTimeStamp;
5089 nsWeakPtr mAutoFocusElement;
5091 nsCString mScrollToRef;
5093 // Weak reference to the scope object (aka the script global object)
5094 // that, unlike mScriptGlobalObject, is never unset once set. This
5095 // is a weak reference to avoid leaks due to circular references.
5096 nsWeakPtr mScopeObject;
5098 // Array of intersection observers
5099 nsTHashSet<DOMIntersectionObserver*> mIntersectionObservers;
5101 RefPtr<DOMIntersectionObserver> mLazyLoadImageObserver;
5102 // Used to measure how effective the lazyload thresholds are.
5103 RefPtr<DOMIntersectionObserver> mLazyLoadImageObserverViewport;
5105 // Stack of top layer elements.
5106 nsTArray<nsWeakPtr> mTopLayer;
5108 // The root of the doc tree in which this document is in. This is only
5109 // non-null when this document is in fullscreen mode.
5110 nsWeakPtr mFullscreenRoot;
5112 RefPtr<DOMImplementation> mDOMImplementation;
5114 RefPtr<nsContentList> mImageMaps;
5116 // A set of responsive images keyed by address pointer.
5117 nsTHashSet<HTMLImageElement*> mResponsiveContent;
5119 RefPtr<DocumentTimeline> mDocumentTimeline;
5120 LinkedList<DocumentTimeline> mTimelines;
5122 RefPtr<dom::ScriptLoader> mScriptLoader;
5124 // Tracker for animations that are waiting to start.
5125 // nullptr until GetOrCreatePendingAnimationTracker is called.
5126 RefPtr<PendingAnimationTracker> mPendingAnimationTracker;
5128 // A document "without a browsing context" that owns the content of
5129 // HTMLTemplateElement.
5130 RefPtr<Document> mTemplateContentsOwner;
5132 dom::ExternalResourceMap mExternalResourceMap;
5134 // ScreenOrientation "pending promise" as described by
5135 // http://www.w3.org/TR/screen-orientation/
5136 RefPtr<Promise> mOrientationPendingPromise;
5138 nsTArray<RefPtr<nsFrameLoader>> mInitializableFrameLoaders;
5139 nsTArray<nsCOMPtr<nsIRunnable>> mFrameLoaderFinalizers;
5140 RefPtr<nsRunnableMethod<Document>> mFrameLoaderRunner;
5142 nsTArray<PendingFrameStaticClone> mPendingFrameStaticClones;
5144 // The layout history state that should be used by nodes in this
5145 // document. We only actually store a pointer to it when:
5146 // 1) We have no script global object.
5147 // 2) We haven't had Destroy() called on us yet.
5148 nsCOMPtr<nsILayoutHistoryState> mLayoutHistoryState;
5150 struct MetaViewportElementAndData;
5151 // An array of <meta name="viewport"> elements and their data.
5152 nsTArray<MetaViewportElementAndData> mMetaViewports;
5154 // These member variables cache information about the viewport so we don't
5155 // have to recalculate it each time.
5156 LayoutDeviceToScreenScale mScaleMinFloat;
5157 LayoutDeviceToScreenScale mScaleMaxFloat;
5158 LayoutDeviceToScreenScale mScaleFloat;
5159 CSSToLayoutDeviceScale mPixelRatio;
5161 CSSCoord mMinWidth;
5162 CSSCoord mMaxWidth;
5163 CSSCoord mMinHeight;
5164 CSSCoord mMaxHeight;
5166 RefPtr<EventListenerManager> mListenerManager;
5168 nsCOMPtr<nsIRequest> mOnloadBlocker;
5170 // Gecko-internal sheets used for extensions and such.
5171 // Exposed to privileged script via nsIDOMWindowUtils.loadSheet.
5172 nsTArray<RefPtr<StyleSheet>> mAdditionalSheets[AdditionalSheetTypeCount];
5174 // Member to store out last-selected stylesheet set.
5175 nsString mLastStyleSheetSet;
5176 nsString mPreferredStyleSheetSet;
5178 RefPtr<DOMStyleSheetSetList> mStyleSheetSetList;
5180 // We lazily calculate declaration blocks for SVG elements with mapped
5181 // attributes in Servo mode. This list contains all elements which need lazy
5182 // resolution.
5183 nsTHashSet<SVGElement*> mLazySVGPresElements;
5185 nsTHashSet<RefPtr<nsAtom>> mLanguagesUsed;
5187 // TODO(emilio): Is this hot enough to warrant to be cached?
5188 RefPtr<nsAtom> mLanguageFromCharset;
5190 // Restyle root for servo's style system.
5192 // We store this as an nsINode, rather than as an Element, so that we can
5193 // store the Document node as the restyle root if the entire document (along
5194 // with all document-level native-anonymous content) needs to be restyled.
5196 // We also track which "descendant" bits (normal/animation-only/lazy-fc) the
5197 // root corresponds to.
5198 nsCOMPtr<nsINode> mServoRestyleRoot;
5199 uint32_t mServoRestyleRootDirtyBits;
5201 // Used in conjunction with the create-an-element-for-the-token algorithm to
5202 // prevent custom element constructors from being able to use document.open(),
5203 // document.close(), and document.write() when they are invoked by the parser.
5204 uint32_t mThrowOnDynamicMarkupInsertionCounter;
5206 // Count of unload/beforeunload/pagehide operations in progress.
5207 uint32_t mIgnoreOpensDuringUnloadCounter;
5209 nsCOMPtr<nsIDOMXULCommandDispatcher>
5210 mCommandDispatcher; // [OWNER] of the focus tracker
5212 RefPtr<XULBroadcastManager> mXULBroadcastManager;
5213 RefPtr<XULPersist> mXULPersist;
5214 RefPtr<ChromeObserver> mChromeObserver;
5216 RefPtr<HTMLAllCollection> mAll;
5218 // document lightweight theme for use with :-moz-lwtheme,
5219 // :-moz-lwtheme-brighttext and :-moz-lwtheme-darktext
5220 DocumentTheme mDocLWTheme;
5222 // Pres shell resolution saved before entering fullscreen mode.
5223 float mSavedResolution;
5225 // Pres shell resolution saved before creating a MobileViewportManager.
5226 float mSavedResolutionBeforeMVM;
5228 nsCOMPtr<nsICookieJarSettings> mCookieJarSettings;
5230 bool mHasStoragePermission;
5232 // Document generation. Gets incremented everytime it changes.
5233 int32_t mGeneration;
5235 // Cached TabSizes values for the document.
5236 int32_t mCachedTabSizeGeneration;
5237 nsTabSizes mCachedTabSizes;
5239 // This is equal to document's principal but with an isolation key. See
5240 // StoragePrincipalHelper.h to know more.
5241 nsCOMPtr<nsIPrincipal> mPartitionedPrincipal;
5243 // The cached storage principal for this document.
5244 // This is mutable so that we can keep EffectiveStoragePrincipal() const
5245 // which is required due to its CloneDocHelper() call site. :-(
5246 mutable nsCOMPtr<nsIPrincipal> mActiveStoragePrincipal;
5248 // See GetNextFormNumber and GetNextControlNumber.
5249 int32_t mNextFormNumber;
5250 int32_t mNextControlNumber;
5252 uint32_t mMediaElementWithMSECount = 0;
5254 // Scope preloads per document. This is used by speculative loading as well.
5255 PreloadService mPreloadService;
5257 // See NotifyFetchOrXHRSuccess and SetNotifyFetchSuccess.
5258 bool mShouldNotifyFetchSuccess;
5260 // See SetNotifyFormOrPasswordRemoved and ShouldNotifyFormOrPasswordRemoved.
5261 bool mShouldNotifyFormOrPasswordRemoved;
5263 // Accumulate JS telemetry collected
5264 void AccumulateJSTelemetry();
5266 // Accumulate page load metrics
5267 void AccumulatePageLoadTelemetry();
5269 // The OOP counterpart to nsDocLoader::mChildrenInOnload.
5270 // Not holding strong refs here since we don't actually use the BBCs.
5271 nsTArray<const BrowserBridgeChild*> mOOPChildrenLoading;
5273 public:
5274 // Needs to be public because the bindings code pokes at it.
5275 JS::ExpandoAndGeneration mExpandoAndGeneration;
5277 bool HasPendingInitialTranslation();
5279 nsRefPtrHashtable<nsRefPtrHashKey<Element>, nsXULPrototypeElement>
5280 mL10nProtoElements;
5282 void TraceProtos(JSTracer* aTrc);
5284 float GetSavedResolutionBeforeMVM() { return mSavedResolutionBeforeMVM; }
5285 void SetSavedResolutionBeforeMVM(float aResolution) {
5286 mSavedResolutionBeforeMVM = aResolution;
5289 void LoadEventFired();
5292 NS_DEFINE_STATIC_IID_ACCESSOR(Document, NS_IDOCUMENT_IID)
5295 * mozAutoSubtreeModified batches DOM mutations so that a DOMSubtreeModified
5296 * event is dispatched, if necessary, when the outermost mozAutoSubtreeModified
5297 * object is deleted.
5299 class MOZ_STACK_CLASS mozAutoSubtreeModified {
5300 public:
5302 * @param aSubTreeOwner The document in which a subtree will be modified.
5303 * @param aTarget The target of the possible DOMSubtreeModified event.
5304 * Can be nullptr, in which case mozAutoSubtreeModified
5305 * is just used to batch DOM mutations.
5307 mozAutoSubtreeModified(Document* aSubtreeOwner, nsINode* aTarget) {
5308 UpdateTarget(aSubtreeOwner, aTarget);
5311 ~mozAutoSubtreeModified() { UpdateTarget(nullptr, nullptr); }
5313 void UpdateTarget(Document* aSubtreeOwner, nsINode* aTarget) {
5314 if (mSubtreeOwner) {
5315 mSubtreeOwner->MutationEventDispatched(mTarget);
5318 mTarget = aTarget;
5319 mSubtreeOwner = aSubtreeOwner;
5320 if (mSubtreeOwner) {
5321 mSubtreeOwner->WillDispatchMutationEvent(mTarget);
5325 private:
5326 nsCOMPtr<nsINode> mTarget;
5327 RefPtr<Document> mSubtreeOwner;
5330 enum class SyncOperationBehavior { eSuspendInput, eAllowInput };
5332 class AutoWalkBrowsingContextGroup {
5333 public:
5334 virtual ~AutoWalkBrowsingContextGroup() = default;
5336 protected:
5337 void SuppressBrowsingContext(BrowsingContext* aContext);
5338 void SuppressBrowsingContextGroup(BrowsingContextGroup* aGroup);
5339 void UnsuppressDocuments() {
5340 for (const auto& doc : mDocuments) {
5341 UnsuppressDocument(doc);
5344 virtual void SuppressDocument(Document* aDocument) = 0;
5345 virtual void UnsuppressDocument(Document* aDocument) = 0;
5346 AutoTArray<RefPtr<Document>, 16> mDocuments;
5349 class MOZ_RAII nsAutoSyncOperation : private AutoWalkBrowsingContextGroup {
5350 public:
5351 explicit nsAutoSyncOperation(Document* aDocument,
5352 SyncOperationBehavior aSyncBehavior);
5353 ~nsAutoSyncOperation();
5355 protected:
5356 void SuppressDocument(Document* aDocument) override;
5357 void UnsuppressDocument(Document* aDocument) override;
5359 private:
5360 uint32_t mMicroTaskLevel;
5361 const SyncOperationBehavior mSyncBehavior;
5362 RefPtr<BrowsingContext> mBrowsingContext;
5365 class MOZ_RAII AutoSetThrowOnDynamicMarkupInsertionCounter final {
5366 public:
5367 explicit AutoSetThrowOnDynamicMarkupInsertionCounter(Document* aDocument)
5368 : mDocument(aDocument) {
5369 mDocument->IncrementThrowOnDynamicMarkupInsertionCounter();
5372 ~AutoSetThrowOnDynamicMarkupInsertionCounter() {
5373 mDocument->DecrementThrowOnDynamicMarkupInsertionCounter();
5376 private:
5377 Document* mDocument;
5380 class MOZ_RAII IgnoreOpensDuringUnload final {
5381 public:
5382 explicit IgnoreOpensDuringUnload(Document* aDoc) : mDoc(aDoc) {
5383 mDoc->IncrementIgnoreOpensDuringUnloadCounter();
5386 ~IgnoreOpensDuringUnload() {
5387 mDoc->DecrementIgnoreOpensDuringUnloadCounter();
5390 private:
5391 Document* mDoc;
5394 bool IsInActiveTab(Document* aDoc);
5396 } // namespace dom
5397 } // namespace mozilla
5399 // XXX These belong somewhere else
5400 nsresult NS_NewHTMLDocument(mozilla::dom::Document** aInstancePtrResult,
5401 bool aLoadedAsData = false);
5403 nsresult NS_NewXMLDocument(mozilla::dom::Document** aInstancePtrResult,
5404 bool aLoadedAsData = false,
5405 bool aIsPlainDocument = false);
5407 nsresult NS_NewSVGDocument(mozilla::dom::Document** aInstancePtrResult);
5409 nsresult NS_NewImageDocument(mozilla::dom::Document** aInstancePtrResult);
5411 nsresult NS_NewVideoDocument(mozilla::dom::Document** aInstancePtrResult);
5413 // Enum for requesting a particular type of document when creating a doc
5414 enum DocumentFlavor {
5415 DocumentFlavorLegacyGuess, // compat with old code until made HTML5-compliant
5416 DocumentFlavorHTML, // HTMLDocument with HTMLness bit set to true
5417 DocumentFlavorSVG, // SVGDocument
5418 DocumentFlavorXML, // XMLDocument
5419 DocumentFlavorPlain, // Just a Document
5422 // Note: it's the caller's responsibility to create or get aPrincipal as needed
5423 // -- this method will not attempt to get a principal based on aDocumentURI.
5424 // Also, both aDocumentURI and aBaseURI must not be null.
5425 nsresult NS_NewDOMDocument(
5426 mozilla::dom::Document** aInstancePtrResult, const nsAString& aNamespaceURI,
5427 const nsAString& aQualifiedName, mozilla::dom::DocumentType* aDoctype,
5428 nsIURI* aDocumentURI, nsIURI* aBaseURI, nsIPrincipal* aPrincipal,
5429 bool aLoadedAsData, nsIGlobalObject* aEventObject, DocumentFlavor aFlavor);
5431 nsresult NS_NewPluginDocument(mozilla::dom::Document** aInstancePtrResult);
5433 inline mozilla::dom::Document* nsINode::GetOwnerDocument() const {
5434 mozilla::dom::Document* ownerDoc = OwnerDoc();
5436 return ownerDoc != this ? ownerDoc : nullptr;
5439 inline nsINode* nsINode::OwnerDocAsNode() const { return OwnerDoc(); }
5441 inline mozilla::dom::Document* nsINode::AsDocument() {
5442 MOZ_ASSERT(IsDocument());
5443 return static_cast<mozilla::dom::Document*>(this);
5446 inline const mozilla::dom::Document* nsINode::AsDocument() const {
5447 MOZ_ASSERT(IsDocument());
5448 return static_cast<const mozilla::dom::Document*>(this);
5451 inline nsISupports* ToSupports(mozilla::dom::Document* aDoc) {
5452 return static_cast<nsINode*>(aDoc);
5455 #endif /* mozilla_dom_Document_h___ */