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/. */
6 #ifndef nsIDocument_h___
7 #define nsIDocument_h___
8
9 #include "mozFlushType.h" // for enum
10 #include "nsAutoPtr.h" // for member
11 #include "nsCOMArray.h" // for member
12 #include "nsCRT.h" // for NS_DECL_AND_IMPL_ZEROING_OPERATOR_NEW
13 #include "nsCompatibility.h" // for member
14 #include "nsCOMPtr.h" // for member
15 #include "nsGkAtoms.h" // for static class members
16 #include "nsIDocumentObserver.h" // for typedef (nsUpdateType)
17 #include "nsILoadGroup.h" // for member (in nsCOMPtr)
18 #include "nsINode.h" // for base class
19 #include "nsIScriptGlobalObject.h" // for member (in nsCOMPtr)
20 #include "nsIServiceManager.h"
21 #include "nsIUUIDGenerator.h"
22 #include "nsPIDOMWindow.h" // for use in inline functions
23 #include "nsPropertyTable.h" // for member
24 #include "nsDataHashtable.h" // for member
25 #include "nsURIHashKey.h" // for member
26 #include "mozilla/net/ReferrerPolicy.h" // for member
27 #include "nsWeakReference.h"
28 #include "mozilla/UseCounter.h"
29 #include "mozilla/WeakPtr.h"
30 #include "Units.h"
31 #include "nsContentListDeclarations.h"
32 #include "nsExpirationTracker.h"
33 #include "nsClassHashtable.h"
34 #include "prclist.h"
35 #include "mozilla/UniquePtr.h"
36 #include "mozilla/CORSMode.h"
37 #include "mozilla/LinkedList.h"
38 #include "mozilla/StyleBackendType.h"
39 #include "mozilla/StyleSheet.h"
40 #include "mozilla/TimeStamp.h"
41 #include <bitset> // for member
42
43 #ifdef MOZILLA_INTERNAL_API
44 #include "mozilla/dom/DocumentBinding.h"
45 #else
46 namespace mozilla {
47 namespace dom {
48 class ElementCreationOptionsOrString;
49 } // namespace dom
50 } // namespace mozilla
51 #endif // MOZILLA_INTERNAL_API
52
53 class gfxUserFontSet;
54 class imgIRequest;
55 class nsAString;
56 class nsBindingManager;
57 class nsIDocShell;
58 class nsDocShell;
59 class nsDOMNavigationTiming;
60 class nsFrameLoader;
61 class nsHTMLCSSStyleSheet;
62 class nsHTMLDocument;
63 class nsHTMLStyleSheet;
64 class nsIAtom;
65 class nsIBFCacheEntry;
66 class nsIChannel;
67 class nsIContent;
68 class nsIContentSink;
69 class nsIDocShell;
70 class nsIDocShellTreeItem;
71 class nsIDocumentEncoder;
72 class nsIDocumentObserver;
73 class nsIDOMDocument;
74 class nsIDOMDocumentType;
75 class nsIDOMElement;
76 class nsIDOMNodeFilter;
77 class nsIDOMNodeList;
78 class nsIHTMLCollection;
79 class nsILayoutHistoryState;
80 class nsILoadContext;
81 class nsIObjectLoadingContent;
82 class nsIObserver;
83 class nsIPresShell;
84 class nsIPrincipal;
85 class nsIRequest;
86 class nsIRunnable;
87 class nsIStreamListener;
88 class nsIStructuredCloneContainer;
89 class nsIURI;
90 class nsIVariant;
91 class nsViewManager;
92 class nsPresContext;
93 class nsRange;
94 class nsScriptLoader;
95 class nsSMILAnimationController;
96 class nsTextNode;
97 class nsWindowSizes;
98 class nsDOMCaretPosition;
99 class nsViewportInfo;
100 class nsIGlobalObject;
101 struct nsCSSSelectorList;
102
103 namespace mozilla {
104 class CSSStyleSheet;
105 class ErrorResult;
106 class EventStates;
107 class PendingAnimationTracker;
108 class StyleSetHandle;
109 class SVGAttrAnimationRuleProcessor;
110 template<typename> class OwningNonNull;
111
112 namespace css {
113 class Loader;
114 class ImageLoader;
115 class Rule;
116 } // namespace css
117
118 namespace dom {
119 class Animation;
120 class AnonymousContent;
121 class Attr;
122 class BoxObject;
123 class CDATASection;
124 class Comment;
125 struct CustomElementDefinition;
126 class DocGroup;
127 class DocumentFragment;
128 class DocumentTimeline;
129 class DocumentType;
130 class DOMImplementation;
131 class DOMIntersectionObserver;
132 class DOMStringList;
133 class Element;
134 struct ElementCreationOptions;
135 struct ElementRegistrationOptions;
136 class Event;
137 class EventTarget;
138 class FontFaceSet;
139 class FrameRequestCallback;
140 struct FullscreenRequest;
141 class ImageTracker;
142 class ImportManager;
143 class HTMLBodyElement;
144 struct LifecycleCallbackArgs;
145 class Link;
146 class Location;
147 class MediaQueryList;
148 class GlobalObject;
149 class NodeFilter;
150 class NodeIterator;
151 enum class OrientationType : uint32_t;
152 class ProcessingInstruction;
153 class Promise;
154 class StyleSheetList;
155 class SVGDocument;
156 class SVGSVGElement;
157 class Touch;
158 class TouchList;
159 class TreeWalker;
160 class XPathEvaluator;
161 class XPathExpression;
162 class XPathNSResolver;
163 class XPathResult;
164 template<typename> class Sequence;
165
166 template<typename, typename> class CallbackObjectHolder;
167 typedef CallbackObjectHolder<NodeFilter, nsIDOMNodeFilter> NodeFilterHolder;
168
169 } // namespace dom
170 } // namespace mozilla
171
172 #define NS_IDOCUMENT_IID \
173 { 0xce1f7627, 0x7109, 0x4977, \
174 { 0xba, 0x77, 0x49, 0x0f, 0xfd, 0xe0, 0x7a, 0xaa } }
175
176 // Enum for requesting a particular type of document when creating a doc
177 enum DocumentFlavor {
178 DocumentFlavorLegacyGuess, // compat with old code until made HTML5-compliant
179 DocumentFlavorHTML, // HTMLDocument with HTMLness bit set to true
180 DocumentFlavorSVG, // SVGDocument
181 DocumentFlavorPlain, // Just a Document
182 };
183
184 // Enum for HSTS priming states
185 enum class HSTSPrimingState {
186 eNO_HSTS_PRIMING = 0, // don't do HSTS Priming
187 eHSTS_PRIMING_ALLOW = 1, // if HSTS priming fails, allow the load to proceed
188 eHSTS_PRIMING_BLOCK = 2 // if HSTS priming fails, block the load
189 };
190
191 // Document states
192
193 // RTL locale: specific to the XUL localedir attribute
194 #define NS_DOCUMENT_STATE_RTL_LOCALE NS_DEFINE_EVENT_STATE_MACRO(0)
195 // Window activation status
196 #define NS_DOCUMENT_STATE_WINDOW_INACTIVE NS_DEFINE_EVENT_STATE_MACRO(1)
197
198 // Some function forward-declarations
199 class nsContentList;
200
201 //----------------------------------------------------------------------
202
203 // Document interface. This is implemented by all document objects in
204 // Gecko.
205 class nsIDocument : public nsINode
206 {
207 typedef mozilla::dom::GlobalObject GlobalObject;
208
209 public:
210 typedef mozilla::net::ReferrerPolicy ReferrerPolicyEnum;
211 typedef mozilla::dom::Element Element;
212 typedef mozilla::dom::FullscreenRequest FullscreenRequest;
213
214 NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOCUMENT_IID)
215 NS_DECL_AND_IMPL_ZEROING_OPERATOR_NEW
216
217 #ifdef MOZILLA_INTERNAL_API
218 nsIDocument();
219 #endif
220
221 // This helper class must be set when we dispatch beforeunload and unload
222 // events in order to avoid unterminate sync XHRs.
223 class MOZ_RAII PageUnloadingEventTimeStamp
224 {
225 nsCOMPtr<nsIDocument> mDocument;
226 bool mSet;
227
228 public:
PageUnloadingEventTimeStamp(nsIDocument * aDocument)229 explicit PageUnloadingEventTimeStamp(nsIDocument* aDocument)
230 : mDocument(aDocument)
231 , mSet(false)
232 {
233 MOZ_ASSERT(aDocument);
234 if (mDocument->mPageUnloadingEventTimeStamp.IsNull()) {
235 mDocument->SetPageUnloadingEventTimeStamp();
236 mSet = true;
237 }
238 }
239
~PageUnloadingEventTimeStamp()240 ~PageUnloadingEventTimeStamp()
241 {
242 if (mSet) {
243 mDocument->CleanUnloadEventsTimeStamp();
244 }
245 }
246 };
247
248 /**
249 * Let the document know that we're starting to load data into it.
250 * @param aCommand The parser command. Must not be null.
251 * XXXbz It's odd to have that here.
252 * @param aChannel The channel the data will come from. The channel must be
253 * able to report its Content-Type.
254 * @param aLoadGroup The loadgroup this document should use from now on.
255 * Note that the document might not be the only thing using
256 * this loadgroup.
257 * @param aContainer The container this document is in. This may be null.
258 * XXXbz maybe we should make it more explicit (eg make the
259 * container an nsIWebNavigation or nsIDocShell or
260 * something)?
261 * @param [out] aDocListener the listener to pump data from the channel into.
262 * Generally this will be the parser this document
263 * sets up, or some sort of data-handler for media
264 * documents.
265 * @param aReset whether the document should call Reset() on itself. If this
266 * is false, the document will NOT set its principal to the
267 * channel's owner, will not clear any event listeners that are
268 * already set on it, etc.
269 * @param aSink The content sink to use for the data. If this is null and
270 * the document needs a content sink, it will create one based
271 * on whatever it knows about the data it's going to load.
272 * This MUST be null if the underlying document is an HTML
273 * document. Even in the XML case, please don't add new calls
274 * with non-null sink.
275 *
276 * Once this has been called, the document will return false for
277 * MayStartLayout() until SetMayStartLayout(true) is called on it. Making
278 * sure this happens is the responsibility of the caller of
279 * StartDocumentLoad().
280 */
281 virtual nsresult StartDocumentLoad(const char* aCommand,
282 nsIChannel* aChannel,
283 nsILoadGroup* aLoadGroup,
284 nsISupports* aContainer,
285 nsIStreamListener **aDocListener,
286 bool aReset,
287 nsIContentSink* aSink = nullptr) = 0;
288 virtual void StopDocumentLoad() = 0;
289
SetSuppressParserErrorElement(bool aSuppress)290 virtual void SetSuppressParserErrorElement(bool aSuppress) {}
SuppressParserErrorElement()291 virtual bool SuppressParserErrorElement() { return false; }
292
SetSuppressParserErrorConsoleMessages(bool aSuppress)293 virtual void SetSuppressParserErrorConsoleMessages(bool aSuppress) {}
SuppressParserErrorConsoleMessages()294 virtual bool SuppressParserErrorConsoleMessages() { return false; }
295
296 /**
297 * Signal that the document title may have changed
298 * (see nsDocument::GetTitle).
299 * @param aBoundTitleElement true if an HTML or SVG <title> element
300 * has just been bound to the document.
301 */
302 virtual void NotifyPossibleTitleChange(bool aBoundTitleElement) = 0;
303
304 /**
305 * Return the URI for the document. May return null.
306 *
307 * The value returned corresponds to the "document's address" in
308 * HTML5. As such, it may change over the lifetime of the document, for
309 * instance as a result of the user navigating to a fragment identifier on
310 * the page, or as a result to a call to pushState() or replaceState().
311 *
312 * https://html.spec.whatwg.org/multipage/dom.html#the-document%27s-address
313 */
GetDocumentURI()314 nsIURI* GetDocumentURI() const
315 {
316 return mDocumentURI;
317 }
318
319 /**
320 * Return the original URI of the document. This is the same as the
321 * document's URI unless that has changed from its original value (for
322 * example, due to history.pushState() or replaceState() being invoked on the
323 * document).
324 *
325 * This method corresponds to the "creation URL" in HTML5 and, once set,
326 * doesn't change over the lifetime of the document.
327 *
328 * https://html.spec.whatwg.org/multipage/webappapis.html#creation-url
329 */
GetOriginalURI()330 nsIURI* GetOriginalURI() const
331 {
332 return mOriginalURI;
333 }
334
335 /**
336 * Set the URI for the document. This also sets the document's original URI,
337 * if it's null.
338 */
339 virtual void SetDocumentURI(nsIURI* aURI) = 0;
340
341 /**
342 * Set the URI for the document loaded via XHR, when accessed from
343 * chrome privileged script.
344 */
345 virtual void SetChromeXHRDocURI(nsIURI* aURI) = 0;
346
347 /**
348 * Set the base URI for the document loaded via XHR, when accessed from
349 * chrome privileged script.
350 */
351 virtual void SetChromeXHRDocBaseURI(nsIURI* aURI) = 0;
352
353 /**
354 * Set referrer policy and upgrade-insecure-requests flags
355 */
356 virtual void ApplySettingsFromCSP(bool aSpeculative) = 0;
357
358 /**
359 * Return the referrer policy of the document. Return "default" if there's no
360 * valid meta referrer tag found in the document.
361 */
GetReferrerPolicy()362 ReferrerPolicyEnum GetReferrerPolicy() const
363 {
364 return mReferrerPolicy;
365 }
366
367 /**
368 * GetReferrerPolicy() for Document.webidl.
369 */
ReferrerPolicy()370 uint32_t ReferrerPolicy() const
371 {
372 return GetReferrerPolicy();
373 }
374
375 /**
376 * If true, this flag indicates that all mixed content subresource
377 * loads for this document (and also embeded browsing contexts) will
378 * be blocked.
379 */
GetBlockAllMixedContent(bool aPreload)380 bool GetBlockAllMixedContent(bool aPreload) const
381 {
382 if (aPreload) {
383 return mBlockAllMixedContentPreloads;
384 }
385 return mBlockAllMixedContent;
386 }
387
388 /**
389 * If true, this flag indicates that all subresource loads for this
390 * document need to be upgraded from http to https.
391 * This flag becomes true if the CSP of the document itself, or any
392 * of the document's ancestors up to the toplevel document makes use
393 * of the CSP directive 'upgrade-insecure-requests'.
394 */
GetUpgradeInsecureRequests(bool aPreload)395 bool GetUpgradeInsecureRequests(bool aPreload) const
396 {
397 if (aPreload) {
398 return mUpgradeInsecurePreloads;
399 }
400 return mUpgradeInsecureRequests;
401 }
402
SetReferrer(const nsACString & aReferrer)403 void SetReferrer(const nsACString& aReferrer) {
404 mReferrer = aReferrer;
405 }
406
407 /**
408 * Check to see if a subresource we want to load requires HSTS priming
409 * to be done.
410 */
GetHSTSPrimingStateForLocation(nsIURI * aContentLocation)411 HSTSPrimingState GetHSTSPrimingStateForLocation(nsIURI* aContentLocation) const
412 {
413 HSTSPrimingState state;
414 if (mHSTSPrimingURIList.Get(aContentLocation, &state)) {
415 return state;
416 }
417 return HSTSPrimingState::eNO_HSTS_PRIMING;
418 }
419
420 /**
421 * Add a subresource to the HSTS priming list. If this URI is
422 * not in the HSTS cache, it will trigger an HSTS priming request
423 * when we try to load it.
424 */
AddHSTSPrimingLocation(nsIURI * aContentLocation,HSTSPrimingState aState)425 void AddHSTSPrimingLocation(nsIURI* aContentLocation, HSTSPrimingState aState)
426 {
427 mHSTSPrimingURIList.Put(aContentLocation, aState);
428 }
429
ClearHSTSPrimingLocation(nsIURI * aContentLocation)430 void ClearHSTSPrimingLocation(nsIURI* aContentLocation)
431 {
432 mHSTSPrimingURIList.Remove(aContentLocation);
433 }
434
435 /**
436 * Set the principal responsible for this document.
437 */
438 virtual void SetPrincipal(nsIPrincipal *aPrincipal) = 0;
439
440 /**
441 * Return the LoadGroup for the document. May return null.
442 */
GetDocumentLoadGroup()443 already_AddRefed<nsILoadGroup> GetDocumentLoadGroup() const
444 {
445 nsCOMPtr<nsILoadGroup> group = do_QueryReferent(mDocumentLoadGroup);
446 return group.forget();
447 }
448
449 /**
450 * Return the fallback base URL for this document, as defined in the HTML
451 * specification. Note that this can return null if there is no document URI.
452 *
453 * XXXbz: This doesn't implement the bits for about:blank yet.
454 */
GetFallbackBaseURI()455 nsIURI* GetFallbackBaseURI() const
456 {
457 if (mIsSrcdocDocument && mParentDocument) {
458 return mParentDocument->GetDocBaseURI();
459 }
460 return mDocumentURI;
461 }
462
463 /**
464 * Return the base URI for relative URIs in the document (the document uri
465 * unless it's overridden by SetBaseURI, HTML <base> tags, etc.). The
466 * returned URI could be null if there is no document URI. If the document is
467 * a srcdoc document and has no explicit base URL, return the parent
468 * document's base URL.
469 */
GetDocBaseURI()470 nsIURI* GetDocBaseURI() const
471 {
472 if (mDocumentBaseURI) {
473 return mDocumentBaseURI;
474 }
475 return GetFallbackBaseURI();
476 }
477 virtual already_AddRefed<nsIURI> GetBaseURI(bool aTryUseXHRDocBaseURI = false) const override;
478
479 virtual void SetBaseURI(nsIURI* aURI) = 0;
480
481 /**
482 * Get/Set the base target of a link in a document.
483 */
484 virtual void GetBaseTarget(nsAString &aBaseTarget) = 0;
SetBaseTarget(const nsString & aBaseTarget)485 void SetBaseTarget(const nsString& aBaseTarget) {
486 mBaseTarget = aBaseTarget;
487 }
488
489 /**
490 * Return a standard name for the document's character set.
491 */
GetDocumentCharacterSet()492 const nsCString& GetDocumentCharacterSet() const
493 {
494 return mCharacterSet;
495 }
496
497 /**
498 * Set the document's character encoding. |aCharSetID| should be canonical.
499 * That is, callers are responsible for the charset alias resolution.
500 */
501 virtual void SetDocumentCharacterSet(const nsACString& aCharSetID) = 0;
502
GetDocumentCharacterSetSource()503 int32_t GetDocumentCharacterSetSource() const
504 {
505 return mCharacterSetSource;
506 }
507
508 // This method MUST be called before SetDocumentCharacterSet if
509 // you're planning to call both.
SetDocumentCharacterSetSource(int32_t aCharsetSource)510 void SetDocumentCharacterSetSource(int32_t aCharsetSource)
511 {
512 mCharacterSetSource = aCharsetSource;
513 }
514
515 /**
516 * Add an observer that gets notified whenever the charset changes.
517 */
518 virtual nsresult AddCharSetObserver(nsIObserver* aObserver) = 0;
519
520 /**
521 * Remove a charset observer.
522 */
523 virtual void RemoveCharSetObserver(nsIObserver* aObserver) = 0;
524
525 /**
526 * This gets fired when the element that an id refers to changes.
527 * This fires at difficult times. It is generally not safe to do anything
528 * which could modify the DOM in any way. Use
529 * nsContentUtils::AddScriptRunner.
530 * @return true to keep the callback in the callback set, false
531 * to remove it.
532 */
533 typedef bool (* IDTargetObserver)(Element* aOldElement,
534 Element* aNewelement, void* aData);
535
536 /**
537 * Add an IDTargetObserver for a specific ID. The IDTargetObserver
538 * will be fired whenever the content associated with the ID changes
539 * in the future. If aForImage is true, mozSetImageElement can override
540 * what content is associated with the ID. In that case the IDTargetObserver
541 * will be notified at those times when the result of LookupImageElement
542 * changes.
543 * At most one (aObserver, aData, aForImage) triple can be
544 * registered for each ID.
545 * @return the content currently associated with the ID.
546 */
547 virtual Element* AddIDTargetObserver(nsIAtom* aID, IDTargetObserver aObserver,
548 void* aData, bool aForImage) = 0;
549 /**
550 * Remove the (aObserver, aData, aForImage) triple for a specific ID, if
551 * registered.
552 */
553 virtual void RemoveIDTargetObserver(nsIAtom* aID, IDTargetObserver aObserver,
554 void* aData, bool aForImage) = 0;
555
556 /**
557 * Get the Content-Type of this document.
558 * (This will always return NS_OK, but has this signature to be compatible
559 * with nsIDOMDocument::GetContentType())
560 */
561 NS_IMETHOD GetContentType(nsAString& aContentType) = 0;
562
563 /**
564 * Set the Content-Type of this document.
565 */
566 virtual void SetContentType(const nsAString& aContentType) = 0;
567
568 /**
569 * Return the language of this document.
570 */
GetContentLanguage(nsAString & aContentLanguage)571 void GetContentLanguage(nsAString& aContentLanguage) const
572 {
573 CopyASCIItoUTF16(mContentLanguage, aContentLanguage);
574 }
575
576 // The states BidiEnabled and MathMLEnabled should persist across multiple views
577 // (screen, print) of the same document.
578
579 /**
580 * Check if the document contains bidi data.
581 * If so, we have to apply the Unicode Bidi Algorithm.
582 */
GetBidiEnabled()583 bool GetBidiEnabled() const
584 {
585 return mBidiEnabled;
586 }
587
588 /**
589 * Indicate the document contains bidi data.
590 * Currently, we cannot disable bidi, because once bidi is enabled,
591 * it affects a frame model irreversibly, and plays even though
592 * the document no longer contains bidi data.
593 */
SetBidiEnabled()594 void SetBidiEnabled()
595 {
596 mBidiEnabled = true;
597 }
598
599 /**
600 * Check if the document contains (or has contained) any MathML elements.
601 */
GetMathMLEnabled()602 bool GetMathMLEnabled() const
603 {
604 return mMathMLEnabled;
605 }
606
SetMathMLEnabled()607 void SetMathMLEnabled()
608 {
609 mMathMLEnabled = true;
610 }
611
612 /**
613 * Ask this document whether it's the initial document in its window.
614 */
IsInitialDocument()615 bool IsInitialDocument() const
616 {
617 return mIsInitialDocumentInWindow;
618 }
619
620 /**
621 * Tell this document that it's the initial document in its window. See
622 * comments on mIsInitialDocumentInWindow for when this should be called.
623 */
SetIsInitialDocument(bool aIsInitialDocument)624 void SetIsInitialDocument(bool aIsInitialDocument)
625 {
626 mIsInitialDocumentInWindow = aIsInitialDocument;
627 }
628
629
630 /**
631 * Get the bidi options for this document.
632 * @see nsBidiUtils.h
633 */
GetBidiOptions()634 uint32_t GetBidiOptions() const
635 {
636 return mBidiOptions;
637 }
638
639 /**
640 * Set the bidi options for this document. This just sets the bits;
641 * callers are expected to take action as needed if they want this
642 * change to actually change anything immediately.
643 * @see nsBidiUtils.h
644 */
SetBidiOptions(uint32_t aBidiOptions)645 void SetBidiOptions(uint32_t aBidiOptions)
646 {
647 mBidiOptions = aBidiOptions;
648 }
649
650 /**
651 * Get the has mixed active content loaded flag for this document.
652 */
GetHasMixedActiveContentLoaded()653 bool GetHasMixedActiveContentLoaded()
654 {
655 return mHasMixedActiveContentLoaded;
656 }
657
658 /**
659 * Set the has mixed active content loaded flag for this document.
660 */
SetHasMixedActiveContentLoaded(bool aHasMixedActiveContentLoaded)661 void SetHasMixedActiveContentLoaded(bool aHasMixedActiveContentLoaded)
662 {
663 mHasMixedActiveContentLoaded = aHasMixedActiveContentLoaded;
664 }
665
666 /**
667 * Get mixed active content blocked flag for this document.
668 */
GetHasMixedActiveContentBlocked()669 bool GetHasMixedActiveContentBlocked()
670 {
671 return mHasMixedActiveContentBlocked;
672 }
673
674 /**
675 * Set the mixed active content blocked flag for this document.
676 */
SetHasMixedActiveContentBlocked(bool aHasMixedActiveContentBlocked)677 void SetHasMixedActiveContentBlocked(bool aHasMixedActiveContentBlocked)
678 {
679 mHasMixedActiveContentBlocked = aHasMixedActiveContentBlocked;
680 }
681
682 /**
683 * Get the has mixed display content loaded flag for this document.
684 */
GetHasMixedDisplayContentLoaded()685 bool GetHasMixedDisplayContentLoaded()
686 {
687 return mHasMixedDisplayContentLoaded;
688 }
689
690 /**
691 * Set the has mixed display content loaded flag for this document.
692 */
SetHasMixedDisplayContentLoaded(bool aHasMixedDisplayContentLoaded)693 void SetHasMixedDisplayContentLoaded(bool aHasMixedDisplayContentLoaded)
694 {
695 mHasMixedDisplayContentLoaded = aHasMixedDisplayContentLoaded;
696 }
697
698 /**
699 * Get mixed display content blocked flag for this document.
700 */
GetHasMixedDisplayContentBlocked()701 bool GetHasMixedDisplayContentBlocked()
702 {
703 return mHasMixedDisplayContentBlocked;
704 }
705
706 /**
707 * Set the mixed display content blocked flag for this document.
708 */
SetHasMixedDisplayContentBlocked(bool aHasMixedDisplayContentBlocked)709 void SetHasMixedDisplayContentBlocked(bool aHasMixedDisplayContentBlocked)
710 {
711 mHasMixedDisplayContentBlocked = aHasMixedDisplayContentBlocked;
712 }
713
714 /**
715 * Set the mixed content object subrequest flag for this document.
716 */
SetHasMixedContentObjectSubrequest(bool aHasMixedContentObjectSubrequest)717 void SetHasMixedContentObjectSubrequest(bool aHasMixedContentObjectSubrequest)
718 {
719 mHasMixedContentObjectSubrequest = aHasMixedContentObjectSubrequest;
720 }
721
722 /**
723 * Set CSP flag for this document.
724 */
SetHasCSP(bool aHasCSP)725 void SetHasCSP(bool aHasCSP)
726 {
727 mHasCSP = aHasCSP;
728 }
729
730 /**
731 * Set unsafe-inline CSP flag for this document.
732 */
SetHasUnsafeInlineCSP(bool aHasUnsafeInlineCSP)733 void SetHasUnsafeInlineCSP(bool aHasUnsafeInlineCSP)
734 {
735 mHasUnsafeInlineCSP = aHasUnsafeInlineCSP;
736 }
737
738 /**
739 * Set unsafe-eval CSP flag for this document.
740 */
SetHasUnsafeEvalCSP(bool aHasUnsafeEvalCSP)741 void SetHasUnsafeEvalCSP(bool aHasUnsafeEvalCSP)
742 {
743 mHasUnsafeEvalCSP = aHasUnsafeEvalCSP;
744 }
745
746 /**
747 * Get tracking content blocked flag for this document.
748 */
GetHasTrackingContentBlocked()749 bool GetHasTrackingContentBlocked()
750 {
751 return mHasTrackingContentBlocked;
752 }
753
754 /**
755 * Set the tracking content blocked flag for this document.
756 */
SetHasTrackingContentBlocked(bool aHasTrackingContentBlocked)757 void SetHasTrackingContentBlocked(bool aHasTrackingContentBlocked)
758 {
759 mHasTrackingContentBlocked = aHasTrackingContentBlocked;
760 }
761
762 /**
763 * Get tracking content loaded flag for this document.
764 */
GetHasTrackingContentLoaded()765 bool GetHasTrackingContentLoaded()
766 {
767 return mHasTrackingContentLoaded;
768 }
769
770 /**
771 * Set the tracking content loaded flag for this document.
772 */
SetHasTrackingContentLoaded(bool aHasTrackingContentLoaded)773 void SetHasTrackingContentLoaded(bool aHasTrackingContentLoaded)
774 {
775 mHasTrackingContentLoaded = aHasTrackingContentLoaded;
776 }
777
778 /**
779 * Get the sandbox flags for this document.
780 * @see nsSandboxFlags.h for the possible flags
781 */
GetSandboxFlags()782 uint32_t GetSandboxFlags() const
783 {
784 return mSandboxFlags;
785 }
786
787 /**
788 * Get string representation of sandbox flags (null if no flags are set)
789 */
790 void GetSandboxFlagsAsString(nsAString& aFlags);
791
792 /**
793 * Set the sandbox flags for this document.
794 * @see nsSandboxFlags.h for the possible flags
795 */
SetSandboxFlags(uint32_t sandboxFlags)796 void SetSandboxFlags(uint32_t sandboxFlags)
797 {
798 mSandboxFlags = sandboxFlags;
799 }
800
801 /**
802 * Access HTTP header data (this may also get set from other
803 * sources, like HTML META tags).
804 */
805 virtual void GetHeaderData(nsIAtom* aHeaderField, nsAString& aData) const = 0;
806 virtual void SetHeaderData(nsIAtom* aheaderField, const nsAString& aData) = 0;
807
808 /**
809 * Create a new presentation shell that will use aContext for its
810 * presentation context (presentation contexts <b>must not</b> be
811 * shared among multiple presentation shells). The caller of this
812 * method is responsible for calling BeginObservingDocument() on the
813 * presshell if the presshell should observe document mutations.
814 */
815 virtual already_AddRefed<nsIPresShell> CreateShell(
816 nsPresContext* aContext,
817 nsViewManager* aViewManager,
818 mozilla::StyleSetHandle aStyleSet) = 0;
819 virtual void DeleteShell() = 0;
820
GetShell()821 nsIPresShell* GetShell() const
822 {
823 return GetBFCacheEntry() ? nullptr : mPresShell;
824 }
825
826 // Instead using this method, what you probably want is
827 // RemoveFromBFCacheSync() as we do in MessagePort and BroadcastChannel.
DisallowBFCaching()828 void DisallowBFCaching()
829 {
830 NS_ASSERTION(!mBFCacheEntry, "We're already in the bfcache!");
831 mBFCacheDisallowed = true;
832 }
833
IsBFCachingAllowed()834 bool IsBFCachingAllowed() const
835 {
836 return !mBFCacheDisallowed;
837 }
838
SetBFCacheEntry(nsIBFCacheEntry * aEntry)839 void SetBFCacheEntry(nsIBFCacheEntry* aEntry)
840 {
841 NS_ASSERTION(IsBFCachingAllowed() || !aEntry,
842 "You should have checked!");
843
844 mBFCacheEntry = aEntry;
845 }
846
GetBFCacheEntry()847 nsIBFCacheEntry* GetBFCacheEntry() const
848 {
849 return mBFCacheEntry;
850 }
851
852 /**
853 * Return the parent document of this document. Will return null
854 * unless this document is within a compound document and has a
855 * parent. Note that this parent chain may cross chrome boundaries.
856 */
GetParentDocument()857 nsIDocument *GetParentDocument() const
858 {
859 return mParentDocument;
860 }
861
862 /**
863 * Set the parent document of this document.
864 */
SetParentDocument(nsIDocument * aParent)865 void SetParentDocument(nsIDocument* aParent)
866 {
867 mParentDocument = aParent;
868 }
869
870 /**
871 * Are plugins allowed in this document ?
872 */
873 virtual nsresult GetAllowPlugins (bool* aAllowPlugins) = 0;
874
875 /**
876 * Set the sub document for aContent to aSubDoc.
877 */
878 virtual nsresult SetSubDocumentFor(Element* aContent,
879 nsIDocument* aSubDoc) = 0;
880
881 /**
882 * Get the sub document for aContent
883 */
884 virtual nsIDocument *GetSubDocumentFor(nsIContent *aContent) const = 0;
885
886 /**
887 * Find the content node for which aDocument is a sub document.
888 */
889 virtual Element* FindContentForSubDocument(nsIDocument* aDocument) const = 0;
890
891 /**
892 * Return the doctype for this document.
893 */
894 mozilla::dom::DocumentType* GetDoctype() const;
895
896 /**
897 * Return the root element for this document.
898 */
899 Element* GetRootElement() const;
900
901 /**
902 * Retrieve information about the viewport as a data structure.
903 * This will return information in the viewport META data section
904 * of the document. This can be used in lieu of ProcessViewportInfo(),
905 * which places the viewport information in the document header instead
906 * of returning it directly.
907 *
908 * @param aDisplaySize size of the on-screen display area for this
909 * document, in device pixels.
910 *
911 * NOTE: If the site is optimized for mobile (via the doctype), this
912 * will return viewport information that specifies default information.
913 */
914 virtual nsViewportInfo GetViewportInfo(const mozilla::ScreenIntSize& aDisplaySize) = 0;
915
916 /**
917 * True iff this doc will ignore manual character encoding overrides.
918 */
WillIgnoreCharsetOverride()919 virtual bool WillIgnoreCharsetOverride() {
920 return true;
921 }
922
923 /**
924 * Return whether the document was created by a srcdoc iframe.
925 */
IsSrcdocDocument()926 bool IsSrcdocDocument() const {
927 return mIsSrcdocDocument;
928 }
929
930 /**
931 * Sets whether the document was created by a srcdoc iframe.
932 */
SetIsSrcdocDocument(bool aIsSrcdocDocument)933 void SetIsSrcdocDocument(bool aIsSrcdocDocument) {
934 mIsSrcdocDocument = aIsSrcdocDocument;
935 }
936
937 /*
938 * Gets the srcdoc string from within the channel (assuming both exist).
939 * Returns a void string if this isn't a srcdoc document or if
940 * the channel has not been set.
941 */
942 nsresult GetSrcdocData(nsAString& aSrcdocData);
943
DidDocumentOpen()944 bool DidDocumentOpen() {
945 return mDidDocumentOpen;
946 }
947
948 already_AddRefed<mozilla::dom::AnonymousContent>
949 InsertAnonymousContent(mozilla::dom::Element& aElement,
950 mozilla::ErrorResult& aError);
951 void RemoveAnonymousContent(mozilla::dom::AnonymousContent& aContent,
952 mozilla::ErrorResult& aError);
953 /**
954 * If aNode is a descendant of anonymous content inserted by
955 * InsertAnonymousContent, this method returns the root element of the
956 * inserted anonymous content (in other words, the clone of the aElement
957 * that was passed to InsertAnonymousContent).
958 */
959 Element* GetAnonRootIfInAnonymousContentContainer(nsINode* aNode) const;
GetAnonymousContents()960 nsTArray<RefPtr<mozilla::dom::AnonymousContent>>& GetAnonymousContents() {
961 return mAnonymousContents;
962 }
963
964 static nsresult GenerateDocumentId(nsAString& aId);
965 nsresult GetOrCreateId(nsAString& aId);
966 void SetId(const nsAString& aId);
967
GetPageUnloadingEventTimeStamp()968 mozilla::TimeStamp GetPageUnloadingEventTimeStamp() const
969 {
970 if (!mParentDocument) {
971 return mPageUnloadingEventTimeStamp;
972 }
973
974 mozilla::TimeStamp parentTimeStamp(mParentDocument->GetPageUnloadingEventTimeStamp());
975 if (parentTimeStamp.IsNull()) {
976 return mPageUnloadingEventTimeStamp;
977 }
978
979 if (!mPageUnloadingEventTimeStamp ||
980 parentTimeStamp < mPageUnloadingEventTimeStamp) {
981 return parentTimeStamp;
982 }
983
984 return mPageUnloadingEventTimeStamp;
985 }
986
987 virtual void NotifyLayerManagerRecreated() = 0;
988
989 protected:
990 virtual Element *GetRootElementInternal() const = 0;
991
SetPageUnloadingEventTimeStamp()992 void SetPageUnloadingEventTimeStamp()
993 {
994 MOZ_ASSERT(!mPageUnloadingEventTimeStamp);
995 mPageUnloadingEventTimeStamp = mozilla::TimeStamp::NowLoRes();
996 }
997
CleanUnloadEventsTimeStamp()998 void CleanUnloadEventsTimeStamp()
999 {
1000 MOZ_ASSERT(mPageUnloadingEventTimeStamp);
1001 mPageUnloadingEventTimeStamp = mozilla::TimeStamp();
1002 }
1003
1004 private:
1005 class SelectorCacheKey
1006 {
1007 public:
SelectorCacheKey(const nsAString & aString)1008 explicit SelectorCacheKey(const nsAString& aString) : mKey(aString)
1009 {
1010 MOZ_COUNT_CTOR(SelectorCacheKey);
1011 }
1012
1013 nsString mKey;
1014 nsExpirationState mState;
1015
GetExpirationState()1016 nsExpirationState* GetExpirationState() { return &mState; }
1017
~SelectorCacheKey()1018 ~SelectorCacheKey()
1019 {
1020 MOZ_COUNT_DTOR(SelectorCacheKey);
1021 }
1022 };
1023
1024 class SelectorCacheKeyDeleter;
1025
1026 public:
1027 class SelectorCache final
1028 : public nsExpirationTracker<SelectorCacheKey, 4>
1029 {
1030 public:
1031 SelectorCache();
1032
1033 // CacheList takes ownership of aSelectorList.
1034 void CacheList(const nsAString& aSelector, nsCSSSelectorList* aSelectorList);
1035
1036 virtual void NotifyExpired(SelectorCacheKey* aSelector) override;
1037
1038 // We do not call MarkUsed because it would just slow down lookups and
1039 // because we're OK expiring things after a few seconds even if they're
1040 // being used. Returns whether we actually had an entry for aSelector.
1041 // If we have an entry and *aList is null, that indicates that aSelector
1042 // has already been parsed and is not a syntactically valid selector.
GetList(const nsAString & aSelector,nsCSSSelectorList ** aList)1043 bool GetList(const nsAString& aSelector, nsCSSSelectorList** aList)
1044 {
1045 return mTable.Get(aSelector, aList);
1046 }
1047
~SelectorCache()1048 ~SelectorCache()
1049 {
1050 AgeAllGenerations();
1051 }
1052
1053 private:
1054 nsClassHashtable<nsStringHashKey, nsCSSSelectorList> mTable;
1055 };
1056
GetSelectorCache()1057 SelectorCache& GetSelectorCache()
1058 {
1059 return mSelectorCache;
1060 }
1061 // Get the root <html> element, or return null if there isn't one (e.g.
1062 // if the root isn't <html>)
1063 Element* GetHtmlElement() const;
1064 // Returns the first child of GetHtmlContent which has the given tag,
1065 // or nullptr if that doesn't exist.
1066 Element* GetHtmlChildElement(nsIAtom* aTag);
1067 // Get the canonical <body> element, or return null if there isn't one (e.g.
1068 // if the root isn't <html> or if the <body> isn't there)
1069 mozilla::dom::HTMLBodyElement* GetBodyElement();
1070 // Get the canonical <head> element, or return null if there isn't one (e.g.
1071 // if the root isn't <html> or if the <head> isn't there)
GetHeadElement()1072 Element* GetHeadElement() {
1073 return GetHtmlChildElement(nsGkAtoms::head);
1074 }
1075
1076 /**
1077 * Accessors to the collection of stylesheets owned by this document.
1078 * Style sheets are ordered, most significant last.
1079 */
1080
1081 /**
1082 * These exists to allow us to on-demand load user-agent style sheets that
1083 * would otherwise be loaded by nsDocumentViewer::CreateStyleSet. This allows
1084 * us to keep the memory used by a document's rule cascade data (the stuff in
1085 * its nsStyleSet's nsCSSRuleProcessors) - which can be considerable - lower
1086 * than it would be if we loaded all built-in user-agent style sheets up
1087 * front.
1088 *
1089 * By "built-in" user-agent style sheets we mean the user-agent style sheets
1090 * that gecko itself supplies (such as html.css and svg.css) as opposed to
1091 * user-agent level style sheets inserted by add-ons or the like.
1092 *
1093 * This function prepends the given style sheet to the document's style set
1094 * in order to make sure that it does not override user-agent style sheets
1095 * supplied by add-ons or by the app (Firefox OS or Firefox Mobile, for
1096 * example), since their sheets should override built-in sheets.
1097 *
1098 * TODO We can get rid of the whole concept of delayed loading if we fix
1099 * bug 77999.
1100 */
1101 virtual void EnsureOnDemandBuiltInUASheet(mozilla::StyleSheet* aSheet) = 0;
1102
1103 /**
1104 * Get the number of (document) stylesheets
1105 *
1106 * @return the number of stylesheets
1107 * @throws no exceptions
1108 */
1109 virtual int32_t GetNumberOfStyleSheets() const = 0;
1110
1111 /**
1112 * Get a particular stylesheet
1113 * @param aIndex the index the stylesheet lives at. This is zero-based
1114 * @return the stylesheet at aIndex. Null if aIndex is out of range.
1115 * @throws no exceptions
1116 */
1117 virtual mozilla::StyleSheet* GetStyleSheetAt(int32_t aIndex) const = 0;
1118
1119 /**
1120 * Insert a sheet at a particular spot in the stylesheet list (zero-based)
1121 * @param aSheet the sheet to insert
1122 * @param aIndex the index to insert at. This index will be
1123 * adjusted for the "special" sheets.
1124 * @throws no exceptions
1125 */
1126 virtual void InsertStyleSheetAt(mozilla::StyleSheet* aSheet,
1127 int32_t aIndex) = 0;
1128
1129 /**
1130 * Get the index of a particular stylesheet. This will _always_
1131 * consider the "special" sheets as part of the sheet list.
1132 * @param aSheet the sheet to get the index of
1133 * @return aIndex the index of the sheet in the full list
1134 */
1135 virtual int32_t GetIndexOfStyleSheet(
1136 const mozilla::StyleSheet* aSheet) const = 0;
1137
1138 /**
1139 * Replace the stylesheets in aOldSheets with the stylesheets in
1140 * aNewSheets. The two lists must have equal length, and the sheet
1141 * at positon J in the first list will be replaced by the sheet at
1142 * position J in the second list. Some sheets in the second list
1143 * may be null; if so the corresponding sheets in the first list
1144 * will simply be removed.
1145 */
1146 virtual void UpdateStyleSheets(
1147 nsTArray<RefPtr<mozilla::StyleSheet>>& aOldSheets,
1148 nsTArray<RefPtr<mozilla::StyleSheet>>& aNewSheets) = 0;
1149
1150 /**
1151 * Add a stylesheet to the document
1152 */
1153 virtual void AddStyleSheet(mozilla::StyleSheet* aSheet) = 0;
1154
1155 /**
1156 * Remove a stylesheet from the document
1157 */
1158 virtual void RemoveStyleSheet(mozilla::StyleSheet* aSheet) = 0;
1159
1160 /**
1161 * Notify the document that the applicable state of the sheet changed
1162 * and that observers should be notified and style sets updated
1163 */
1164 virtual void SetStyleSheetApplicableState(mozilla::StyleSheet* aSheet,
1165 bool aApplicable) = 0;
1166
1167 enum additionalSheetType {
1168 eAgentSheet,
1169 eUserSheet,
1170 eAuthorSheet,
1171 AdditionalSheetTypeCount
1172 };
1173
1174 virtual nsresult LoadAdditionalStyleSheet(additionalSheetType aType,
1175 nsIURI* aSheetURI) = 0;
1176 virtual nsresult AddAdditionalStyleSheet(additionalSheetType aType,
1177 mozilla::StyleSheet* aSheet) = 0;
1178 virtual void RemoveAdditionalStyleSheet(additionalSheetType aType,
1179 nsIURI* sheetURI) = 0;
1180 virtual mozilla::StyleSheet* GetFirstAdditionalAuthorSheet() = 0;
1181
1182 /**
1183 * Assuming that aDocSheets is an array of document-level style
1184 * sheets for this document, returns the index that aSheet should
1185 * be inserted at to maintain document ordering.
1186 *
1187 * Defined in nsIDocumentInlines.h.
1188 */
1189 template<typename T>
1190 size_t FindDocStyleSheetInsertionPoint(const nsTArray<RefPtr<T>>& aDocSheets,
1191 T* aSheet);
1192
1193 /**
1194 * Get this document's CSSLoader. This is guaranteed to not return null.
1195 */
CSSLoader()1196 mozilla::css::Loader* CSSLoader() const {
1197 return mCSSLoader;
1198 }
1199
GetStyleBackendType()1200 mozilla::StyleBackendType GetStyleBackendType() const {
1201 if (mStyleBackendType == mozilla::StyleBackendType(0)) {
1202 const_cast<nsIDocument*>(this)->UpdateStyleBackendType();
1203 }
1204 MOZ_ASSERT(mStyleBackendType != mozilla::StyleBackendType(0));
1205 return mStyleBackendType;
1206 }
1207
1208 void UpdateStyleBackendType();
1209
IsStyledByServo()1210 bool IsStyledByServo() const {
1211 return GetStyleBackendType() == mozilla::StyleBackendType::Servo;
1212 }
1213
1214 /**
1215 * Get this document's StyleImageLoader. This is guaranteed to not return null.
1216 */
StyleImageLoader()1217 mozilla::css::ImageLoader* StyleImageLoader() const {
1218 return mStyleImageLoader;
1219 }
1220
1221 /**
1222 * Get the channel that was passed to StartDocumentLoad or Reset for this
1223 * document. Note that this may be null in some cases (eg if
1224 * StartDocumentLoad or Reset were never called)
1225 */
1226 virtual nsIChannel* GetChannel() const = 0;
1227
1228 /**
1229 * Get this document's attribute stylesheet. May return null if
1230 * there isn't one.
1231 */
GetAttributeStyleSheet()1232 nsHTMLStyleSheet* GetAttributeStyleSheet() const {
1233 return mAttrStyleSheet;
1234 }
1235
1236 /**
1237 * Get this document's inline style sheet. May return null if there
1238 * isn't one
1239 */
GetInlineStyleSheet()1240 nsHTMLCSSStyleSheet* GetInlineStyleSheet() const {
1241 return mStyleAttrStyleSheet;
1242 }
1243
1244 /**
1245 * Get this document's SVG Animation rule processor. May return null
1246 * if there isn't one.
1247 */
1248 mozilla::SVGAttrAnimationRuleProcessor*
GetSVGAttrAnimationRuleProcessor()1249 GetSVGAttrAnimationRuleProcessor() const
1250 {
1251 return mSVGAttrAnimationRuleProcessor;
1252 }
1253
1254 virtual void SetScriptGlobalObject(nsIScriptGlobalObject* aGlobalObject) = 0;
1255
1256 /**
1257 * Get/set the object from which the context for the event/script handling can
1258 * be got. Normally GetScriptHandlingObject() returns the same object as
1259 * GetScriptGlobalObject(), but if the document is loaded as data,
1260 * non-null may be returned, even if GetScriptGlobalObject() returns null.
1261 * aHasHadScriptHandlingObject is set true if document has had the object
1262 * for event/script handling. Do not process any events/script if the method
1263 * returns null, but aHasHadScriptHandlingObject is true.
1264 */
1265 nsIScriptGlobalObject*
GetScriptHandlingObject(bool & aHasHadScriptHandlingObject)1266 GetScriptHandlingObject(bool& aHasHadScriptHandlingObject) const
1267 {
1268 aHasHadScriptHandlingObject = mHasHadScriptHandlingObject;
1269 return mScriptGlobalObject ? mScriptGlobalObject.get() :
1270 GetScriptHandlingObjectInternal();
1271 }
1272 virtual void SetScriptHandlingObject(nsIScriptGlobalObject* aScriptObject) = 0;
1273
1274 /**
1275 * Get the object that is used as the scope for all of the content
1276 * wrappers whose owner document is this document. Unlike the script global
1277 * object, this will only return null when the global object for this
1278 * document is truly gone. Use this object when you're trying to find a
1279 * content wrapper in XPConnect.
1280 */
1281 virtual nsIGlobalObject* GetScopeObject() const = 0;
1282 virtual void SetScopeObject(nsIGlobalObject* aGlobal) = 0;
1283
1284 /**
1285 * Return the window containing the document (the outer window).
1286 */
GetWindow()1287 nsPIDOMWindowOuter *GetWindow() const
1288 {
1289 return mWindow ? mWindow->GetOuterWindow() : GetWindowInternal();
1290 }
1291
IsInBackgroundWindow()1292 bool IsInBackgroundWindow() const
1293 {
1294 auto* outer = mWindow ? mWindow->GetOuterWindow() : nullptr;
1295 return outer && outer->IsBackground();
1296 }
1297
1298 /**
1299 * Return the inner window used as the script compilation scope for
1300 * this document. If you're not absolutely sure you need this, use
1301 * GetWindow().
1302 */
GetInnerWindow()1303 nsPIDOMWindowInner* GetInnerWindow() const
1304 {
1305 return mRemovedFromDocShell ? nullptr : mWindow;
1306 }
1307
1308 /**
1309 * Return the outer window ID.
1310 */
OuterWindowID()1311 uint64_t OuterWindowID() const
1312 {
1313 nsPIDOMWindowOuter* window = GetWindow();
1314 return window ? window->WindowID() : 0;
1315 }
1316
1317 /**
1318 * Return the inner window ID.
1319 */
InnerWindowID()1320 uint64_t InnerWindowID() const
1321 {
1322 nsPIDOMWindowInner* window = GetInnerWindow();
1323 return window ? window->WindowID() : 0;
1324 }
1325
1326 /**
1327 * Get the script loader for this document
1328 */
1329 virtual nsScriptLoader* ScriptLoader() = 0;
1330
1331 /**
1332 * Add/Remove an element to the document's id and name hashes
1333 */
1334 virtual void AddToIdTable(Element* aElement, nsIAtom* aId) = 0;
1335 virtual void RemoveFromIdTable(Element* aElement, nsIAtom* aId) = 0;
1336 virtual void AddToNameTable(Element* aElement, nsIAtom* aName) = 0;
1337 virtual void RemoveFromNameTable(Element* aElement, nsIAtom* aName) = 0;
1338
1339 /**
1340 * Returns all elements in the fullscreen stack in the insertion order.
1341 */
1342 virtual nsTArray<Element*> GetFullscreenStack() const = 0;
1343
1344 /**
1345 * Asynchronously requests that the document make aElement the fullscreen
1346 * element, and move into fullscreen mode. The current fullscreen element
1347 * (if any) is pushed onto the fullscreen element stack, and it can be
1348 * returned to fullscreen status by calling RestorePreviousFullScreenState().
1349 *
1350 * Note that requesting fullscreen in a document also makes the element which
1351 * contains this document in this document's parent document fullscreen. i.e.
1352 * the <iframe> or <browser> that contains this document is also mode
1353 * fullscreen. This happens recursively in all ancestor documents.
1354 */
1355 virtual void AsyncRequestFullScreen(
1356 mozilla::UniquePtr<FullscreenRequest>&& aRequest) = 0;
1357
1358 /**
1359 * Called when a frame in a child process has entered fullscreen or when a
1360 * fullscreen frame in a child process changes to another origin.
1361 * aFrameElement is the frame element which contains the child-process
1362 * fullscreen document.
1363 */
1364 virtual nsresult
1365 RemoteFrameFullscreenChanged(nsIDOMElement* aFrameElement) = 0;
1366
1367 /**
1368 * Called when a frame in a remote child document has rolled back fullscreen
1369 * so that all its fullscreen element stacks are empty; we must continue the
1370 * rollback in this parent process' doc tree branch which is fullscreen.
1371 * Note that only one branch of the document tree can have its documents in
1372 * fullscreen state at one time. We're in inconsistent state if a
1373 * fullscreen document has a parent and that parent isn't fullscreen. We
1374 * preserve this property across process boundaries.
1375 */
1376 virtual nsresult RemoteFrameFullscreenReverted() = 0;
1377
1378 /**
1379 * Restores the previous full-screen element to full-screen status. If there
1380 * is no former full-screen element, this exits full-screen, moving the
1381 * top-level browser window out of full-screen mode.
1382 */
1383 virtual void RestorePreviousFullScreenState() = 0;
1384
1385 /**
1386 * Returns true if this document is a fullscreen leaf document, i.e. it
1387 * is in fullscreen mode and has no fullscreen children.
1388 */
1389 virtual bool IsFullscreenLeaf() = 0;
1390
1391 /**
1392 * Returns the document which is at the root of this document's branch
1393 * in the in-process document tree. Returns nullptr if the document isn't
1394 * fullscreen.
1395 */
1396 virtual nsIDocument* GetFullscreenRoot() = 0;
1397
1398 /**
1399 * Sets the fullscreen root to aRoot. This stores a weak reference to aRoot
1400 * in this document.
1401 */
1402 virtual void SetFullscreenRoot(nsIDocument* aRoot) = 0;
1403
1404 /**
1405 * Synchronously cleans up the fullscreen state on the given document.
1406 *
1407 * Calling this without performing fullscreen transition could lead
1408 * to undesired effect (the transition happens after document state
1409 * flips), hence it should only be called either by nsGlobalWindow
1410 * when we have performed the transition, or when it is necessary to
1411 * clean up the state immediately. Otherwise, AsyncExitFullscreen()
1412 * should be called instead.
1413 *
1414 * aDocument must not be null.
1415 */
1416 static void ExitFullscreenInDocTree(nsIDocument* aDocument);
1417
1418 /**
1419 * Ask the document to exit fullscreen state asynchronously.
1420 *
1421 * Different from ExitFullscreenInDocTree(), this allows the window
1422 * to perform fullscreen transition first if any.
1423 *
1424 * If aDocument is null, it will exit fullscreen from all documents
1425 * in all windows.
1426 */
1427 static void AsyncExitFullscreen(nsIDocument* aDocument);
1428
1429 /**
1430 * Handles any pending fullscreen in aDocument or its subdocuments.
1431 *
1432 * Returns whether there is any fullscreen request handled.
1433 */
1434 static bool HandlePendingFullscreenRequests(nsIDocument* aDocument);
1435
1436 /**
1437 * Dispatch fullscreenerror event and report the failure message to
1438 * the console.
1439 */
1440 void DispatchFullscreenError(const char* aMessage);
1441
1442 virtual void RequestPointerLock(Element* aElement) = 0;
1443
1444 static void UnlockPointer(nsIDocument* aDoc = nullptr);
1445
1446 // ScreenOrientation related APIs
1447
1448 virtual void SetCurrentOrientation(mozilla::dom::OrientationType aType,
1449 uint16_t aAngle) = 0;
1450 virtual uint16_t CurrentOrientationAngle() const = 0;
1451 virtual mozilla::dom::OrientationType CurrentOrientationType() const = 0;
1452 virtual void SetOrientationPendingPromise(mozilla::dom::Promise* aPromise) = 0;
1453 virtual mozilla::dom::Promise* GetOrientationPendingPromise() const = 0;
1454
1455 //----------------------------------------------------------------------
1456
1457 // Document notification API's
1458
1459 /**
1460 * Add a new observer of document change notifications. Whenever
1461 * content is changed, appended, inserted or removed the observers are
1462 * informed. An observer that is already observing the document must
1463 * not be added without being removed first.
1464 */
1465 virtual void AddObserver(nsIDocumentObserver* aObserver) = 0;
1466
1467 /**
1468 * Remove an observer of document change notifications. This will
1469 * return false if the observer cannot be found.
1470 */
1471 virtual bool RemoveObserver(nsIDocumentObserver* aObserver) = 0;
1472
1473 // Observation hooks used to propagate notifications to document observers.
1474 // BeginUpdate must be called before any batch of modifications of the
1475 // content model or of style data, EndUpdate must be called afterward.
1476 // To make this easy and painless, use the mozAutoDocUpdate helper class.
1477 virtual void BeginUpdate(nsUpdateType aUpdateType) = 0;
1478 virtual void EndUpdate(nsUpdateType aUpdateType) = 0;
1479 virtual void BeginLoad() = 0;
1480 virtual void EndLoad() = 0;
1481
1482 enum ReadyState { READYSTATE_UNINITIALIZED = 0, READYSTATE_LOADING = 1, READYSTATE_INTERACTIVE = 3, READYSTATE_COMPLETE = 4};
1483 virtual void SetReadyStateInternal(ReadyState rs) = 0;
GetReadyStateEnum()1484 ReadyState GetReadyStateEnum()
1485 {
1486 return mReadyState;
1487 }
1488
1489 // notify that a content node changed state. This must happen under
1490 // a scriptblocker but NOT within a begin/end update.
1491 virtual void ContentStateChanged(nsIContent* aContent,
1492 mozilla::EventStates aStateMask) = 0;
1493
1494 // Notify that a document state has changed.
1495 // This should only be called by callers whose state is also reflected in the
1496 // implementation of nsDocument::GetDocumentState.
1497 virtual void DocumentStatesChanged(mozilla::EventStates aStateMask) = 0;
1498
1499 // Observation hooks for style data to propagate notifications
1500 // to document observers
1501 virtual void StyleRuleChanged(mozilla::StyleSheet* aStyleSheet,
1502 mozilla::css::Rule* aStyleRule) = 0;
1503 virtual void StyleRuleAdded(mozilla::StyleSheet* aStyleSheet,
1504 mozilla::css::Rule* aStyleRule) = 0;
1505 virtual void StyleRuleRemoved(mozilla::StyleSheet* aStyleSheet,
1506 mozilla::css::Rule* aStyleRule) = 0;
1507
1508 /**
1509 * Flush notifications for this document and its parent documents
1510 * (since those may affect the layout of this one).
1511 */
1512 virtual void FlushPendingNotifications(mozFlushType aType) = 0;
1513
1514 /**
1515 * Calls FlushPendingNotifications on any external resources this document
1516 * has. If this document has no external resources or is an external resource
1517 * itself this does nothing. This should only be called with
1518 * aType >= Flush_Style.
1519 */
1520 virtual void FlushExternalResources(mozFlushType aType) = 0;
1521
BindingManager()1522 nsBindingManager* BindingManager() const
1523 {
1524 return mNodeInfoManager->GetBindingManager();
1525 }
1526
1527 /**
1528 * Only to be used inside Gecko, you can't really do anything with the
1529 * pointer outside Gecko anyway.
1530 */
NodeInfoManager()1531 nsNodeInfoManager* NodeInfoManager() const
1532 {
1533 return mNodeInfoManager;
1534 }
1535
1536 /**
1537 * Reset the document using the given channel and loadgroup. This works
1538 * like ResetToURI, but also sets the document's channel to aChannel.
1539 * The principal of the document will be set from the channel.
1540 */
1541 virtual void Reset(nsIChannel* aChannel, nsILoadGroup* aLoadGroup) = 0;
1542
1543 /**
1544 * Reset this document to aURI, aLoadGroup, and aPrincipal. aURI must not be
1545 * null. If aPrincipal is null, a codebase principal based on aURI will be
1546 * used.
1547 */
1548 virtual void ResetToURI(nsIURI *aURI, nsILoadGroup* aLoadGroup,
1549 nsIPrincipal* aPrincipal) = 0;
1550
1551 /**
1552 * Set the container (docshell) for this document. Virtual so that
1553 * docshell can call it.
1554 */
1555 virtual void SetContainer(nsDocShell* aContainer);
1556
1557 /**
1558 * Get the container (docshell) for this document.
1559 */
1560 virtual nsISupports* GetContainer() const;
1561
1562 /**
1563 * Get the container's load context for this document.
1564 */
1565 nsILoadContext* GetLoadContext() const;
1566
1567 /**
1568 * Get docshell the for this document.
1569 */
1570 nsIDocShell* GetDocShell() const;
1571
1572 /**
1573 * Set and get XML declaration. If aVersion is null there is no declaration.
1574 * aStandalone takes values -1, 0 and 1 indicating respectively that there
1575 * was no standalone parameter in the declaration, that it was given as no,
1576 * or that it was given as yes.
1577 */
1578 virtual void SetXMLDeclaration(const char16_t *aVersion,
1579 const char16_t *aEncoding,
1580 const int32_t aStandalone) = 0;
1581 virtual void GetXMLDeclaration(nsAString& aVersion,
1582 nsAString& aEncoding,
1583 nsAString& Standalone) = 0;
1584
1585 /**
1586 * Returns true if this is what HTML 5 calls an "HTML document" (for example
1587 * regular HTML document with Content-Type "text/html", image documents and
1588 * media documents). Returns false for XHTML and any other documents parsed
1589 * by the XML parser.
1590 */
IsHTMLDocument()1591 bool IsHTMLDocument() const
1592 {
1593 return mType == eHTML;
1594 }
IsHTMLOrXHTML()1595 bool IsHTMLOrXHTML() const
1596 {
1597 return mType == eHTML || mType == eXHTML;
1598 }
IsXMLDocument()1599 bool IsXMLDocument() const
1600 {
1601 return !IsHTMLDocument();
1602 }
IsSVGDocument()1603 bool IsSVGDocument() const
1604 {
1605 return mType == eSVG;
1606 }
IsXULDocument()1607 bool IsXULDocument() const
1608 {
1609 return mType == eXUL;
1610 }
IsUnstyledDocument()1611 bool IsUnstyledDocument()
1612 {
1613 return IsLoadedAsData() || IsLoadedAsInteractiveData();
1614 }
LoadsFullXULStyleSheetUpFront()1615 bool LoadsFullXULStyleSheetUpFront()
1616 {
1617 return IsXULDocument() || AllowXULXBL();
1618 }
1619
1620 virtual bool IsScriptEnabled() = 0;
1621
1622 /**
1623 * Create an element with the specified name, prefix and namespace ID.
1624 * Returns null if element name parsing failed.
1625 */
1626 virtual already_AddRefed<Element> CreateElem(const nsAString& aName,
1627 nsIAtom* aPrefix,
1628 int32_t aNamespaceID,
1629 const nsAString* aIs = nullptr) = 0;
1630
1631 /**
1632 * Get the security info (i.e. SSL state etc) that the document got
1633 * from the channel/document that created the content of the
1634 * document.
1635 *
1636 * @see nsIChannel
1637 */
GetSecurityInfo()1638 nsISupports *GetSecurityInfo()
1639 {
1640 return mSecurityInfo;
1641 }
1642
1643 /**
1644 * Get the channel that failed to load and resulted in an error page, if it
1645 * exists. This is only relevant to error pages.
1646 */
1647 virtual nsIChannel* GetFailedChannel() const = 0;
1648
1649 /**
1650 * Set the channel that failed to load and resulted in an error page.
1651 * This is only relevant to error pages.
1652 */
1653 virtual void SetFailedChannel(nsIChannel* aChannel) = 0;
1654
1655 /**
1656 * Returns the default namespace ID used for elements created in this
1657 * document.
1658 */
GetDefaultNamespaceID()1659 int32_t GetDefaultNamespaceID() const
1660 {
1661 return mDefaultElementType;
1662 }
1663
1664 void DeleteAllProperties();
1665 void DeleteAllPropertiesFor(nsINode* aNode);
1666
PropertyTable(uint16_t aCategory)1667 nsPropertyTable* PropertyTable(uint16_t aCategory) {
1668 if (aCategory == 0)
1669 return &mPropertyTable;
1670 return GetExtraPropertyTable(aCategory);
1671 }
GetPropertyTableCount()1672 uint32_t GetPropertyTableCount()
1673 { return mExtraPropertyTables.Length() + 1; }
1674
1675 /**
1676 * Sets the ID used to identify this part of the multipart document
1677 */
SetPartID(uint32_t aID)1678 void SetPartID(uint32_t aID) {
1679 mPartID = aID;
1680 }
1681
1682 /**
1683 * Return the ID used to identify this part of the multipart document
1684 */
GetPartID()1685 uint32_t GetPartID() const {
1686 return mPartID;
1687 }
1688
1689 /**
1690 * Sanitize the document by resetting all input elements and forms that have
1691 * autocomplete=off to their default values.
1692 */
1693 virtual void Sanitize() = 0;
1694
1695 /**
1696 * Enumerate all subdocuments.
1697 * The enumerator callback should return true to continue enumerating, or
1698 * false to stop. This will never get passed a null aDocument.
1699 */
1700 typedef bool (*nsSubDocEnumFunc)(nsIDocument *aDocument, void *aData);
1701 virtual void EnumerateSubDocuments(nsSubDocEnumFunc aCallback,
1702 void *aData) = 0;
1703
1704 /**
1705 * Check whether it is safe to cache the presentation of this document
1706 * and all of its subdocuments. This method checks the following conditions
1707 * recursively:
1708 * - Some document types, such as plugin documents, cannot be safely cached.
1709 * - If there are any pending requests, we don't allow the presentation
1710 * to be cached. Ideally these requests would be suspended and resumed,
1711 * but that is difficult in some cases, such as XMLHttpRequest.
1712 * - If there are any beforeunload or unload listeners, we must fire them
1713 * for correctness, but this likely puts the document into a state where
1714 * it would not function correctly if restored.
1715 *
1716 * |aNewRequest| should be the request for a new document which will
1717 * replace this document in the docshell. The new document's request
1718 * will be ignored when checking for active requests. If there is no
1719 * request associated with the new document, this parameter may be null.
1720 */
1721 virtual bool CanSavePresentation(nsIRequest *aNewRequest) = 0;
1722
1723 /**
1724 * Notify the document that its associated ContentViewer is being destroyed.
1725 * This releases circular references so that the document can go away.
1726 * Destroy() is only called on documents that have a content viewer.
1727 */
1728 virtual void Destroy() = 0;
1729
1730 /**
1731 * Notify the document that its associated ContentViewer is no longer
1732 * the current viewer for the docshell. The document might still
1733 * be rendered in "zombie state" until the next document is ready.
1734 * The document should save form control state.
1735 */
1736 virtual void RemovedFromDocShell() = 0;
1737
1738 /**
1739 * Get the layout history state that should be used to save and restore state
1740 * for nodes in this document. This may return null; if that happens state
1741 * saving and restoration is not possible.
1742 */
1743 virtual already_AddRefed<nsILayoutHistoryState> GetLayoutHistoryState() const = 0;
1744
1745 /**
1746 * Methods that can be used to prevent onload firing while an event that
1747 * should block onload is posted. onload is guaranteed to not fire until
1748 * either all calls to BlockOnload() have been matched by calls to
1749 * UnblockOnload() or the load has been stopped altogether (by the user
1750 * pressing the Stop button, say).
1751 */
1752 virtual void BlockOnload() = 0;
1753 /**
1754 * @param aFireSync whether to fire onload synchronously. If false,
1755 * onload will fire asynchronously after all onload blocks have been
1756 * removed. It will NOT fire from inside UnblockOnload. If true,
1757 * onload may fire from inside UnblockOnload.
1758 */
1759 virtual void UnblockOnload(bool aFireSync) = 0;
1760
BlockDOMContentLoaded()1761 void BlockDOMContentLoaded()
1762 {
1763 ++mBlockDOMContentLoaded;
1764 }
1765
1766 virtual void UnblockDOMContentLoaded() = 0;
1767
1768 /**
1769 * Notification that the page has been shown, for documents which are loaded
1770 * into a DOM window. This corresponds to the completion of document load,
1771 * or to the page's presentation being restored into an existing DOM window.
1772 * This notification fires applicable DOM events to the content window. See
1773 * PageTransitionEvent.webidl for a description of the |aPersisted|
1774 * parameter. If aDispatchStartTarget is null, the pageshow event is
1775 * dispatched on the ScriptGlobalObject for this document, otherwise it's
1776 * dispatched on aDispatchStartTarget.
1777 * Note: if aDispatchStartTarget isn't null, the showing state of the
1778 * document won't be altered.
1779 */
1780 virtual void OnPageShow(bool aPersisted,
1781 mozilla::dom::EventTarget* aDispatchStartTarget) = 0;
1782
1783 /**
1784 * Notification that the page has been hidden, for documents which are loaded
1785 * into a DOM window. This corresponds to the unloading of the document, or
1786 * to the document's presentation being saved but removed from an existing
1787 * DOM window. This notification fires applicable DOM events to the content
1788 * window. See PageTransitionEvent.webidl for a description of the
1789 * |aPersisted| parameter. If aDispatchStartTarget is null, the pagehide
1790 * event is dispatched on the ScriptGlobalObject for this document,
1791 * otherwise it's dispatched on aDispatchStartTarget.
1792 * Note: if aDispatchStartTarget isn't null, the showing state of the
1793 * document won't be altered.
1794 */
1795 virtual void OnPageHide(bool aPersisted,
1796 mozilla::dom::EventTarget* aDispatchStartTarget) = 0;
1797
1798 /*
1799 * We record the set of links in the document that are relevant to
1800 * style.
1801 */
1802 /**
1803 * Notification that an element is a link that is relevant to style.
1804 */
1805 virtual void AddStyleRelevantLink(mozilla::dom::Link* aLink) = 0;
1806 /**
1807 * Notification that an element is a link and its URI might have been
1808 * changed or the element removed. If the element is still a link relevant
1809 * to style, then someone must ensure that AddStyleRelevantLink is
1810 * (eventually) called on it again.
1811 */
1812 virtual void ForgetLink(mozilla::dom::Link* aLink) = 0;
1813
1814 /**
1815 * Resets and removes a box object from the document's box object cache
1816 *
1817 * @param aElement canonical nsIContent pointer of the box object's element
1818 */
1819 virtual void ClearBoxObjectFor(nsIContent *aContent) = 0;
1820
1821 /**
1822 * Get the box object for an element. This is not exposed through a
1823 * scriptable interface except for XUL documents.
1824 */
1825 virtual already_AddRefed<mozilla::dom::BoxObject>
1826 GetBoxObjectFor(mozilla::dom::Element* aElement,
1827 mozilla::ErrorResult& aRv) = 0;
1828
1829 /**
1830 * Support for window.matchMedia()
1831 */
1832
1833 already_AddRefed<mozilla::dom::MediaQueryList>
1834 MatchMedia(const nsAString& aMediaQueryList);
1835
MediaQueryLists()1836 const PRCList* MediaQueryLists() const {
1837 return &mDOMMediaQueryLists;
1838 }
1839
1840 /**
1841 * Get the compatibility mode for this document
1842 */
GetCompatibilityMode()1843 nsCompatibility GetCompatibilityMode() const {
1844 return mCompatMode;
1845 }
1846
1847 /**
1848 * Check whether we've ever fired a DOMTitleChanged event for this
1849 * document.
1850 */
HaveFiredDOMTitleChange()1851 bool HaveFiredDOMTitleChange() const {
1852 return mHaveFiredTitleChange;
1853 }
1854
1855 /**
1856 * See GetAnonymousElementByAttribute on nsIDOMDocumentXBL.
1857 */
1858 virtual Element*
1859 GetAnonymousElementByAttribute(nsIContent* aElement,
1860 nsIAtom* aAttrName,
1861 const nsAString& aAttrValue) const = 0;
1862
1863 /**
1864 * Helper for nsIDOMDocument::elementFromPoint implementation that allows
1865 * ignoring the scroll frame and/or avoiding layout flushes.
1866 *
1867 * @see nsIDOMWindowUtils::elementFromPoint
1868 */
1869 virtual Element* ElementFromPointHelper(float aX, float aY,
1870 bool aIgnoreRootScrollFrame,
1871 bool aFlushLayout) = 0;
1872
1873 enum ElementsFromPointFlags {
1874 IGNORE_ROOT_SCROLL_FRAME = 1,
1875 FLUSH_LAYOUT = 2,
1876 IS_ELEMENT_FROM_POINT = 4
1877 };
1878
1879 virtual void ElementsFromPointHelper(float aX, float aY,
1880 uint32_t aFlags,
1881 nsTArray<RefPtr<mozilla::dom::Element>>& aElements) = 0;
1882
1883 virtual nsresult NodesFromRectHelper(float aX, float aY,
1884 float aTopSize, float aRightSize,
1885 float aBottomSize, float aLeftSize,
1886 bool aIgnoreRootScrollFrame,
1887 bool aFlushLayout,
1888 nsIDOMNodeList** aReturn) = 0;
1889
1890 /**
1891 * See FlushSkinBindings on nsBindingManager
1892 */
1893 virtual void FlushSkinBindings() = 0;
1894
1895 /**
1896 * To batch DOMSubtreeModified, document needs to be informed when
1897 * a mutation event might be dispatched, even if the event isn't actually
1898 * created because there are no listeners for it.
1899 *
1900 * @param aTarget is the target for the mutation event.
1901 */
MayDispatchMutationEvent(nsINode * aTarget)1902 void MayDispatchMutationEvent(nsINode* aTarget)
1903 {
1904 if (mSubtreeModifiedDepth > 0) {
1905 mSubtreeModifiedTargets.AppendObject(aTarget);
1906 }
1907 }
1908
1909 /**
1910 * Marks as not-going-to-be-collected for the given generation of
1911 * cycle collection.
1912 */
MarkUncollectableForCCGeneration(uint32_t aGeneration)1913 void MarkUncollectableForCCGeneration(uint32_t aGeneration)
1914 {
1915 mMarkedCCGeneration = aGeneration;
1916 }
1917
1918 /**
1919 * Gets the cycle collector generation this document is marked for.
1920 */
GetMarkedCCGeneration()1921 uint32_t GetMarkedCCGeneration()
1922 {
1923 return mMarkedCCGeneration;
1924 }
1925
IsLoadedAsData()1926 bool IsLoadedAsData()
1927 {
1928 return mLoadedAsData;
1929 }
1930
IsLoadedAsInteractiveData()1931 bool IsLoadedAsInteractiveData()
1932 {
1933 return mLoadedAsInteractiveData;
1934 }
1935
MayStartLayout()1936 bool MayStartLayout()
1937 {
1938 return mMayStartLayout;
1939 }
1940
SetMayStartLayout(bool aMayStartLayout)1941 void SetMayStartLayout(bool aMayStartLayout)
1942 {
1943 mMayStartLayout = aMayStartLayout;
1944 }
1945
1946 already_AddRefed<nsIDocumentEncoder> GetCachedEncoder();
1947
1948 void SetCachedEncoder(already_AddRefed<nsIDocumentEncoder> aEncoder);
1949
1950 // In case of failure, the document really can't initialize the frame loader.
1951 virtual nsresult InitializeFrameLoader(nsFrameLoader* aLoader) = 0;
1952 // In case of failure, the caller must handle the error, for example by
1953 // finalizing frame loader asynchronously.
1954 virtual nsresult FinalizeFrameLoader(nsFrameLoader* aLoader, nsIRunnable* aFinalizer) = 0;
1955 // Removes the frame loader of aShell from the initialization list.
1956 virtual void TryCancelFrameLoaderInitialization(nsIDocShell* aShell) = 0;
1957
1958 /**
1959 * Check whether this document is a root document that is not an
1960 * external resource.
1961 */
IsRootDisplayDocument()1962 bool IsRootDisplayDocument() const
1963 {
1964 return !mParentDocument && !mDisplayDocument;
1965 }
1966
IsBeingUsedAsImage()1967 bool IsBeingUsedAsImage() const {
1968 return mIsBeingUsedAsImage;
1969 }
1970
SetIsBeingUsedAsImage()1971 void SetIsBeingUsedAsImage() {
1972 mIsBeingUsedAsImage = true;
1973 }
1974
IsResourceDoc()1975 bool IsResourceDoc() const {
1976 return IsBeingUsedAsImage() || // Are we a helper-doc for an SVG image?
1977 mHasDisplayDocument; // Are we an external resource doc?
1978 }
1979
1980 /**
1981 * Get the document for which this document is an external resource. This
1982 * will be null if this document is not an external resource. Otherwise,
1983 * GetDisplayDocument() will return a non-null document, and
1984 * GetDisplayDocument()->GetDisplayDocument() is guaranteed to be null.
1985 */
GetDisplayDocument()1986 nsIDocument* GetDisplayDocument() const
1987 {
1988 return mDisplayDocument;
1989 }
1990
1991 /**
1992 * Set the display document for this document. aDisplayDocument must not be
1993 * null.
1994 */
SetDisplayDocument(nsIDocument * aDisplayDocument)1995 void SetDisplayDocument(nsIDocument* aDisplayDocument)
1996 {
1997 MOZ_ASSERT(!GetShell() &&
1998 !GetContainer() &&
1999 !GetWindow(),
2000 "Shouldn't set mDisplayDocument on documents that already "
2001 "have a presentation or a docshell or a window");
2002 MOZ_ASSERT(aDisplayDocument, "Must not be null");
2003 MOZ_ASSERT(aDisplayDocument != this, "Should be different document");
2004 MOZ_ASSERT(!aDisplayDocument->GetDisplayDocument(),
2005 "Display documents should not nest");
2006 mDisplayDocument = aDisplayDocument;
2007 mHasDisplayDocument = !!aDisplayDocument;
2008 }
2009
2010 /**
2011 * A class that represents an external resource load that has begun but
2012 * doesn't have a document yet. Observers can be registered on this object,
2013 * and will be notified after the document is created. Observers registered
2014 * after the document has been created will NOT be notified. When observers
2015 * are notified, the subject will be the newly-created document, the topic
2016 * will be "external-resource-document-created", and the data will be null.
2017 * If document creation fails for some reason, observers will still be
2018 * notified, with a null document pointer.
2019 */
2020 class ExternalResourceLoad : public nsISupports
2021 {
2022 public:
~ExternalResourceLoad()2023 virtual ~ExternalResourceLoad() {}
2024
AddObserver(nsIObserver * aObserver)2025 void AddObserver(nsIObserver* aObserver) {
2026 MOZ_ASSERT(aObserver, "Must have observer");
2027 mObservers.AppendElement(aObserver);
2028 }
2029
Observers()2030 const nsTArray< nsCOMPtr<nsIObserver> > & Observers() {
2031 return mObservers;
2032 }
2033 protected:
2034 AutoTArray< nsCOMPtr<nsIObserver>, 8 > mObservers;
2035 };
2036
2037 /**
2038 * Request an external resource document for aURI. This will return the
2039 * resource document if available. If one is not available yet, it will
2040 * start loading as needed, and the pending load object will be returned in
2041 * aPendingLoad so that the caller can register an observer to wait for the
2042 * load. If this function returns null and doesn't return a pending load,
2043 * that means that there is no resource document for this URI and won't be
2044 * one in the future.
2045 *
2046 * @param aURI the URI to get
2047 * @param aRequestingNode the node making the request
2048 * @param aPendingLoad the pending load for this request, if any
2049 */
2050 virtual nsIDocument*
2051 RequestExternalResource(nsIURI* aURI,
2052 nsINode* aRequestingNode,
2053 ExternalResourceLoad** aPendingLoad) = 0;
2054
2055 /**
2056 * Enumerate the external resource documents associated with this document.
2057 * The enumerator callback should return true to continue enumerating, or
2058 * false to stop. This callback will never get passed a null aDocument.
2059 */
2060 virtual void EnumerateExternalResources(nsSubDocEnumFunc aCallback,
2061 void* aData) = 0;
2062
2063 /**
2064 * Return whether the document is currently showing (in the sense of
2065 * OnPageShow() having been called already and OnPageHide() not having been
2066 * called yet.
2067 */
IsShowing()2068 bool IsShowing() const { return mIsShowing; }
2069 /**
2070 * Return whether the document is currently visible (in the sense of
2071 * OnPageHide having been called and OnPageShow not yet having been called)
2072 */
IsVisible()2073 bool IsVisible() const { return mVisible; }
2074
2075 /**
2076 * Return whether the document and all its ancestors are visible in the sense of
2077 * pageshow / hide.
2078 */
2079 bool IsVisibleConsideringAncestors() const;
2080
2081 /**
2082 * Return true when this document is active, i.e., an active document
2083 * in a content viewer. Note that this will return true for bfcached
2084 * documents, so this does NOT match the "active document" concept in
2085 * the WHATWG spec - see IsCurrentActiveDocument.
2086 */
IsActive()2087 bool IsActive() const { return mDocumentContainer && !mRemovedFromDocShell; }
2088
2089 /**
2090 * Return true if this is the current active document for its
2091 * docshell. Note that a docshell may have multiple active documents
2092 * due to the bfcache -- this should be used when you need to
2093 * differentiate the *current* active document from any active
2094 * documents.
2095 */
IsCurrentActiveDocument()2096 bool IsCurrentActiveDocument() const
2097 {
2098 nsPIDOMWindowInner* inner = GetInnerWindow();
2099 return inner && inner->IsCurrentInnerWindow() && inner->GetDoc() == this;
2100 }
2101
2102 /**
2103 * Register/Unregister the ActivityObserver into mActivityObservers to listen
2104 * the document's activity changes such as OnPageHide, visibility, activity.
2105 * The ActivityObserver objects can be nsIObjectLoadingContent or
2106 * nsIDocumentActivity or HTMLMEdiaElement.
2107 */
2108 void RegisterActivityObserver(nsISupports* aSupports);
2109 bool UnregisterActivityObserver(nsISupports* aSupports);
2110 // Enumerate all the observers in mActivityObservers by the aEnumerator.
2111 typedef void (* ActivityObserverEnumerator)(nsISupports*, void*);
2112 void EnumerateActivityObservers(ActivityObserverEnumerator aEnumerator,
2113 void* aData);
2114
2115 // Indicates whether mAnimationController has been (lazily) initialized.
2116 // If this returns true, we're promising that GetAnimationController()
2117 // will have a non-null return value.
HasAnimationController()2118 bool HasAnimationController() { return !!mAnimationController; }
2119
2120 // Getter for this document's SMIL Animation Controller. Performs lazy
2121 // initialization, if this document supports animation and if
2122 // mAnimationController isn't yet initialized.
2123 virtual nsSMILAnimationController* GetAnimationController() = 0;
2124
2125 // Gets the tracker for animations that are waiting to start.
2126 // Returns nullptr if there is no pending animation tracker for this document
2127 // which will be the case if there have never been any CSS animations or
2128 // transitions on elements in the document.
2129 virtual mozilla::PendingAnimationTracker* GetPendingAnimationTracker() = 0;
2130
2131 // Gets the tracker for animations that are waiting to start and
2132 // creates it if it doesn't already exist. As a result, the return value
2133 // will never be nullptr.
2134 virtual mozilla::PendingAnimationTracker*
2135 GetOrCreatePendingAnimationTracker() = 0;
2136
2137 enum SuppressionType {
2138 eAnimationsOnly = 0x1,
2139
2140 // Note that suppressing events also suppresses animation frames, so
2141 // there's no need to split out events in its own bitmask.
2142 eEvents = 0x3,
2143 };
2144
2145 /**
2146 * Prevents user initiated events from being dispatched to the document and
2147 * subdocuments.
2148 */
2149 virtual void SuppressEventHandling(SuppressionType aWhat,
2150 uint32_t aIncrease = 1) = 0;
2151
2152 /**
2153 * Unsuppress event handling.
2154 * @param aFireEvents If true, delayed events (focus/blur) will be fired
2155 * asynchronously.
2156 */
2157 virtual void UnsuppressEventHandlingAndFireEvents(SuppressionType aWhat,
2158 bool aFireEvents) = 0;
2159
EventHandlingSuppressed()2160 uint32_t EventHandlingSuppressed() const { return mEventsSuppressed; }
AnimationsPaused()2161 uint32_t AnimationsPaused() const { return mAnimationsPaused; }
2162
IsEventHandlingEnabled()2163 bool IsEventHandlingEnabled() {
2164 return !EventHandlingSuppressed() && mScriptGlobalObject;
2165 }
2166
2167 /**
2168 * Increment the number of external scripts being evaluated.
2169 */
BeginEvaluatingExternalScript()2170 void BeginEvaluatingExternalScript() { ++mExternalScriptsBeingEvaluated; }
2171
2172 /**
2173 * Decrement the number of external scripts being evaluated.
2174 */
EndEvaluatingExternalScript()2175 void EndEvaluatingExternalScript() { --mExternalScriptsBeingEvaluated; }
2176
IsDNSPrefetchAllowed()2177 bool IsDNSPrefetchAllowed() const { return mAllowDNSPrefetch; }
2178
2179 /**
2180 * Returns true if this document is allowed to contain XUL element and
2181 * use non-builtin XBL bindings.
2182 */
AllowXULXBL()2183 bool AllowXULXBL() {
2184 return mAllowXULXBL == eTriTrue ? true :
2185 mAllowXULXBL == eTriFalse ? false :
2186 InternalAllowXULXBL();
2187 }
2188
ForceEnableXULXBL()2189 void ForceEnableXULXBL() {
2190 mAllowXULXBL = eTriTrue;
2191 }
2192
2193 /**
2194 * Returns the template content owner document that owns the content of
2195 * HTMLTemplateElement.
2196 */
2197 virtual nsIDocument* GetTemplateContentsOwner() = 0;
2198
2199 /**
2200 * Returns true if this document is a static clone of a normal document.
2201 *
2202 * We create static clones for print preview and printing (possibly other
2203 * things in future).
2204 *
2205 * Note that static documents are also "loaded as data" (if this method
2206 * returns true, IsLoadedAsData() will also return true).
2207 */
IsStaticDocument()2208 bool IsStaticDocument() { return mIsStaticDocument; }
2209
2210 /**
2211 * Clones the document along with any subdocuments, stylesheet, etc.
2212 *
2213 * The resulting document and everything it contains (including any
2214 * sub-documents) are created purely via cloning. The returned documents and
2215 * any sub-documents are "loaded as data" documents to preserve the state as
2216 * it was during the clone process (we don't want external resources to load
2217 * and replace the cloned resources).
2218 *
2219 * @param aCloneContainer The container for the clone document.
2220 */
2221 virtual already_AddRefed<nsIDocument>
2222 CreateStaticClone(nsIDocShell* aCloneContainer);
2223
2224 /**
2225 * If this document is a static clone, this returns the original
2226 * document.
2227 */
GetOriginalDocument()2228 nsIDocument* GetOriginalDocument()
2229 {
2230 MOZ_ASSERT(!mOriginalDocument || !mOriginalDocument->GetOriginalDocument());
2231 return mOriginalDocument;
2232 }
2233
2234 /**
2235 * If this document is a static clone, let the original document know that
2236 * we're going away and then release our reference to it.
2237 */
2238 void UnlinkOriginalDocumentIfStatic();
2239
2240 /**
2241 * These are called by the parser as it encounters <picture> tags, the end of
2242 * said tags, and possible picture <source srcset> sources respectively. These
2243 * are used to inform ResolvePreLoadImage() calls. Unset attributes are
2244 * expected to be marked void.
2245 *
2246 * NOTE that the parser does not attempt to track the current picture nesting
2247 * level or whether the given <source> tag is within a picture -- it is only
2248 * guaranteed to order these calls properly with respect to
2249 * ResolvePreLoadImage.
2250 */
2251
2252 virtual void PreloadPictureOpened() = 0;
2253
2254 virtual void PreloadPictureClosed() = 0;
2255
2256 virtual void PreloadPictureImageSource(const nsAString& aSrcsetAttr,
2257 const nsAString& aSizesAttr,
2258 const nsAString& aTypeAttr,
2259 const nsAString& aMediaAttr) = 0;
2260
2261 /**
2262 * Called by the parser to resolve an image for preloading. The parser will
2263 * call the PreloadPicture* functions to inform us of possible <picture>
2264 * nesting and possible sources, which are used to inform URL selection
2265 * responsive <picture> or <img srcset> images. Unset attributes are expected
2266 * to be marked void.
2267 */
2268 virtual already_AddRefed<nsIURI>
2269 ResolvePreloadImage(nsIURI *aBaseURI,
2270 const nsAString& aSrcAttr,
2271 const nsAString& aSrcsetAttr,
2272 const nsAString& aSizesAttr) = 0;
2273 /**
2274 * Called by nsParser to preload images. Can be removed and code moved
2275 * to nsPreloadURIs::PreloadURIs() in file nsParser.cpp whenever the
2276 * parser-module is linked with gklayout-module. aCrossOriginAttr should
2277 * be a void string if the attr is not present.
2278 */
2279 virtual void MaybePreLoadImage(nsIURI* uri,
2280 const nsAString& aCrossOriginAttr,
2281 ReferrerPolicyEnum aReferrerPolicy) = 0;
2282
2283 /**
2284 * Called by images to forget an image preload when they start doing
2285 * the real load.
2286 */
2287 virtual void ForgetImagePreload(nsIURI* aURI) = 0;
2288
2289 /**
2290 * Called by nsParser to preload style sheets. Can also be merged into the
2291 * parser if and when the parser is merged with libgklayout. aCrossOriginAttr
2292 * should be a void string if the attr is not present.
2293 */
2294 virtual void PreloadStyle(nsIURI* aURI, const nsAString& aCharset,
2295 const nsAString& aCrossOriginAttr,
2296 ReferrerPolicyEnum aReferrerPolicy,
2297 const nsAString& aIntegrity) = 0;
2298
2299 /**
2300 * Called by the chrome registry to load style sheets. Can be put
2301 * back there if and when when that module is merged with libgklayout.
2302 *
2303 * This always does a synchronous load. If aIsAgentSheet is true,
2304 * it also uses the system principal and enables unsafe rules.
2305 * DO NOT USE FOR UNTRUSTED CONTENT.
2306 */
2307 virtual nsresult LoadChromeSheetSync(nsIURI* aURI, bool aIsAgentSheet,
2308 RefPtr<mozilla::StyleSheet>* aSheet) = 0;
2309
2310 /**
2311 * Returns true if the locale used for the document specifies a direction of
2312 * right to left. For chrome documents, this comes from the chrome registry.
2313 * This is used to determine the current state for the :-moz-locale-dir pseudoclass
2314 * so once can know whether a document is expected to be rendered left-to-right
2315 * or right-to-left.
2316 */
IsDocumentRightToLeft()2317 virtual bool IsDocumentRightToLeft() { return false; }
2318
2319 /**
2320 * Called by Parser for link rel=preconnect
2321 */
2322 virtual void MaybePreconnect(nsIURI* uri,
2323 mozilla::CORSMode aCORSMode) = 0;
2324
2325 enum DocumentTheme {
2326 Doc_Theme_Uninitialized, // not determined yet
2327 Doc_Theme_None,
2328 Doc_Theme_Neutral,
2329 Doc_Theme_Dark,
2330 Doc_Theme_Bright
2331 };
2332
2333 /**
2334 * Set the document's pending state object (as serialized using structured
2335 * clone).
2336 */
2337 void SetStateObject(nsIStructuredCloneContainer *scContainer);
2338
2339 /**
2340 * Returns Doc_Theme_None if there is no lightweight theme specified,
2341 * Doc_Theme_Dark for a dark theme, Doc_Theme_Bright for a light theme, and
2342 * Doc_Theme_Neutral for any other theme. This is used to determine the state
2343 * of the pseudoclasses :-moz-lwtheme and :-moz-lwtheme-text.
2344 */
GetDocumentLWTheme()2345 virtual int GetDocumentLWTheme() { return Doc_Theme_None; }
2346
2347 /**
2348 * Returns the document state.
2349 * Document state bits have the form NS_DOCUMENT_STATE_* and are declared in
2350 * nsIDocument.h.
2351 */
2352 virtual mozilla::EventStates GetDocumentState() = 0;
2353
2354 virtual nsISupports* GetCurrentContentSink() = 0;
2355
2356 virtual void SetScrollToRef(nsIURI *aDocumentURI) = 0;
2357 virtual void ScrollToRef() = 0;
2358 virtual void ResetScrolledToRefAlready() = 0;
2359 virtual void SetChangeScrollPosWhenScrollingToRef(bool aValue) = 0;
2360
2361 /**
2362 * This method is similar to GetElementById() from nsIDOMDocument but it
2363 * returns a mozilla::dom::Element instead of a nsIDOMElement.
2364 * It prevents converting nsIDOMElement to mozilla::dom::Element which is
2365 * already converted from mozilla::dom::Element.
2366 */
2367 virtual Element* GetElementById(const nsAString& aElementId) = 0;
2368
2369 /**
2370 * This method returns _all_ the elements in this document which
2371 * have id aElementId, if there are any. Otherwise it returns null.
2372 */
2373 virtual const nsTArray<Element*>* GetAllElementsForId(const nsAString& aElementId) const = 0;
2374
2375 /**
2376 * Lookup an image element using its associated ID, which is usually provided
2377 * by |-moz-element()|. Similar to GetElementById, with the difference that
2378 * elements set using mozSetImageElement have higher priority.
2379 * @param aId the ID associated the element we want to lookup
2380 * @return the element associated with |aId|
2381 */
2382 virtual Element* LookupImageElement(const nsAString& aElementId) = 0;
2383
2384 virtual mozilla::dom::DocumentTimeline* Timeline() = 0;
2385 virtual mozilla::LinkedList<mozilla::dom::DocumentTimeline>& Timelines() = 0;
2386
2387 virtual void GetAnimations(
2388 nsTArray<RefPtr<mozilla::dom::Animation>>& aAnimations) = 0;
2389
2390 mozilla::dom::SVGSVGElement* GetSVGRootElement() const;
2391
2392 nsresult ScheduleFrameRequestCallback(mozilla::dom::FrameRequestCallback& aCallback,
2393 int32_t *aHandle);
2394 void CancelFrameRequestCallback(int32_t aHandle);
2395
2396 typedef nsTArray<RefPtr<mozilla::dom::FrameRequestCallback>> FrameRequestCallbackList;
2397 /**
2398 * Put this document's frame request callbacks into the provided
2399 * list, and forget about them.
2400 */
2401 void TakeFrameRequestCallbacks(FrameRequestCallbackList& aCallbacks);
2402
2403 /**
2404 * @return true if this document's frame request callbacks should be
2405 * throttled. We throttle requestAnimationFrame for documents which aren't
2406 * visible (e.g. scrolled out of the viewport).
2407 */
2408 bool ShouldThrottleFrameRequests();
2409
2410 // This returns true when the document tree is being teared down.
InUnlinkOrDeletion()2411 bool InUnlinkOrDeletion() { return mInUnlinkOrDeletion; }
2412
2413 mozilla::dom::ImageTracker* ImageTracker();
2414
2415 virtual nsresult AddPlugin(nsIObjectLoadingContent* aPlugin) = 0;
2416 virtual void RemovePlugin(nsIObjectLoadingContent* aPlugin) = 0;
2417 virtual void GetPlugins(nsTArray<nsIObjectLoadingContent*>& aPlugins) = 0;
2418
2419 virtual nsresult AddResponsiveContent(nsIContent* aContent) = 0;
2420 virtual void RemoveResponsiveContent(nsIContent* aContent) = 0;
2421 virtual void NotifyMediaFeatureValuesChanged() = 0;
2422
2423 virtual nsresult GetStateObject(nsIVariant** aResult) = 0;
2424
2425 virtual nsDOMNavigationTiming* GetNavigationTiming() const = 0;
2426
2427 virtual nsresult SetNavigationTiming(nsDOMNavigationTiming* aTiming) = 0;
2428
2429 virtual Element* FindImageMap(const nsAString& aNormalizedMapName) = 0;
2430
2431 // Add aLink to the set of links that need their status resolved.
2432 void RegisterPendingLinkUpdate(mozilla::dom::Link* aLink);
2433
2434 // Remove aLink from the set of links that need their status resolved.
2435 // This function must be called when links are removed from the document.
2436 void UnregisterPendingLinkUpdate(mozilla::dom::Link* aElement);
2437
2438 // Update state on links in mLinksToUpdate. This function must
2439 // be called prior to selector matching.
2440 void FlushPendingLinkUpdates();
2441
2442 #define DEPRECATED_OPERATION(_op) e##_op,
2443 enum DeprecatedOperations {
2444 #include "nsDeprecatedOperationList.h"
2445 eDeprecatedOperationCount
2446 };
2447 #undef DEPRECATED_OPERATION
2448 bool HasWarnedAbout(DeprecatedOperations aOperation) const;
2449 void WarnOnceAbout(DeprecatedOperations aOperation,
2450 bool asError = false) const;
2451
2452 #define DOCUMENT_WARNING(_op) e##_op,
2453 enum DocumentWarnings {
2454 #include "nsDocumentWarningList.h"
2455 eDocumentWarningCount
2456 };
2457 #undef DOCUMENT_WARNING
2458 bool HasWarnedAbout(DocumentWarnings aWarning) const;
2459 void WarnOnceAbout(DocumentWarnings aWarning,
2460 bool asError = false,
2461 const char16_t **aParams = nullptr,
2462 uint32_t aParamsLength = 0) const;
2463
2464 virtual void PostVisibilityUpdateEvent() = 0;
2465
IsSyntheticDocument()2466 bool IsSyntheticDocument() const { return mIsSyntheticDocument; }
2467
SetNeedLayoutFlush()2468 void SetNeedLayoutFlush() {
2469 mNeedLayoutFlush = true;
2470 if (mDisplayDocument) {
2471 mDisplayDocument->SetNeedLayoutFlush();
2472 }
2473 }
2474
SetNeedStyleFlush()2475 void SetNeedStyleFlush() {
2476 mNeedStyleFlush = true;
2477 if (mDisplayDocument) {
2478 mDisplayDocument->SetNeedStyleFlush();
2479 }
2480 }
2481
2482 // Note: nsIDocument is a sub-class of nsINode, which has a
2483 // SizeOfExcludingThis function. However, because nsIDocument objects can
2484 // only appear at the top of the DOM tree, we have a specialized measurement
2485 // function which returns multiple sizes.
2486 virtual void DocAddSizeOfExcludingThis(nsWindowSizes* aWindowSizes) const;
2487 // DocAddSizeOfIncludingThis doesn't need to be overridden by sub-classes
2488 // because nsIDocument inherits from nsINode; see the comment above the
2489 // declaration of nsINode::SizeOfIncludingThis.
2490 virtual void DocAddSizeOfIncludingThis(nsWindowSizes* aWindowSizes) const;
2491
MayHaveDOMMutationObservers()2492 bool MayHaveDOMMutationObservers()
2493 {
2494 return mMayHaveDOMMutationObservers;
2495 }
2496
SetMayHaveDOMMutationObservers()2497 void SetMayHaveDOMMutationObservers()
2498 {
2499 mMayHaveDOMMutationObservers = true;
2500 }
2501
MayHaveAnimationObservers()2502 bool MayHaveAnimationObservers()
2503 {
2504 return mMayHaveAnimationObservers;
2505 }
2506
SetMayHaveAnimationObservers()2507 void SetMayHaveAnimationObservers()
2508 {
2509 mMayHaveAnimationObservers = true;
2510 }
2511
IsInSyncOperation()2512 bool IsInSyncOperation()
2513 {
2514 return mInSyncOperationCount != 0;
2515 }
2516
SetIsInSyncOperation(bool aSync)2517 void SetIsInSyncOperation(bool aSync)
2518 {
2519 if (aSync) {
2520 ++mInSyncOperationCount;
2521 } else {
2522 --mInSyncOperationCount;
2523 }
2524 }
2525
CreatingStaticClone()2526 bool CreatingStaticClone() const
2527 {
2528 return mCreatingStaticClone;
2529 }
2530
2531 /**
2532 * Creates a new element in the HTML namespace with a local name given by
2533 * aTag.
2534 */
2535 already_AddRefed<Element> CreateHTMLElement(nsIAtom* aTag);
2536
2537 // WebIDL API
GetParentObject()2538 nsIGlobalObject* GetParentObject() const
2539 {
2540 return GetScopeObject();
2541 }
2542 static already_AddRefed<nsIDocument>
2543 Constructor(const GlobalObject& aGlobal,
2544 mozilla::ErrorResult& rv);
2545 virtual mozilla::dom::DOMImplementation*
2546 GetImplementation(mozilla::ErrorResult& rv) = 0;
2547 MOZ_MUST_USE nsresult GetURL(nsString& retval) const;
2548 MOZ_MUST_USE nsresult GetDocumentURI(nsString& retval) const;
2549 // Return the URI for the document.
2550 // The returned value may differ if the document is loaded via XHR, and
2551 // when accessed from chrome privileged script and
2552 // from content privileged script for compatibility.
2553 void GetDocumentURIFromJS(nsString& aDocumentURI,
2554 mozilla::ErrorResult& aRv) const;
2555 void GetCompatMode(nsString& retval) const;
2556 void GetCharacterSet(nsAString& retval) const;
2557 // Skip GetContentType, because our NS_IMETHOD version above works fine here.
2558 // GetDoctype defined above
GetDocumentElement()2559 Element* GetDocumentElement() const
2560 {
2561 return GetRootElement();
2562 }
2563
2564 enum ElementCallbackType {
2565 eCreated,
2566 eAttached,
2567 eDetached,
2568 eAttributeChanged
2569 };
2570
2571 nsIDocument* GetTopLevelContentDocument();
2572
2573 virtual void
2574 RegisterElement(JSContext* aCx, const nsAString& aName,
2575 const mozilla::dom::ElementRegistrationOptions& aOptions,
2576 JS::MutableHandle<JSObject*> aRetval,
2577 mozilla::ErrorResult& rv) = 0;
2578 virtual already_AddRefed<mozilla::dom::CustomElementRegistry>
2579 GetCustomElementRegistry() = 0;
2580
2581 already_AddRefed<nsContentList>
GetElementsByTagName(const nsAString & aTagName)2582 GetElementsByTagName(const nsAString& aTagName)
2583 {
2584 return NS_GetContentList(this, kNameSpaceID_Unknown, aTagName);
2585 }
2586 already_AddRefed<nsContentList>
2587 GetElementsByTagNameNS(const nsAString& aNamespaceURI,
2588 const nsAString& aLocalName,
2589 mozilla::ErrorResult& aResult);
2590 already_AddRefed<nsContentList>
2591 GetElementsByClassName(const nsAString& aClasses);
2592 // GetElementById defined above
2593 virtual already_AddRefed<Element>
2594 CreateElement(const nsAString& aTagName,
2595 const mozilla::dom::ElementCreationOptionsOrString& aOptions,
2596 mozilla::ErrorResult& rv) = 0;
2597 virtual already_AddRefed<Element>
2598 CreateElementNS(const nsAString& aNamespaceURI,
2599 const nsAString& aQualifiedName,
2600 const mozilla::dom::ElementCreationOptionsOrString& aOptions,
2601 mozilla::ErrorResult& rv) = 0;
2602 already_AddRefed<mozilla::dom::DocumentFragment>
2603 CreateDocumentFragment() const;
2604 already_AddRefed<nsTextNode> CreateTextNode(const nsAString& aData) const;
2605 already_AddRefed<mozilla::dom::Comment>
2606 CreateComment(const nsAString& aData) const;
2607 already_AddRefed<mozilla::dom::ProcessingInstruction>
2608 CreateProcessingInstruction(const nsAString& target, const nsAString& data,
2609 mozilla::ErrorResult& rv) const;
2610 already_AddRefed<nsINode>
2611 ImportNode(nsINode& aNode, bool aDeep, mozilla::ErrorResult& rv) const;
2612 nsINode* AdoptNode(nsINode& aNode, mozilla::ErrorResult& rv);
2613 already_AddRefed<mozilla::dom::Event>
2614 CreateEvent(const nsAString& aEventType, mozilla::ErrorResult& rv) const;
2615 already_AddRefed<nsRange> CreateRange(mozilla::ErrorResult& rv);
2616 already_AddRefed<mozilla::dom::NodeIterator>
2617 CreateNodeIterator(nsINode& aRoot, uint32_t aWhatToShow,
2618 mozilla::dom::NodeFilter* aFilter,
2619 mozilla::ErrorResult& rv) const;
2620 already_AddRefed<mozilla::dom::NodeIterator>
2621 CreateNodeIterator(nsINode& aRoot, uint32_t aWhatToShow,
2622 mozilla::dom::NodeFilterHolder aFilter,
2623 mozilla::ErrorResult& rv) const;
2624 already_AddRefed<mozilla::dom::TreeWalker>
2625 CreateTreeWalker(nsINode& aRoot, uint32_t aWhatToShow,
2626 mozilla::dom::NodeFilter* aFilter, mozilla::ErrorResult& rv) const;
2627 already_AddRefed<mozilla::dom::TreeWalker>
2628 CreateTreeWalker(nsINode& aRoot, uint32_t aWhatToShow,
2629 mozilla::dom::NodeFilterHolder aFilter,
2630 mozilla::ErrorResult& rv) const;
2631
2632 // Deprecated WebIDL bits
2633 already_AddRefed<mozilla::dom::CDATASection>
2634 CreateCDATASection(const nsAString& aData, mozilla::ErrorResult& rv);
2635 already_AddRefed<mozilla::dom::Attr>
2636 CreateAttribute(const nsAString& aName, mozilla::ErrorResult& rv);
2637 already_AddRefed<mozilla::dom::Attr>
2638 CreateAttributeNS(const nsAString& aNamespaceURI,
2639 const nsAString& aQualifiedName,
2640 mozilla::ErrorResult& rv);
2641 void GetInputEncoding(nsAString& aInputEncoding) const;
2642 already_AddRefed<mozilla::dom::Location> GetLocation() const;
2643 void GetReferrer(nsAString& aReferrer) const;
2644 void GetLastModified(nsAString& aLastModified) const;
2645 void GetReadyState(nsAString& aReadyState) const;
2646 // Not const because otherwise the compiler can't figure out whether to call
2647 // this GetTitle or the nsAString version from non-const methods, since
2648 // neither is an exact match.
2649 virtual void GetTitle(nsString& aTitle) = 0;
2650 virtual void SetTitle(const nsAString& aTitle, mozilla::ErrorResult& rv) = 0;
2651 void GetDir(nsAString& aDirection) const;
2652 void SetDir(const nsAString& aDirection);
GetDefaultView()2653 nsPIDOMWindowOuter* GetDefaultView() const
2654 {
2655 return GetWindow();
2656 }
2657 Element* GetActiveElement();
2658 bool HasFocus(mozilla::ErrorResult& rv) const;
2659 // Event handlers are all on nsINode already
MozSyntheticDocument()2660 bool MozSyntheticDocument() const
2661 {
2662 return IsSyntheticDocument();
2663 }
2664 Element* GetCurrentScript();
2665 void ReleaseCapture() const;
2666 virtual void MozSetImageElement(const nsAString& aImageElementId,
2667 Element* aElement) = 0;
2668 nsIURI* GetDocumentURIObject() const;
2669 // Not const because all the full-screen goop is not const
2670 virtual bool FullscreenEnabled() = 0;
2671 virtual Element* GetFullscreenElement() = 0;
Fullscreen()2672 bool Fullscreen()
2673 {
2674 return !!GetFullscreenElement();
2675 }
2676 void ExitFullscreen();
2677 Element* GetPointerLockElement();
ExitPointerLock()2678 void ExitPointerLock()
2679 {
2680 UnlockPointer(this);
2681 }
2682 #ifdef MOZILLA_INTERNAL_API
Hidden()2683 bool Hidden() const
2684 {
2685 return mVisibilityState != mozilla::dom::VisibilityState::Visible;
2686 }
VisibilityState()2687 mozilla::dom::VisibilityState VisibilityState() const
2688 {
2689 return mVisibilityState;
2690 }
2691 #endif
2692 virtual mozilla::dom::StyleSheetList* StyleSheets() = 0;
2693 void GetSelectedStyleSheetSet(nsAString& aSheetSet);
2694 virtual void SetSelectedStyleSheetSet(const nsAString& aSheetSet) = 0;
2695 virtual void GetLastStyleSheetSet(nsString& aSheetSet) = 0;
2696 void GetPreferredStyleSheetSet(nsAString& aSheetSet);
2697 virtual mozilla::dom::DOMStringList* StyleSheetSets() = 0;
2698 virtual void EnableStyleSheetsForSet(const nsAString& aSheetSet) = 0;
2699 Element* ElementFromPoint(float aX, float aY);
2700 void ElementsFromPoint(float aX,
2701 float aY,
2702 nsTArray<RefPtr<mozilla::dom::Element>>& aElements);
2703
2704 /**
2705 * Retrieve the location of the caret position (DOM node and character
2706 * offset within that node), given a point.
2707 *
2708 * @param aX Horizontal point at which to determine the caret position, in
2709 * page coordinates.
2710 * @param aY Vertical point at which to determine the caret position, in
2711 * page coordinates.
2712 */
2713 already_AddRefed<nsDOMCaretPosition>
2714 CaretPositionFromPoint(float aX, float aY);
2715
2716 Element* GetScrollingElement();
2717
2718 // QuerySelector and QuerySelectorAll already defined on nsINode
2719 nsINodeList* GetAnonymousNodes(Element& aElement);
2720 Element* GetAnonymousElementByAttribute(Element& aElement,
2721 const nsAString& aAttrName,
2722 const nsAString& aAttrValue);
2723 Element* GetBindingParent(nsINode& aNode);
2724 void LoadBindingDocument(const nsAString& aURI,
2725 nsIPrincipal& aSubjectPrincipal,
2726 mozilla::ErrorResult& rv);
2727 void LoadBindingDocument(const nsAString& aURI,
2728 const mozilla::Maybe<nsIPrincipal*>& aSubjectPrincipal,
2729 mozilla::ErrorResult& rv);
2730 mozilla::dom::XPathExpression*
2731 CreateExpression(const nsAString& aExpression,
2732 mozilla::dom::XPathNSResolver* aResolver,
2733 mozilla::ErrorResult& rv);
2734 nsINode* CreateNSResolver(nsINode& aNodeResolver);
2735 already_AddRefed<mozilla::dom::XPathResult>
2736 Evaluate(JSContext* aCx, const nsAString& aExpression, nsINode& aContextNode,
2737 mozilla::dom::XPathNSResolver* aResolver, uint16_t aType,
2738 JS::Handle<JSObject*> aResult, mozilla::ErrorResult& rv);
2739 // Touch event handlers already on nsINode
2740 already_AddRefed<mozilla::dom::Touch>
2741 CreateTouch(nsGlobalWindow* aView, mozilla::dom::EventTarget* aTarget,
2742 int32_t aIdentifier, int32_t aPageX, int32_t aPageY,
2743 int32_t aScreenX, int32_t aScreenY, int32_t aClientX,
2744 int32_t aClientY, int32_t aRadiusX, int32_t aRadiusY,
2745 float aRotationAngle, float aForce);
2746 already_AddRefed<mozilla::dom::TouchList> CreateTouchList();
2747 already_AddRefed<mozilla::dom::TouchList>
2748 CreateTouchList(mozilla::dom::Touch& aTouch,
2749 const mozilla::dom::Sequence<mozilla::OwningNonNull<mozilla::dom::Touch> >& aTouches);
2750 already_AddRefed<mozilla::dom::TouchList>
2751 CreateTouchList(const mozilla::dom::Sequence<mozilla::OwningNonNull<mozilla::dom::Touch> >& aTouches);
2752
SetStyleSheetChangeEventsEnabled(bool aValue)2753 void SetStyleSheetChangeEventsEnabled(bool aValue)
2754 {
2755 mStyleSheetChangeEventsEnabled = aValue;
2756 }
2757
StyleSheetChangeEventsEnabled()2758 bool StyleSheetChangeEventsEnabled() const
2759 {
2760 return mStyleSheetChangeEventsEnabled;
2761 }
2762
2763 void ObsoleteSheet(nsIURI *aSheetURI, mozilla::ErrorResult& rv);
2764
2765 void ObsoleteSheet(const nsAString& aSheetURI, mozilla::ErrorResult& rv);
2766
2767 already_AddRefed<nsIURI> GetMozDocumentURIIfNotForErrorPages();
2768
2769 // ParentNode
2770 nsIHTMLCollection* Children();
2771 uint32_t ChildElementCount();
2772
AsHTMLDocument()2773 virtual nsHTMLDocument* AsHTMLDocument() { return nullptr; }
AsSVGDocument()2774 virtual mozilla::dom::SVGDocument* AsSVGDocument() { return nullptr; }
2775
2776 // The root document of the import tree. If this document is not an import
2777 // this will return the document itself.
2778 virtual nsIDocument* MasterDocument() = 0;
2779 virtual void SetMasterDocument(nsIDocument* master) = 0;
2780 virtual bool IsMasterDocument() = 0;
2781 virtual mozilla::dom::ImportManager* ImportManager() = 0;
2782 // We keep track of the order of sub imports were added to the document.
2783 virtual bool HasSubImportLink(nsINode* aLink) = 0;
2784 virtual uint32_t IndexOfSubImportLink(nsINode* aLink) = 0;
2785 virtual void AddSubImportLink(nsINode* aLink) = 0;
2786 virtual nsINode* GetSubImportLink(uint32_t aIdx) = 0;
2787
2788 /*
2789 * Given a node, get a weak reference to it and append that reference to
2790 * mBlockedTrackingNodes. Can be used later on to look up a node in it.
2791 * (e.g., by the UI)
2792 */
AddBlockedTrackingNode(nsINode * node)2793 void AddBlockedTrackingNode(nsINode *node)
2794 {
2795 if (!node) {
2796 return;
2797 }
2798
2799 nsWeakPtr weakNode = do_GetWeakReference(node);
2800
2801 if (weakNode) {
2802 mBlockedTrackingNodes.AppendElement(weakNode);
2803 }
2804 }
2805
2806 gfxUserFontSet* GetUserFontSet(bool aFlushUserFontSet = true);
2807 void FlushUserFontSet();
2808 void RebuildUserFontSet(); // asynchronously
GetFonts()2809 mozilla::dom::FontFaceSet* GetFonts() { return mFontFaceSet; }
2810
2811 // FontFaceSource
2812 mozilla::dom::FontFaceSet* Fonts();
2813
DidFireDOMContentLoaded()2814 bool DidFireDOMContentLoaded() const { return mDidFireDOMContentLoaded; }
2815
SetDocumentUseCounter(mozilla::UseCounter aUseCounter)2816 void SetDocumentUseCounter(mozilla::UseCounter aUseCounter)
2817 {
2818 if (!mUseCounters[aUseCounter]) {
2819 mUseCounters[aUseCounter] = true;
2820 }
2821 }
2822
2823 void SetPageUseCounter(mozilla::UseCounter aUseCounter);
2824
SetDocumentAndPageUseCounter(mozilla::UseCounter aUseCounter)2825 void SetDocumentAndPageUseCounter(mozilla::UseCounter aUseCounter)
2826 {
2827 SetDocumentUseCounter(aUseCounter);
2828 SetPageUseCounter(aUseCounter);
2829 }
2830
2831 void PropagateUseCounters(nsIDocument* aParentDocument);
2832
SetUserHasInteracted(bool aUserHasInteracted)2833 void SetUserHasInteracted(bool aUserHasInteracted)
2834 {
2835 mUserHasInteracted = aUserHasInteracted;
2836 }
2837
UserHasInteracted()2838 bool UserHasInteracted()
2839 {
2840 return mUserHasInteracted;
2841 }
2842
2843 bool HasScriptsBlockedBySandbox();
2844
2845 bool InlineScriptAllowedByCSP();
2846
2847 void ReportHasScrollLinkedEffect();
HasScrollLinkedEffect()2848 bool HasScrollLinkedEffect() const
2849 {
2850 return mHasScrollLinkedEffect;
2851 }
2852
2853 mozilla::dom::DocGroup* GetDocGroup();
2854
2855 virtual void AddIntersectionObserver(
2856 mozilla::dom::DOMIntersectionObserver* aObserver) = 0;
2857 virtual void RemoveIntersectionObserver(
2858 mozilla::dom::DOMIntersectionObserver* aObserver) = 0;
2859
2860 virtual void UpdateIntersectionObservations() = 0;
2861 virtual void ScheduleIntersectionObserverNotification() = 0;
2862 virtual void NotifyIntersectionObservers() = 0;
2863
2864 protected:
GetUseCounter(mozilla::UseCounter aUseCounter)2865 bool GetUseCounter(mozilla::UseCounter aUseCounter)
2866 {
2867 return mUseCounters[aUseCounter];
2868 }
2869
SetChildDocumentUseCounter(mozilla::UseCounter aUseCounter)2870 void SetChildDocumentUseCounter(mozilla::UseCounter aUseCounter)
2871 {
2872 if (!mChildDocumentUseCounters[aUseCounter]) {
2873 mChildDocumentUseCounters[aUseCounter] = true;
2874 }
2875 }
2876
GetChildDocumentUseCounter(mozilla::UseCounter aUseCounter)2877 bool GetChildDocumentUseCounter(mozilla::UseCounter aUseCounter)
2878 {
2879 return mChildDocumentUseCounters[aUseCounter];
2880 }
2881
2882 private:
2883 mutable std::bitset<eDeprecatedOperationCount> mDeprecationWarnedAbout;
2884 mutable std::bitset<eDocumentWarningCount> mDocWarningWarnedAbout;
2885 SelectorCache mSelectorCache;
2886
2887 protected:
2888 ~nsIDocument();
2889 nsPropertyTable* GetExtraPropertyTable(uint16_t aCategory);
2890
2891 // Never ever call this. Only call GetWindow!
2892 virtual nsPIDOMWindowOuter* GetWindowInternal() const = 0;
2893
2894 // Never ever call this. Only call GetScriptHandlingObject!
2895 virtual nsIScriptGlobalObject* GetScriptHandlingObjectInternal() const = 0;
2896
2897 // Never ever call this. Only call AllowXULXBL!
2898 virtual bool InternalAllowXULXBL() = 0;
2899
2900 /**
2901 * These methods should be called before and after dispatching
2902 * a mutation event.
2903 * To make this easy and painless, use the mozAutoSubtreeModified helper class.
2904 */
2905 virtual void WillDispatchMutationEvent(nsINode* aTarget) = 0;
2906 virtual void MutationEventDispatched(nsINode* aTarget) = 0;
2907 friend class mozAutoSubtreeModified;
2908
GetNameSpaceElement()2909 virtual Element* GetNameSpaceElement() override
2910 {
2911 return GetRootElement();
2912 }
2913
2914 void SetContentTypeInternal(const nsACString& aType);
2915
GetContentTypeInternal()2916 nsCString GetContentTypeInternal() const
2917 {
2918 return mContentType;
2919 }
2920
2921 mozilla::dom::XPathEvaluator* XPathEvaluator();
2922
HandleRebuildUserFontSet()2923 void HandleRebuildUserFontSet() {
2924 mPostedFlushUserFontSet = false;
2925 FlushUserFontSet();
2926 }
2927
GetId()2928 const nsString& GetId() const
2929 {
2930 return mId;
2931 }
2932
2933 // Update our frame request callback scheduling state, if needed. This will
2934 // schedule or unschedule them, if necessary, and update
2935 // mFrameRequestCallbacksScheduled. aOldShell should only be passed when
2936 // mPresShell is becoming null; in that case it will be used to get hold of
2937 // the relevant refresh driver.
2938 void UpdateFrameRequestCallbackSchedulingState(nsIPresShell* aOldShell = nullptr);
2939
2940 nsCString mReferrer;
2941 nsString mLastModified;
2942
2943 nsCOMPtr<nsIURI> mDocumentURI;
2944 nsCOMPtr<nsIURI> mOriginalURI;
2945 nsCOMPtr<nsIURI> mChromeXHRDocURI;
2946 nsCOMPtr<nsIURI> mDocumentBaseURI;
2947 nsCOMPtr<nsIURI> mChromeXHRDocBaseURI;
2948
2949 nsWeakPtr mDocumentLoadGroup;
2950
2951 bool mReferrerPolicySet;
2952 ReferrerPolicyEnum mReferrerPolicy;
2953
2954 bool mBlockAllMixedContent;
2955 bool mBlockAllMixedContentPreloads;
2956 bool mUpgradeInsecureRequests;
2957 bool mUpgradeInsecurePreloads;
2958
2959 // if nsMixedContentBlocker requires sending an HSTS priming request,
2960 // temporarily store that in the document so that it can be propogated to the
2961 // LoadInfo and eventually the HTTP Channel
2962 nsDataHashtable<nsURIHashKey, HSTSPrimingState> mHSTSPrimingURIList;
2963
2964 mozilla::WeakPtr<nsDocShell> mDocumentContainer;
2965
2966 nsCString mCharacterSet;
2967 int32_t mCharacterSetSource;
2968
2969 // This is just a weak pointer; the parent document owns its children.
2970 nsIDocument* mParentDocument;
2971
2972 // A reference to the element last returned from GetRootElement().
2973 mozilla::dom::Element* mCachedRootElement;
2974
2975 // This is a weak reference, but we hold a strong reference to mNodeInfo,
2976 // which in turn holds a strong reference to this mNodeInfoManager.
2977 nsNodeInfoManager* mNodeInfoManager;
2978 RefPtr<mozilla::css::Loader> mCSSLoader;
2979 RefPtr<mozilla::css::ImageLoader> mStyleImageLoader;
2980 RefPtr<nsHTMLStyleSheet> mAttrStyleSheet;
2981 RefPtr<nsHTMLCSSStyleSheet> mStyleAttrStyleSheet;
2982 RefPtr<mozilla::SVGAttrAnimationRuleProcessor> mSVGAttrAnimationRuleProcessor;
2983
2984 // Tracking for images in the document.
2985 RefPtr<mozilla::dom::ImageTracker> mImageTracker;
2986
2987 // The set of all object, embed, applet, video/audio elements or
2988 // nsIObjectLoadingContent or nsIDocumentActivity for which this is the
2989 // owner document. (They might not be in the document.)
2990 // These are non-owning pointers, the elements are responsible for removing
2991 // themselves when they go away.
2992 nsAutoPtr<nsTHashtable<nsPtrHashKey<nsISupports> > > mActivityObservers;
2993
2994 // The set of all links that need their status resolved. Links must add themselves
2995 // to this set by calling RegisterPendingLinkUpdate when added to a document and must
2996 // remove themselves by calling UnregisterPendingLinkUpdate when removed from a document.
2997 nsTHashtable<nsPtrHashKey<mozilla::dom::Link> > mLinksToUpdate;
2998
2999 // SMIL Animation Controller, lazily-initialized in GetAnimationController
3000 RefPtr<nsSMILAnimationController> mAnimationController;
3001
3002 // Table of element properties for this document.
3003 nsPropertyTable mPropertyTable;
3004 nsTArray<nsAutoPtr<nsPropertyTable> > mExtraPropertyTables;
3005
3006 // Our cached .children collection
3007 nsCOMPtr<nsIHTMLCollection> mChildrenCollection;
3008
3009 // container for per-context fonts (downloadable, SVG, etc.)
3010 RefPtr<mozilla::dom::FontFaceSet> mFontFaceSet;
3011
3012 // Compatibility mode
3013 nsCompatibility mCompatMode;
3014
3015 // Our readyState
3016 ReadyState mReadyState;
3017
3018 #ifdef MOZILLA_INTERNAL_API
3019 // Our visibility state
3020 mozilla::dom::VisibilityState mVisibilityState;
3021 static_assert(sizeof(mozilla::dom::VisibilityState) == sizeof(uint32_t), "Error size of mVisibilityState and mDummy");
3022 #else
3023 uint32_t mDummy;
3024 #endif
3025
3026 // Whether this document has (or will have, once we have a pres shell) a
3027 // Gecko- or Servo-backed style system.
3028 mozilla::StyleBackendType mStyleBackendType;
3029
3030 // True if BIDI is enabled.
3031 bool mBidiEnabled : 1;
3032 // True if a MathML element has ever been owned by this document.
3033 bool mMathMLEnabled : 1;
3034
3035 // True if this document is the initial document for a window. This should
3036 // basically be true only for documents that exist in newly-opened windows or
3037 // documents created to satisfy a GetDocument() on a window when there's no
3038 // document in it.
3039 bool mIsInitialDocumentInWindow : 1;
3040
3041 // True if we're loaded as data and therefor has any dangerous stuff, such
3042 // as scripts and plugins, disabled.
3043 bool mLoadedAsData : 1;
3044
3045 // This flag is only set in XMLDocument, for e.g. documents used in XBL. We
3046 // don't want animations to play in such documents, so we need to store the
3047 // flag here so that we can check it in nsDocument::GetAnimationController.
3048 bool mLoadedAsInteractiveData : 1;
3049
3050 // If true, whoever is creating the document has gotten it to the
3051 // point where it's safe to start layout on it.
3052 bool mMayStartLayout : 1;
3053
3054 // True iff we've ever fired a DOMTitleChanged event for this document
3055 bool mHaveFiredTitleChange : 1;
3056
3057 // State for IsShowing(). mIsShowing starts off false. It becomes true when
3058 // OnPageShow happens and becomes false when OnPageHide happens. So it's false
3059 // before the initial load completes and when we're in bfcache or unloaded,
3060 // true otherwise.
3061 bool mIsShowing : 1;
3062
3063 // State for IsVisible(). mVisible starts off true. It becomes false when
3064 // OnPageHide happens, and becomes true again when OnPageShow happens. So
3065 // it's false only when we're in bfcache or unloaded.
3066 bool mVisible : 1;
3067
3068 // True if our content viewer has been removed from the docshell
3069 // (it may still be displayed, but in zombie state). Form control data
3070 // has been saved.
3071 bool mRemovedFromDocShell : 1;
3072
3073 // True iff DNS prefetch is allowed for this document. Note that if the
3074 // document has no window, DNS prefetch won't be performed no matter what.
3075 bool mAllowDNSPrefetch : 1;
3076
3077 // True when this document is a static clone of a normal document
3078 bool mIsStaticDocument : 1;
3079
3080 // True while this document is being cloned to a static document.
3081 bool mCreatingStaticClone : 1;
3082
3083 // True iff the document is being unlinked or deleted.
3084 bool mInUnlinkOrDeletion : 1;
3085
3086 // True if document has ever had script handling object.
3087 bool mHasHadScriptHandlingObject : 1;
3088
3089 // True if we're an SVG document being used as an image.
3090 bool mIsBeingUsedAsImage : 1;
3091
3092 // True is this document is synthetic : stand alone image, video, audio
3093 // file, etc.
3094 bool mIsSyntheticDocument : 1;
3095
3096 // True if this document has links whose state needs updating
3097 bool mHasLinksToUpdate : 1;
3098
3099 // True if a layout flush might not be a no-op
3100 bool mNeedLayoutFlush : 1;
3101
3102 // True if a style flush might not be a no-op
3103 bool mNeedStyleFlush : 1;
3104
3105 // True if a DOMMutationObserver is perhaps attached to a node in the document.
3106 bool mMayHaveDOMMutationObservers : 1;
3107
3108 // True if an nsIAnimationObserver is perhaps attached to a node in the document.
3109 bool mMayHaveAnimationObservers : 1;
3110
3111 // True if a document has loaded Mixed Active Script (see nsMixedContentBlocker.cpp)
3112 bool mHasMixedActiveContentLoaded : 1;
3113
3114 // True if a document has blocked Mixed Active Script (see nsMixedContentBlocker.cpp)
3115 bool mHasMixedActiveContentBlocked : 1;
3116
3117 // True if a document has loaded Mixed Display/Passive Content (see nsMixedContentBlocker.cpp)
3118 bool mHasMixedDisplayContentLoaded : 1;
3119
3120 // True if a document has blocked Mixed Display/Passive Content (see nsMixedContentBlocker.cpp)
3121 bool mHasMixedDisplayContentBlocked : 1;
3122
3123 // True if a document loads a plugin object that attempts to load mixed content subresources through necko(see nsMixedContentBlocker.cpp)
3124 bool mHasMixedContentObjectSubrequest : 1;
3125
3126 // True if a document load has a CSP attached.
3127 bool mHasCSP : 1;
3128
3129 // True if a document load has a CSP with unsafe-eval attached.
3130 bool mHasUnsafeEvalCSP : 1;
3131
3132 // True if a document load has a CSP with unsafe-inline attached.
3133 bool mHasUnsafeInlineCSP : 1;
3134
3135 // True if a document has blocked Tracking Content
3136 bool mHasTrackingContentBlocked : 1;
3137
3138 // True if a document has loaded Tracking Content
3139 bool mHasTrackingContentLoaded : 1;
3140
3141 // True if DisallowBFCaching has been called on this document.
3142 bool mBFCacheDisallowed : 1;
3143
3144 bool mHasHadDefaultView : 1;
3145
3146 // Whether style sheet change events will be dispatched for this document
3147 bool mStyleSheetChangeEventsEnabled : 1;
3148
3149 // Whether the document was created by a srcdoc iframe.
3150 bool mIsSrcdocDocument : 1;
3151
3152 // Records whether we've done a document.open. If this is true, it's possible
3153 // for nodes from this document to have outdated wrappers in their wrapper
3154 // caches.
3155 bool mDidDocumentOpen : 1;
3156
3157 // Whether this document has a display document and thus is considered to
3158 // be a resource document. Normally this is the same as !!mDisplayDocument,
3159 // but mDisplayDocument is cleared during Unlink. mHasDisplayDocument is
3160 // valid in the document's destructor.
3161 bool mHasDisplayDocument : 1;
3162
3163 // Is the current mFontFaceSet valid?
3164 bool mFontFaceSetDirty : 1;
3165
3166 // Has GetUserFontSet() been called?
3167 bool mGetUserFontSetCalled : 1;
3168
3169 // Do we currently have an event posted to call FlushUserFontSet?
3170 bool mPostedFlushUserFontSet : 1;
3171
3172 // True is document has ever been in a foreground window.
3173 bool mEverInForeground : 1;
3174
3175 // True if we have fired the DOMContentLoaded event, or don't plan to fire one
3176 // (e.g. we're not being parsed at all).
3177 bool mDidFireDOMContentLoaded : 1;
3178
3179 // True if ReportHasScrollLinkedEffect() has been called.
3180 bool mHasScrollLinkedEffect : 1;
3181
3182 // True if we have frame request callbacks scheduled with the refresh driver.
3183 // This should generally be updated only via
3184 // UpdateFrameRequestCallbackSchedulingState.
3185 bool mFrameRequestCallbacksScheduled : 1;
3186
3187 enum Type {
3188 eUnknown, // should never be used
3189 eHTML,
3190 eXHTML,
3191 eGenericXML,
3192 eSVG,
3193 eXUL
3194 };
3195
3196 Type mType;
3197
3198 uint8_t mDefaultElementType;
3199
3200 enum Tri {
3201 eTriUnset = 0,
3202 eTriFalse,
3203 eTriTrue
3204 };
3205
3206 Tri mAllowXULXBL;
3207
3208 #ifdef DEBUG
3209 /**
3210 * This is true while FlushPendingLinkUpdates executes. Calls to
3211 * [Un]RegisterPendingLinkUpdate will assert when this is true.
3212 */
3213 bool mIsLinkUpdateRegistrationsForbidden;
3214 #endif
3215
3216 // The document's script global object, the object from which the
3217 // document can get its script context and scope. This is the
3218 // *inner* window object.
3219 nsCOMPtr<nsIScriptGlobalObject> mScriptGlobalObject;
3220
3221 // If mIsStaticDocument is true, mOriginalDocument points to the original
3222 // document.
3223 nsCOMPtr<nsIDocument> mOriginalDocument;
3224
3225 // The bidi options for this document. What this bitfield means is
3226 // defined in nsBidiUtils.h
3227 uint32_t mBidiOptions;
3228
3229 // The sandbox flags on the document. These reflect the value of the sandbox attribute of the
3230 // associated IFRAME or CSP-protectable content, if existent. These are set at load time and
3231 // are immutable - see nsSandboxFlags.h for the possible flags.
3232 uint32_t mSandboxFlags;
3233
3234 nsCString mContentLanguage;
3235
3236 // The channel that got passed to nsDocument::StartDocumentLoad(), if any.
3237 nsCOMPtr<nsIChannel> mChannel;
3238 private:
3239 nsCString mContentType;
3240 nsString mId;
3241 protected:
3242
3243 // The document's security info
3244 nsCOMPtr<nsISupports> mSecurityInfo;
3245
3246 // The channel that failed to load and resulted in an error page.
3247 // This only applies to error pages. Might be null.
3248 nsCOMPtr<nsIChannel> mFailedChannel;
3249
3250 // if this document is part of a multipart document,
3251 // the ID can be used to distinguish it from the other parts.
3252 uint32_t mPartID;
3253
3254 // Cycle collector generation in which we're certain that this document
3255 // won't be collected
3256 uint32_t mMarkedCCGeneration;
3257
3258 nsIPresShell* mPresShell;
3259
3260 nsCOMArray<nsINode> mSubtreeModifiedTargets;
3261 uint32_t mSubtreeModifiedDepth;
3262
3263 // If we're an external resource document, this will be non-null and will
3264 // point to our "display document": the one that all resource lookups should
3265 // go to.
3266 nsCOMPtr<nsIDocument> mDisplayDocument;
3267
3268 uint32_t mEventsSuppressed;
3269
3270 uint32_t mAnimationsPaused;
3271
3272 /**
3273 * The number number of external scripts (ones with the src attribute) that
3274 * have this document as their owner and that are being evaluated right now.
3275 */
3276 uint32_t mExternalScriptsBeingEvaluated;
3277
3278 /**
3279 * The current frame request callback handle
3280 */
3281 int32_t mFrameRequestCallbackCounter;
3282
3283 // Count of live static clones of this document.
3284 uint32_t mStaticCloneCount;
3285
3286 // Array of nodes that have been blocked to prevent user tracking.
3287 // They most likely have had their nsIChannel canceled by the URL
3288 // classifier. (Safebrowsing)
3289 //
3290 // Weak nsINode pointers are used to allow nodes to disappear.
3291 nsTArray<nsWeakPtr> mBlockedTrackingNodes;
3292
3293 // Weak reference to mScriptGlobalObject QI:d to nsPIDOMWindow,
3294 // updated on every set of mScriptGlobalObject.
3295 nsPIDOMWindowInner* mWindow;
3296
3297 nsCOMPtr<nsIDocumentEncoder> mCachedEncoder;
3298
3299 struct FrameRequest;
3300
3301 nsTArray<FrameRequest> mFrameRequestCallbacks;
3302
3303 // This object allows us to evict ourself from the back/forward cache. The
3304 // pointer is non-null iff we're currently in the bfcache.
3305 nsIBFCacheEntry *mBFCacheEntry;
3306
3307 // Our base target.
3308 nsString mBaseTarget;
3309
3310 nsCOMPtr<nsIStructuredCloneContainer> mStateObjectContainer;
3311 nsCOMPtr<nsIVariant> mStateObjectCached;
3312
3313 uint32_t mInSyncOperationCount;
3314
3315 RefPtr<mozilla::dom::XPathEvaluator> mXPathEvaluator;
3316
3317 nsTArray<RefPtr<mozilla::dom::AnonymousContent>> mAnonymousContents;
3318
3319 uint32_t mBlockDOMContentLoaded;
3320
3321 // Our live MediaQueryLists
3322 PRCList mDOMMediaQueryLists;
3323
3324 // Flags for use counters used directly by this document.
3325 std::bitset<mozilla::eUseCounter_Count> mUseCounters;
3326 // Flags for use counters used by any child documents of this document.
3327 std::bitset<mozilla::eUseCounter_Count> mChildDocumentUseCounters;
3328 // Flags for whether we've notified our top-level "page" of a use counter
3329 // for this child document.
3330 std::bitset<mozilla::eUseCounter_Count> mNotifiedPageForUseCounter;
3331
3332 // Whether the user has interacted with the document or not:
3333 bool mUserHasInteracted;
3334
3335 mozilla::TimeStamp mPageUnloadingEventTimeStamp;
3336
3337 RefPtr<mozilla::dom::DocGroup> mDocGroup;
3338 };
3339
NS_DEFINE_STATIC_IID_ACCESSOR(nsIDocument,NS_IDOCUMENT_IID)3340 NS_DEFINE_STATIC_IID_ACCESSOR(nsIDocument, NS_IDOCUMENT_IID)
3341
3342 /**
3343 * mozAutoSubtreeModified batches DOM mutations so that a DOMSubtreeModified
3344 * event is dispatched, if necessary, when the outermost mozAutoSubtreeModified
3345 * object is deleted.
3346 */
3347 class MOZ_STACK_CLASS mozAutoSubtreeModified
3348 {
3349 public:
3350 /**
3351 * @param aSubTreeOwner The document in which a subtree will be modified.
3352 * @param aTarget The target of the possible DOMSubtreeModified event.
3353 * Can be nullptr, in which case mozAutoSubtreeModified
3354 * is just used to batch DOM mutations.
3355 */
3356 mozAutoSubtreeModified(nsIDocument* aSubtreeOwner, nsINode* aTarget)
3357 {
3358 UpdateTarget(aSubtreeOwner, aTarget);
3359 }
3360
3361 ~mozAutoSubtreeModified()
3362 {
3363 UpdateTarget(nullptr, nullptr);
3364 }
3365
3366 void UpdateTarget(nsIDocument* aSubtreeOwner, nsINode* aTarget)
3367 {
3368 if (mSubtreeOwner) {
3369 mSubtreeOwner->MutationEventDispatched(mTarget);
3370 }
3371
3372 mTarget = aTarget;
3373 mSubtreeOwner = aSubtreeOwner;
3374 if (mSubtreeOwner) {
3375 mSubtreeOwner->WillDispatchMutationEvent(mTarget);
3376 }
3377 }
3378
3379 private:
3380 nsCOMPtr<nsINode> mTarget;
3381 nsCOMPtr<nsIDocument> mSubtreeOwner;
3382 };
3383
3384 class MOZ_STACK_CLASS nsAutoSyncOperation
3385 {
3386 public:
3387 explicit nsAutoSyncOperation(nsIDocument* aDocument);
3388 ~nsAutoSyncOperation();
3389 private:
3390 nsCOMArray<nsIDocument> mDocuments;
3391 uint32_t mMicroTaskLevel;
3392 };
3393
3394 // XXX These belong somewhere else
3395 nsresult
3396 NS_NewHTMLDocument(nsIDocument** aInstancePtrResult, bool aLoadedAsData = false);
3397
3398 nsresult
3399 NS_NewXMLDocument(nsIDocument** aInstancePtrResult, bool aLoadedAsData = false,
3400 bool aIsPlainDocument = false);
3401
3402 nsresult
3403 NS_NewSVGDocument(nsIDocument** aInstancePtrResult);
3404
3405 nsresult
3406 NS_NewImageDocument(nsIDocument** aInstancePtrResult);
3407
3408 nsresult
3409 NS_NewVideoDocument(nsIDocument** aInstancePtrResult);
3410
3411 // Note: it's the caller's responsibility to create or get aPrincipal as needed
3412 // -- this method will not attempt to get a principal based on aDocumentURI.
3413 // Also, both aDocumentURI and aBaseURI must not be null.
3414 nsresult
3415 NS_NewDOMDocument(nsIDOMDocument** aInstancePtrResult,
3416 const nsAString& aNamespaceURI,
3417 const nsAString& aQualifiedName,
3418 nsIDOMDocumentType* aDoctype,
3419 nsIURI* aDocumentURI,
3420 nsIURI* aBaseURI,
3421 nsIPrincipal* aPrincipal,
3422 bool aLoadedAsData,
3423 nsIGlobalObject* aEventObject,
3424 DocumentFlavor aFlavor);
3425
3426 // This is used only for xbl documents created from the startup cache.
3427 // Non-cached documents are created in the same manner as xml documents.
3428 nsresult
3429 NS_NewXBLDocument(nsIDOMDocument** aInstancePtrResult,
3430 nsIURI* aDocumentURI,
3431 nsIURI* aBaseURI,
3432 nsIPrincipal* aPrincipal);
3433
3434 nsresult
3435 NS_NewPluginDocument(nsIDocument** aInstancePtrResult);
3436
3437 inline nsIDocument*
GetOwnerDocument()3438 nsINode::GetOwnerDocument() const
3439 {
3440 nsIDocument* ownerDoc = OwnerDoc();
3441
3442 return ownerDoc != this ? ownerDoc : nullptr;
3443 }
3444
3445 inline nsINode*
OwnerDocAsNode()3446 nsINode::OwnerDocAsNode() const
3447 {
3448 return OwnerDoc();
3449 }
3450
3451 inline mozilla::dom::ParentObject
GetParentObject()3452 nsINode::GetParentObject() const
3453 {
3454 mozilla::dom::ParentObject p(OwnerDoc());
3455 // Note that mUseXBLScope is a no-op for chrome, and other places where we
3456 // don't use XBL scopes.
3457 p.mUseXBLScope = IsInAnonymousSubtree() && !IsAnonymousContentInSVGUseSubtree();
3458 return p;
3459 }
3460
3461 #endif /* nsIDocument_h___ */
3462