Coverage Report

Created: 2018-09-25 14:53

/work/obj-fuzz/dist/include/nsIDocument.h
Line
Count
Source (jump to first uncovered line)
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 "mozilla/FlushType.h"           // for enum
10
#include "nsAutoPtr.h"                   // for member
11
#include "nsCOMArray.h"                  // for member
12
#include "nsCompatibility.h"             // for member
13
#include "nsCOMPtr.h"                    // for member
14
#include "nsGkAtoms.h"                   // for static class members
15
#include "nsIApplicationCache.h"
16
#include "nsIApplicationCacheContainer.h"
17
#include "nsIContentViewer.h"
18
#include "nsIDOMXULCommandDispatcher.h"
19
#include "nsIInterfaceRequestor.h"
20
#include "nsILoadContext.h"
21
#include "nsILoadGroup.h"                // for member (in nsCOMPtr)
22
#include "nsINode.h"                     // for base class
23
#include "nsIParser.h"
24
#include "nsIPresShell.h"
25
#include "nsIChannelEventSink.h"
26
#include "nsIProgressEventSink.h"
27
#include "nsISecurityEventSink.h"
28
#include "nsIScriptGlobalObject.h"       // for member (in nsCOMPtr)
29
#include "nsIServiceManager.h"
30
#include "nsIURI.h"                      // for use in inline functions
31
#include "nsIUUIDGenerator.h"
32
#include "nsPIDOMWindow.h"               // for use in inline functions
33
#include "nsPropertyTable.h"             // for member
34
#include "nsStringFwd.h"
35
#include "nsTHashtable.h"                // for member
36
#include "nsURIHashKey.h"
37
#include "mozilla/net/ReferrerPolicy.h"  // for member
38
#include "nsWeakReference.h"
39
#include "mozilla/UseCounter.h"
40
#include "mozilla/WeakPtr.h"
41
#include "Units.h"
42
#include "nsContentListDeclarations.h"
43
#include "nsExpirationTracker.h"
44
#include "nsClassHashtable.h"
45
#include "mozilla/CORSMode.h"
46
#include "mozilla/dom/DispatcherTrait.h"
47
#include "mozilla/dom/DocumentOrShadowRoot.h"
48
#include "mozilla/EnumSet.h"
49
#include "mozilla/LinkedList.h"
50
#include "mozilla/NotNull.h"
51
#include "mozilla/SegmentedVector.h"
52
#include "mozilla/ServoBindingTypes.h"
53
#include "mozilla/StyleSheet.h"
54
#include "mozilla/TimeStamp.h"
55
#include "mozilla/UniquePtr.h"
56
#include <bitset>                        // for member
57
58
// windows.h #defines CreateEvent
59
#ifdef CreateEvent
60
#undef CreateEvent
61
#endif
62
63
#ifdef MOZILLA_INTERNAL_API
64
#include "mozilla/dom/DocumentBinding.h"
65
#else
66
namespace mozilla {
67
namespace dom {
68
class ElementCreationOptionsOrString;
69
} // namespace dom
70
} // namespace mozilla
71
#endif // MOZILLA_INTERNAL_API
72
73
class gfxUserFontSet;
74
class imgIRequest;
75
class nsBindingManager;
76
class nsCachableElementsByNameNodeList;
77
class nsIDocShell;
78
class nsDocShell;
79
class nsDOMNavigationTiming;
80
class nsDOMStyleSheetSetList;
81
class nsFrameLoader;
82
class nsGlobalWindowInner;
83
class nsHTMLCSSStyleSheet;
84
class nsHTMLDocument;
85
class nsHTMLStyleSheet;
86
class nsGenericHTMLElement;
87
class nsAtom;
88
class nsIBFCacheEntry;
89
class nsIChannel;
90
class nsIContent;
91
class nsIContentSink;
92
class nsIDocShell;
93
class nsIDocShellTreeItem;
94
class nsIDocumentEncoder;
95
class nsIDocumentObserver;
96
class nsIHTMLCollection;
97
class nsILayoutHistoryState;
98
class nsILoadContext;
99
class nsIObjectLoadingContent;
100
class nsIObserver;
101
class nsIPrincipal;
102
class nsIRequest;
103
class nsIRunnable;
104
class nsISecurityConsoleMessage;
105
class nsIStreamListener;
106
class nsIStructuredCloneContainer;
107
class nsIURI;
108
class nsIVariant;
109
class nsViewManager;
110
class nsPresContext;
111
class nsRange;
112
class nsSMILAnimationController;
113
class nsSVGElement;
114
class nsTextNode;
115
class nsUnblockOnloadEvent;
116
class nsWindowSizes;
117
class nsDOMCaretPosition;
118
class nsViewportInfo;
119
class nsIGlobalObject;
120
class nsIXULWindow;
121
122
namespace mozilla {
123
class AbstractThread;
124
class CSSStyleSheet;
125
class Encoding;
126
class ErrorResult;
127
class EventStates;
128
class EventListenerManager;
129
class FullscreenExit;
130
class FullscreenRequest;
131
class PendingAnimationTracker;
132
class ServoStyleSet;
133
template<typename> class OwningNonNull;
134
struct URLExtraData;
135
136
namespace css {
137
class Loader;
138
class ImageLoader;
139
class Rule;
140
} // namespace css
141
142
namespace dom {
143
class Animation;
144
class AnonymousContent;
145
class Attr;
146
class BoxObject;
147
class ClientInfo;
148
class ClientState;
149
class CDATASection;
150
class Comment;
151
struct CustomElementDefinition;
152
class DocGroup;
153
class DocumentL10n;
154
class DocumentFragment;
155
class DocumentTimeline;
156
class DocumentType;
157
class DOMImplementation;
158
class DOMIntersectionObserver;
159
class DOMStringList;
160
class Element;
161
struct ElementCreationOptions;
162
class Event;
163
class EventTarget;
164
class FontFaceSet;
165
class FrameRequestCallback;
166
class ImageTracker;
167
class HTMLBodyElement;
168
class HTMLSharedElement;
169
class HTMLImageElement;
170
struct LifecycleCallbackArgs;
171
class Link;
172
class Location;
173
class MediaQueryList;
174
class GlobalObject;
175
class NodeFilter;
176
class NodeIterator;
177
enum class OrientationType : uint8_t;
178
class ProcessingInstruction;
179
class Promise;
180
class ScriptLoader;
181
class Selection;
182
class ServiceWorkerDescriptor;
183
class StyleSheetList;
184
class SVGDocument;
185
class SVGSVGElement;
186
class SVGUseElement;
187
class Touch;
188
class TouchList;
189
class TreeWalker;
190
class XPathEvaluator;
191
class XPathExpression;
192
class XPathNSResolver;
193
class XPathResult;
194
class XULDocument;
195
template<typename> class Sequence;
196
197
template<typename, typename> class CallbackObjectHolder;
198
199
enum class CallerType : uint32_t;
200
201
} // namespace dom
202
} // namespace mozilla
203
204
// Must be kept in sync with xpcom/rust/xpcom/src/interfaces/nonidl.rs
205
#define NS_IDOCUMENT_IID \
206
{ 0xce1f7627, 0x7109, 0x4977, \
207
  { 0xba, 0x77, 0x49, 0x0f, 0xfd, 0xe0, 0x7a, 0xaa } }
208
209
// Enum for requesting a particular type of document when creating a doc
210
enum DocumentFlavor {
211
  DocumentFlavorLegacyGuess, // compat with old code until made HTML5-compliant
212
  DocumentFlavorHTML, // HTMLDocument with HTMLness bit set to true
213
  DocumentFlavorSVG, // SVGDocument
214
  DocumentFlavorPlain, // Just a Document
215
};
216
217
// Document states
218
219
// RTL locale: specific to the XUL localedir attribute
220
0
#define NS_DOCUMENT_STATE_RTL_LOCALE              NS_DEFINE_EVENT_STATE_MACRO(0)
221
// Window activation status
222
0
#define NS_DOCUMENT_STATE_WINDOW_INACTIVE         NS_DEFINE_EVENT_STATE_MACRO(1)
223
224
// Some function forward-declarations
225
class nsContentList;
226
class nsDocumentOnStack;
227
228
class nsDocHeaderData
229
{
230
public:
231
  nsDocHeaderData(nsAtom* aField, const nsAString& aData)
232
    : mField(aField), mData(aData), mNext(nullptr)
233
0
  {
234
0
  }
235
236
  ~nsDocHeaderData(void)
237
0
  {
238
0
    delete mNext;
239
0
  }
240
241
  RefPtr<nsAtom> mField;
242
  nsString mData;
243
  nsDocHeaderData* mNext;
244
};
245
246
class nsExternalResourceMap
247
{
248
  typedef bool (*nsSubDocEnumFunc)(nsIDocument *aDocument, void *aData);
249
250
public:
251
  /**
252
   * A class that represents an external resource load that has begun but
253
   * doesn't have a document yet.  Observers can be registered on this object,
254
   * and will be notified after the document is created.  Observers registered
255
   * after the document has been created will NOT be notified.  When observers
256
   * are notified, the subject will be the newly-created document, the topic
257
   * will be "external-resource-document-created", and the data will be null.
258
   * If document creation fails for some reason, observers will still be
259
   * notified, with a null document pointer.
260
   */
261
  class ExternalResourceLoad : public nsISupports
262
  {
263
  public:
264
0
    virtual ~ExternalResourceLoad() {}
265
266
    void AddObserver(nsIObserver* aObserver)
267
0
    {
268
0
      MOZ_ASSERT(aObserver, "Must have observer");
269
0
      mObservers.AppendElement(aObserver);
270
0
    }
271
272
    const nsTArray<nsCOMPtr<nsIObserver>> & Observers()
273
0
    {
274
0
      return mObservers;
275
0
    }
276
  protected:
277
    AutoTArray<nsCOMPtr<nsIObserver>, 8> mObservers;
278
  };
279
280
  nsExternalResourceMap();
281
282
  /**
283
   * Request an external resource document.  This does exactly what
284
   * nsIDocument::RequestExternalResource is documented to do.
285
   */
286
  nsIDocument* RequestResource(nsIURI* aURI,
287
                               nsIURI* aReferrer,
288
                               uint32_t aReferrerPolicy,
289
                               nsINode* aRequestingNode,
290
                               nsIDocument* aDisplayDocument,
291
                               ExternalResourceLoad** aPendingLoad);
292
293
  /**
294
   * Enumerate the resource documents.  See
295
   * nsIDocument::EnumerateExternalResources.
296
   */
297
  void EnumerateResources(nsSubDocEnumFunc aCallback, void* aData);
298
299
  /**
300
   * Traverse ourselves for cycle-collection
301
   */
302
  void Traverse(nsCycleCollectionTraversalCallback* aCallback) const;
303
304
  /**
305
   * Shut ourselves down (used for cycle-collection unlink), as well
306
   * as for document destruction.
307
   */
308
  void Shutdown()
309
0
  {
310
0
    mPendingLoads.Clear();
311
0
    mMap.Clear();
312
0
    mHaveShutDown = true;
313
0
  }
314
315
  bool HaveShutDown() const
316
0
  {
317
0
    return mHaveShutDown;
318
0
  }
319
320
  // Needs to be public so we can traverse them sanely
321
  struct ExternalResource
322
  {
323
    ~ExternalResource();
324
    nsCOMPtr<nsIDocument> mDocument;
325
    nsCOMPtr<nsIContentViewer> mViewer;
326
    nsCOMPtr<nsILoadGroup> mLoadGroup;
327
  };
328
329
  // Hide all our viewers
330
  void HideViewers();
331
332
  // Show all our viewers
333
  void ShowViewers();
334
335
protected:
336
  class PendingLoad : public ExternalResourceLoad,
337
                      public nsIStreamListener
338
  {
339
0
    ~PendingLoad() {}
340
341
  public:
342
    explicit PendingLoad(nsIDocument* aDisplayDocument) :
343
      mDisplayDocument(aDisplayDocument)
344
0
    {}
345
346
    NS_DECL_ISUPPORTS
347
    NS_DECL_NSISTREAMLISTENER
348
    NS_DECL_NSIREQUESTOBSERVER
349
350
    /**
351
     * Start aURI loading.  This will perform the necessary security checks and
352
     * so forth.
353
     */
354
    nsresult StartLoad(nsIURI* aURI,
355
                       nsIURI* aReferrer,
356
                       uint32_t aReferrerPolicy,
357
                       nsINode* aRequestingNode);
358
    /**
359
     * Set up an nsIContentViewer based on aRequest.  This is guaranteed to
360
     * put null in *aViewer and *aLoadGroup on all failures.
361
     */
362
    nsresult SetupViewer(nsIRequest* aRequest, nsIContentViewer** aViewer,
363
                         nsILoadGroup** aLoadGroup);
364
365
  private:
366
    nsCOMPtr<nsIDocument> mDisplayDocument;
367
    nsCOMPtr<nsIStreamListener> mTargetListener;
368
    nsCOMPtr<nsIURI> mURI;
369
  };
370
  friend class PendingLoad;
371
372
  class LoadgroupCallbacks final : public nsIInterfaceRequestor
373
  {
374
0
    ~LoadgroupCallbacks() {}
375
  public:
376
    explicit LoadgroupCallbacks(nsIInterfaceRequestor* aOtherCallbacks)
377
      : mCallbacks(aOtherCallbacks)
378
0
    {}
379
    NS_DECL_ISUPPORTS
380
    NS_DECL_NSIINTERFACEREQUESTOR
381
  private:
382
    // The only reason it's safe to hold a strong ref here without leaking is
383
    // that the notificationCallbacks on a loadgroup aren't the docshell itself
384
    // but a shim that holds a weak reference to the docshell.
385
    nsCOMPtr<nsIInterfaceRequestor> mCallbacks;
386
387
    // Use shims for interfaces that docshell implements directly so that we
388
    // don't hand out references to the docshell.  The shims should all allow
389
    // getInterface back on us, but other than that each one should only
390
    // implement one interface.
391
392
    // XXXbz I wish we could just derive the _allcaps thing from _i
393
#define DECL_SHIM(_i, _allcaps)                                              \
394
    class _i##Shim final : public nsIInterfaceRequestor,                     \
395
                           public _i                                         \
396
    {                                                                        \
397
0
      ~_i##Shim() {}                                                         \
Unexecuted instantiation: nsExternalResourceMap::LoadgroupCallbacks::nsILoadContextShim::~nsILoadContextShim()
Unexecuted instantiation: nsExternalResourceMap::LoadgroupCallbacks::nsIProgressEventSinkShim::~nsIProgressEventSinkShim()
Unexecuted instantiation: nsExternalResourceMap::LoadgroupCallbacks::nsIChannelEventSinkShim::~nsIChannelEventSinkShim()
Unexecuted instantiation: nsExternalResourceMap::LoadgroupCallbacks::nsISecurityEventSinkShim::~nsISecurityEventSinkShim()
Unexecuted instantiation: nsExternalResourceMap::LoadgroupCallbacks::nsIApplicationCacheContainerShim::~nsIApplicationCacheContainerShim()
398
    public:                                                                  \
399
      _i##Shim(nsIInterfaceRequestor* aIfreq, _i* aRealPtr)                  \
400
        : mIfReq(aIfreq), mRealPtr(aRealPtr)                                 \
401
0
      {                                                                      \
402
0
        NS_ASSERTION(mIfReq, "Expected non-null here");                      \
403
0
        NS_ASSERTION(mRealPtr, "Expected non-null here");                    \
404
0
      }                                                                      \
Unexecuted instantiation: nsExternalResourceMap::LoadgroupCallbacks::nsILoadContextShim::nsILoadContextShim(nsIInterfaceRequestor*, nsILoadContext*)
Unexecuted instantiation: nsExternalResourceMap::LoadgroupCallbacks::nsIProgressEventSinkShim::nsIProgressEventSinkShim(nsIInterfaceRequestor*, nsIProgressEventSink*)
Unexecuted instantiation: nsExternalResourceMap::LoadgroupCallbacks::nsIChannelEventSinkShim::nsIChannelEventSinkShim(nsIInterfaceRequestor*, nsIChannelEventSink*)
Unexecuted instantiation: nsExternalResourceMap::LoadgroupCallbacks::nsISecurityEventSinkShim::nsISecurityEventSinkShim(nsIInterfaceRequestor*, nsISecurityEventSink*)
Unexecuted instantiation: nsExternalResourceMap::LoadgroupCallbacks::nsIApplicationCacheContainerShim::nsIApplicationCacheContainerShim(nsIInterfaceRequestor*, nsIApplicationCacheContainer*)
405
      NS_DECL_ISUPPORTS                                                      \
406
      NS_FORWARD_NSIINTERFACEREQUESTOR(mIfReq->)                             \
407
      NS_FORWARD_##_allcaps(mRealPtr->)                                      \
408
    private:                                                                 \
409
      nsCOMPtr<nsIInterfaceRequestor> mIfReq;                                \
410
      nsCOMPtr<_i> mRealPtr;                                                 \
411
    };
412
413
    DECL_SHIM(nsILoadContext, NSILOADCONTEXT)
414
    DECL_SHIM(nsIProgressEventSink, NSIPROGRESSEVENTSINK)
415
    DECL_SHIM(nsIChannelEventSink, NSICHANNELEVENTSINK)
416
    DECL_SHIM(nsISecurityEventSink, NSISECURITYEVENTSINK)
417
    DECL_SHIM(nsIApplicationCacheContainer, NSIAPPLICATIONCACHECONTAINER)
418
#undef DECL_SHIM
419
  };
420
421
  /**
422
   * Add an ExternalResource for aURI.  aViewer and aLoadGroup might be null
423
   * when this is called if the URI didn't result in an XML document.  This
424
   * function makes sure to remove the pending load for aURI, if any, from our
425
   * hashtable, and to notify its observers, if any.
426
   */
427
  nsresult AddExternalResource(nsIURI* aURI, nsIContentViewer* aViewer,
428
                               nsILoadGroup* aLoadGroup,
429
                               nsIDocument* aDisplayDocument);
430
431
  nsClassHashtable<nsURIHashKey, ExternalResource> mMap;
432
  nsRefPtrHashtable<nsURIHashKey, PendingLoad> mPendingLoads;
433
  bool mHaveShutDown;
434
};
435
436
//----------------------------------------------------------------------
437
438
// For classifying a flash document based on its principal.
439
class PrincipalFlashClassifier;
440
441
// Document interface.  This is implemented by all document objects in
442
// Gecko.
443
class nsIDocument : public nsINode,
444
                    public mozilla::dom::DocumentOrShadowRoot,
445
                    public mozilla::dom::DispatcherTrait
446
{
447
  typedef mozilla::dom::GlobalObject GlobalObject;
448
449
protected:
450
  using Encoding = mozilla::Encoding;
451
  template <typename T> using NotNull = mozilla::NotNull<T>;
452
453
public:
454
  typedef nsExternalResourceMap::ExternalResourceLoad ExternalResourceLoad;
455
  typedef mozilla::FullscreenRequest FullscreenRequest;
456
  typedef mozilla::net::ReferrerPolicy ReferrerPolicyEnum;
457
  typedef mozilla::dom::Element Element;
458
459
  NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOCUMENT_IID)
460
461
#ifdef MOZILLA_INTERNAL_API
462
  nsIDocument();
463
#endif
464
465
  // This helper class must be set when we dispatch beforeunload and unload
466
  // events in order to avoid unterminate sync XHRs.
467
  class MOZ_RAII PageUnloadingEventTimeStamp
468
  {
469
    nsCOMPtr<nsIDocument> mDocument;
470
    bool mSet;
471
472
  public:
473
    explicit PageUnloadingEventTimeStamp(nsIDocument* aDocument)
474
      : mDocument(aDocument)
475
      , mSet(false)
476
0
    {
477
0
      MOZ_ASSERT(aDocument);
478
0
      if (mDocument->mPageUnloadingEventTimeStamp.IsNull()) {
479
0
        mDocument->SetPageUnloadingEventTimeStamp();
480
0
        mSet = true;
481
0
      }
482
0
    }
483
484
    ~PageUnloadingEventTimeStamp()
485
0
    {
486
0
      if (mSet) {
487
0
        mDocument->CleanUnloadEventsTimeStamp();
488
0
      }
489
0
    }
490
  };
491
492
  /**
493
   * Let the document know that we're starting to load data into it.
494
   * @param aCommand The parser command. Must not be null.
495
   *                 XXXbz It's odd to have that here.
496
   * @param aChannel The channel the data will come from. The channel must be
497
   *                 able to report its Content-Type.
498
   * @param aLoadGroup The loadgroup this document should use from now on.
499
   *                   Note that the document might not be the only thing using
500
   *                   this loadgroup.
501
   * @param aContainer The container this document is in.  This may be null.
502
   *                   XXXbz maybe we should make it more explicit (eg make the
503
   *                   container an nsIWebNavigation or nsIDocShell or
504
   *                   something)?
505
   * @param [out] aDocListener the listener to pump data from the channel into.
506
   *                           Generally this will be the parser this document
507
   *                           sets up, or some sort of data-handler for media
508
   *                           documents.
509
   * @param aReset whether the document should call Reset() on itself.  If this
510
   *               is false, the document will NOT set its principal to the
511
   *               channel's owner, will not clear any event listeners that are
512
   *               already set on it, etc.
513
   * @param aSink The content sink to use for the data.  If this is null and
514
   *              the document needs a content sink, it will create one based
515
   *              on whatever it knows about the data it's going to load.
516
   *              This MUST be null if the underlying document is an HTML
517
   *              document. Even in the XML case, please don't add new calls
518
   *              with non-null sink.
519
   *
520
   * Once this has been called, the document will return false for
521
   * MayStartLayout() until SetMayStartLayout(true) is called on it.  Making
522
   * sure this happens is the responsibility of the caller of
523
   * StartDocumentLoad().
524
   */
525
  virtual nsresult StartDocumentLoad(const char* aCommand,
526
                                     nsIChannel* aChannel,
527
                                     nsILoadGroup* aLoadGroup,
528
                                     nsISupports* aContainer,
529
                                     nsIStreamListener **aDocListener,
530
                                     bool aReset,
531
                                     nsIContentSink* aSink = nullptr) = 0;
532
  virtual void StopDocumentLoad() = 0;
533
534
0
  virtual void SetSuppressParserErrorElement(bool aSuppress) {}
535
0
  virtual bool SuppressParserErrorElement() { return false; }
536
537
0
  virtual void SetSuppressParserErrorConsoleMessages(bool aSuppress) {}
538
0
  virtual bool SuppressParserErrorConsoleMessages() { return false; }
539
540
  // nsINode
541
  bool IsNodeOfType(uint32_t aFlags) const final;
542
  nsresult InsertChildBefore(nsIContent* aKid, nsIContent* aBeforeThis,
543
                             bool aNotify) override;
544
  void RemoveChildNode(nsIContent* aKid, bool aNotify) final;
545
  nsresult Clone(mozilla::dom::NodeInfo* aNodeInfo,
546
                 nsINode **aResult) const override
547
0
  {
548
0
    return NS_ERROR_NOT_IMPLEMENTED;
549
0
  }
550
551
  /**
552
   * Signal that the document title may have changed
553
   * (see nsDocument::GetTitle).
554
   * @param aBoundTitleElement true if an HTML or SVG <title> element
555
   * has just been bound to the document.
556
   */
557
  void NotifyPossibleTitleChange(bool aBoundTitleElement);
558
559
  /**
560
   * Return the URI for the document. May return null.
561
   *
562
   * The value returned corresponds to the "document's address" in
563
   * HTML5.  As such, it may change over the lifetime of the document, for
564
   * instance as a result of the user navigating to a fragment identifier on
565
   * the page, or as a result to a call to pushState() or replaceState().
566
   *
567
   * https://html.spec.whatwg.org/multipage/dom.html#the-document%27s-address
568
   */
569
  nsIURI* GetDocumentURI() const
570
0
  {
571
0
    return mDocumentURI;
572
0
  }
573
574
  /**
575
   * Return the original URI of the document.  This is the same as the
576
   * document's URI unless that has changed from its original value (for
577
   * example, due to history.pushState() or replaceState() being invoked on the
578
   * document).
579
   *
580
   * This method corresponds to the "creation URL" in HTML5 and, once set,
581
   * doesn't change over the lifetime of the document.
582
   *
583
   * https://html.spec.whatwg.org/multipage/webappapis.html#creation-url
584
   */
585
  nsIURI* GetOriginalURI() const
586
0
  {
587
0
    return mOriginalURI;
588
0
  }
589
590
  /**
591
   * Set the URI for the document.  This also sets the document's original URI,
592
   * if it's null.
593
   */
594
  void SetDocumentURI(nsIURI* aURI);
595
596
  /**
597
   * Set the URI for the document loaded via XHR, when accessed from
598
   * chrome privileged script.
599
   */
600
  void SetChromeXHRDocURI(nsIURI* aURI)
601
0
  {
602
0
    mChromeXHRDocURI = aURI;
603
0
  }
604
605
  /**
606
   * Set the base URI for the document loaded via XHR, when accessed from
607
   * chrome privileged script.
608
   */
609
  void SetChromeXHRDocBaseURI(nsIURI* aURI)
610
0
  {
611
0
    mChromeXHRDocBaseURI = aURI;
612
0
  }
613
614
  /**
615
   * Set referrer policy and upgrade-insecure-requests flags
616
   */
617
  void ApplySettingsFromCSP(bool aSpeculative);
618
619
  already_AddRefed<nsIParser> CreatorParserOrNull()
620
0
  {
621
0
    nsCOMPtr<nsIParser> parser = mParser;
622
0
    return parser.forget();
623
0
  }
624
625
  /**
626
   * Return the referrer policy of the document. Return "default" if there's no
627
   * valid meta referrer tag found in the document.
628
   */
629
  ReferrerPolicyEnum GetReferrerPolicy() const
630
0
  {
631
0
    return mReferrerPolicy;
632
0
  }
633
634
  /**
635
   * GetReferrerPolicy() for Document.webidl.
636
   */
637
  uint32_t ReferrerPolicy() const
638
0
  {
639
0
    return GetReferrerPolicy();
640
0
  }
641
642
  /**
643
   * If true, this flag indicates that all mixed content subresource
644
   * loads for this document (and also embeded browsing contexts) will
645
   * be blocked.
646
   */
647
  bool GetBlockAllMixedContent(bool aPreload) const
648
0
  {
649
0
    if (aPreload) {
650
0
      return mBlockAllMixedContentPreloads;
651
0
    }
652
0
    return mBlockAllMixedContent;
653
0
  }
654
655
  /**
656
   * If true, this flag indicates that all subresource loads for this
657
   * document need to be upgraded from http to https.
658
   * This flag becomes true if the CSP of the document itself, or any
659
   * of the document's ancestors up to the toplevel document makes use
660
   * of the CSP directive 'upgrade-insecure-requests'.
661
   */
662
  bool GetUpgradeInsecureRequests(bool aPreload) const
663
0
  {
664
0
    if (aPreload) {
665
0
      return mUpgradeInsecurePreloads;
666
0
    }
667
0
    return mUpgradeInsecureRequests;
668
0
  }
669
670
0
  void SetReferrer(const nsACString& aReferrer) {
671
0
    mReferrer = aReferrer;
672
0
  }
673
674
  /**
675
   * Set the principal responsible for this document.  Chances are,
676
   * you do not want to be using this.
677
   */
678
  void SetPrincipal(nsIPrincipal* aPrincipal);
679
680
  /**
681
   * Get the list of ancestor principals for a document.  This is the same as
682
   * the ancestor list for the document's docshell the last time SetContainer()
683
   * was called with a non-null argument. See the documentation for the
684
   * corresponding getter in docshell for how this list is determined.  We store
685
   * a copy of the list, because we may lose the ability to reach our docshell
686
   * before people stop asking us for this information.
687
   */
688
  const nsTArray<nsCOMPtr<nsIPrincipal>>& AncestorPrincipals() const
689
0
  {
690
0
    return mAncestorPrincipals;
691
0
  }
692
693
  /**
694
   * Get the list of ancestor outerWindowIDs for a document that correspond to
695
   * the ancestor principals (see above for more details).
696
   */
697
  const nsTArray<uint64_t>& AncestorOuterWindowIDs() const
698
0
  {
699
0
    return mAncestorOuterWindowIDs;
700
0
  }
701
702
  /**
703
   * Return the LoadGroup for the document. May return null.
704
   */
705
  already_AddRefed<nsILoadGroup> GetDocumentLoadGroup() const
706
0
  {
707
0
    nsCOMPtr<nsILoadGroup> group = do_QueryReferent(mDocumentLoadGroup);
708
0
    return group.forget();
709
0
  }
710
711
  /**
712
   * Return the fallback base URL for this document, as defined in the HTML
713
   * specification.  Note that this can return null if there is no document URI.
714
   *
715
   * XXXbz: This doesn't implement the bits for about:blank yet.
716
   */
717
  nsIURI* GetFallbackBaseURI() const
718
0
  {
719
0
    if (mIsSrcdocDocument && mParentDocument) {
720
0
      return mParentDocument->GetDocBaseURI();
721
0
    }
722
0
    return mDocumentURI;
723
0
  }
724
725
  /**
726
   * Return the base URI for relative URIs in the document (the document uri
727
   * unless it's overridden by SetBaseURI, HTML <base> tags, etc.).  The
728
   * returned URI could be null if there is no document URI.  If the document is
729
   * a srcdoc document and has no explicit base URL, return the parent
730
   * document's base URL.
731
   */
732
  nsIURI* GetDocBaseURI() const
733
0
  {
734
0
    if (mDocumentBaseURI) {
735
0
      return mDocumentBaseURI;
736
0
    }
737
0
    return GetFallbackBaseURI();
738
0
  }
739
740
  already_AddRefed<nsIURI> GetBaseURI(bool aTryUseXHRDocBaseURI = false) const final;
741
742
  void SetBaseURI(nsIURI* aURI);
743
744
  /**
745
   * Return the URL data which style system needs for resolving url value.
746
   * This method attempts to use the cached object in mCachedURLData, but
747
   * if the base URI, document URI, or principal has changed since last
748
   * call to this function, or the function is called the first time for
749
   * the document, a new one is created.
750
   */
751
  mozilla::URLExtraData* DefaultStyleAttrURLData();
752
753
  /**
754
   * Get/Set the base target of a link in a document.
755
   */
756
  void GetBaseTarget(nsAString& aBaseTarget) const
757
0
  {
758
0
    aBaseTarget = mBaseTarget;
759
0
  }
760
761
0
  void SetBaseTarget(const nsString& aBaseTarget) {
762
0
    mBaseTarget = aBaseTarget;
763
0
  }
764
765
  /**
766
   * Return a standard name for the document's character set.
767
   */
768
  NotNull<const Encoding*> GetDocumentCharacterSet() const
769
0
  {
770
0
    return mCharacterSet;
771
0
  }
772
773
  /**
774
   * Set the document's character encoding.
775
   */
776
  virtual void SetDocumentCharacterSet(NotNull<const Encoding*> aEncoding);
777
778
  int32_t GetDocumentCharacterSetSource() const
779
0
  {
780
0
    return mCharacterSetSource;
781
0
  }
782
783
  // This method MUST be called before SetDocumentCharacterSet if
784
  // you're planning to call both.
785
  void SetDocumentCharacterSetSource(int32_t aCharsetSource)
786
0
  {
787
0
    mCharacterSetSource = aCharsetSource;
788
0
  }
789
790
  /**
791
   * Get the Content-Type of this document.
792
   */
793
  void GetContentType(nsAString& aContentType);
794
795
  /**
796
   * Set the Content-Type of this document.
797
   */
798
  virtual void SetContentType(const nsAString& aContentType);
799
800
  /**
801
   * Return the language of this document.
802
   */
803
  void GetContentLanguage(nsAString& aContentLanguage) const
804
0
  {
805
0
    CopyASCIItoUTF16(mContentLanguage, aContentLanguage);
806
0
  }
807
808
  // The states BidiEnabled and MathMLEnabled should persist across multiple views
809
  // (screen, print) of the same document.
810
811
  /**
812
   * Check if the document contains bidi data.
813
   * If so, we have to apply the Unicode Bidi Algorithm.
814
   */
815
  bool GetBidiEnabled() const
816
0
  {
817
0
    return mBidiEnabled;
818
0
  }
819
820
  /**
821
   * Indicate the document contains bidi data.
822
   * Currently, we cannot disable bidi, because once bidi is enabled,
823
   * it affects a frame model irreversibly, and plays even though
824
   * the document no longer contains bidi data.
825
   */
826
  void SetBidiEnabled()
827
0
  {
828
0
    mBidiEnabled = true;
829
0
  }
830
831
  void SetMathMLEnabled()
832
0
  {
833
0
    mMathMLEnabled = true;
834
0
  }
835
836
  /**
837
   * Ask this document whether it's the initial document in its window.
838
   */
839
  bool IsInitialDocument() const
840
0
  {
841
0
    return mIsInitialDocumentInWindow;
842
0
  }
843
844
  /**
845
   * Tell this document that it's the initial document in its window.  See
846
   * comments on mIsInitialDocumentInWindow for when this should be called.
847
   */
848
  void SetIsInitialDocument(bool aIsInitialDocument)
849
0
  {
850
0
    mIsInitialDocumentInWindow = aIsInitialDocument;
851
0
  }
852
853
  /**
854
   * Normally we assert if a runnable labeled with one DocGroup touches data
855
   * from another DocGroup. Calling IgnoreDocGroupMismatches() on a document
856
   * means that we can touch that document from any DocGroup without asserting.
857
   */
858
  void IgnoreDocGroupMismatches()
859
0
  {
860
0
    mIgnoreDocGroupMismatches = true;
861
0
  }
862
863
  /**
864
   * Get the bidi options for this document.
865
   * @see nsBidiUtils.h
866
   */
867
  uint32_t GetBidiOptions() const
868
0
  {
869
0
    return mBidiOptions;
870
0
  }
871
872
  /**
873
   * Set the bidi options for this document.  This just sets the bits;
874
   * callers are expected to take action as needed if they want this
875
   * change to actually change anything immediately.
876
   * @see nsBidiUtils.h
877
   */
878
  void SetBidiOptions(uint32_t aBidiOptions)
879
0
  {
880
0
    mBidiOptions = aBidiOptions;
881
0
  }
882
883
  /**
884
   * Get the has mixed active content loaded flag for this document.
885
   */
886
  bool GetHasMixedActiveContentLoaded()
887
0
  {
888
0
    return mHasMixedActiveContentLoaded;
889
0
  }
890
891
  /**
892
   * Set the has mixed active content loaded flag for this document.
893
   */
894
  void SetHasMixedActiveContentLoaded(bool aHasMixedActiveContentLoaded)
895
0
  {
896
0
    mHasMixedActiveContentLoaded = aHasMixedActiveContentLoaded;
897
0
  }
898
899
  /**
900
   * Get mixed active content blocked flag for this document.
901
   */
902
  bool GetHasMixedActiveContentBlocked()
903
0
  {
904
0
    return mHasMixedActiveContentBlocked;
905
0
  }
906
907
  /**
908
   * Set the mixed active content blocked flag for this document.
909
   */
910
  void SetHasMixedActiveContentBlocked(bool aHasMixedActiveContentBlocked)
911
0
  {
912
0
    mHasMixedActiveContentBlocked = aHasMixedActiveContentBlocked;
913
0
  }
914
915
  /**
916
   * Get the has mixed display content loaded flag for this document.
917
   */
918
  bool GetHasMixedDisplayContentLoaded()
919
0
  {
920
0
    return mHasMixedDisplayContentLoaded;
921
0
  }
922
923
  /**
924
   * Set the has mixed display content loaded flag for this document.
925
   */
926
  void SetHasMixedDisplayContentLoaded(bool aHasMixedDisplayContentLoaded)
927
0
  {
928
0
    mHasMixedDisplayContentLoaded = aHasMixedDisplayContentLoaded;
929
0
  }
930
931
  /**
932
   * Get mixed display content blocked flag for this document.
933
   */
934
  bool GetHasMixedDisplayContentBlocked()
935
0
  {
936
0
    return mHasMixedDisplayContentBlocked;
937
0
  }
938
939
  /**
940
   * Set the mixed display content blocked flag for this document.
941
   */
942
  void SetHasMixedDisplayContentBlocked(bool aHasMixedDisplayContentBlocked)
943
0
  {
944
0
    mHasMixedDisplayContentBlocked = aHasMixedDisplayContentBlocked;
945
0
  }
946
947
  /**
948
   * Set the mixed content object subrequest flag for this document.
949
   */
950
  void SetHasMixedContentObjectSubrequest(bool aHasMixedContentObjectSubrequest)
951
0
  {
952
0
    mHasMixedContentObjectSubrequest = aHasMixedContentObjectSubrequest;
953
0
  }
954
955
  /**
956
   * Set CSP flag for this document.
957
   */
958
  void SetHasCSP(bool aHasCSP)
959
0
  {
960
0
    mHasCSP = aHasCSP;
961
0
  }
962
963
  /**
964
   * Set unsafe-inline CSP flag for this document.
965
   */
966
  void SetHasUnsafeInlineCSP(bool aHasUnsafeInlineCSP)
967
0
  {
968
0
    mHasUnsafeInlineCSP = aHasUnsafeInlineCSP;
969
0
  }
970
971
  /**
972
   * Set unsafe-eval CSP flag for this document.
973
   */
974
  void SetHasUnsafeEvalCSP(bool aHasUnsafeEvalCSP)
975
0
  {
976
0
    mHasUnsafeEvalCSP = aHasUnsafeEvalCSP;
977
0
  }
978
979
  /**
980
   * Get tracking content blocked flag for this document.
981
   */
982
  bool GetHasTrackingContentBlocked()
983
0
  {
984
0
    return mHasTrackingContentBlocked;
985
0
  }
986
987
  /**
988
   * Get slow tracking content blocked flag for this document.
989
   */
990
  bool GetHasSlowTrackingContentBlocked()
991
0
  {
992
0
    return mHasSlowTrackingContentBlocked;
993
0
  }
994
995
  /**
996
   * Get all cookies blocked flag for this document.
997
   */
998
  bool GetHasAllCookiesBlocked()
999
0
  {
1000
0
    return mHasAllCookiesBlocked;
1001
0
  }
1002
1003
  /**
1004
   * Get tracking cookies blocked flag for this document.
1005
   */
1006
  bool GetHasTrackingCookiesBlocked()
1007
0
  {
1008
0
    return mHasTrackingCookiesBlocked;
1009
0
  }
1010
1011
  /**
1012
   * Get third-party cookies blocked flag for this document.
1013
   */
1014
  bool GetHasForeignCookiesBlocked()
1015
0
  {
1016
0
    return mHasForeignCookiesBlocked;
1017
0
  }
1018
1019
  /**
1020
   * Get cookies blocked by site permission flag for this document.
1021
   */
1022
  bool GetHasCookiesBlockedByPermission()
1023
0
  {
1024
0
    return mHasCookiesBlockedByPermission;
1025
0
  }
1026
1027
  /**
1028
   * Set the tracking content blocked flag for this document.
1029
   */
1030
  void SetHasTrackingContentBlocked(bool aHasTrackingContentBlocked)
1031
0
  {
1032
0
    mHasTrackingContentBlocked = aHasTrackingContentBlocked;
1033
0
  }
1034
1035
  /**
1036
   * Set the slow tracking content blocked flag for this document.
1037
   */
1038
  void SetHasSlowTrackingContentBlocked(bool aHasSlowTrackingContentBlocked)
1039
0
  {
1040
0
    mHasSlowTrackingContentBlocked = aHasSlowTrackingContentBlocked;
1041
0
  }
1042
1043
  /**
1044
   * Set the all cookies blocked flag for this document.
1045
   */
1046
  void SetHasAllCookiesBlocked(bool aHasAllCookiesBlocked)
1047
0
  {
1048
0
    mHasAllCookiesBlocked = aHasAllCookiesBlocked;
1049
0
  }
1050
1051
  /**
1052
   * Set the tracking cookies blocked flag for this document.
1053
   */
1054
  void SetHasTrackingCookiesBlocked(bool aHasTrackingCookiesBlocked)
1055
0
  {
1056
0
    mHasTrackingCookiesBlocked = aHasTrackingCookiesBlocked;
1057
0
  }
1058
1059
  /**
1060
   * Set the third-party cookies blocked flag for this document.
1061
   */
1062
  void SetHasForeignCookiesBlocked(bool aHasForeignCookiesBlocked)
1063
0
  {
1064
0
    mHasForeignCookiesBlocked = aHasForeignCookiesBlocked;
1065
0
  }
1066
1067
  /**
1068
   * Set the cookies blocked by site permission flag for this document.
1069
   */
1070
  void SetHasCookiesBlockedByPermission(bool aHasCookiesBlockedByPermission)
1071
0
  {
1072
0
    mHasCookiesBlockedByPermission = aHasCookiesBlockedByPermission;
1073
0
  }
1074
1075
  /**
1076
   * Get tracking content loaded flag for this document.
1077
   */
1078
  bool GetHasTrackingContentLoaded()
1079
0
  {
1080
0
    return mHasTrackingContentLoaded;
1081
0
  }
1082
1083
  /**
1084
   * Set the tracking content loaded flag for this document.
1085
   */
1086
  void SetHasTrackingContentLoaded(bool aHasTrackingContentLoaded)
1087
0
  {
1088
0
    mHasTrackingContentLoaded = aHasTrackingContentLoaded;
1089
0
  }
1090
1091
  /**
1092
   * Get the sandbox flags for this document.
1093
   * @see nsSandboxFlags.h for the possible flags
1094
   */
1095
  uint32_t GetSandboxFlags() const
1096
0
  {
1097
0
    return mSandboxFlags;
1098
0
  }
1099
1100
  /**
1101
   * Get string representation of sandbox flags (null if no flags are set)
1102
   */
1103
  void GetSandboxFlagsAsString(nsAString& aFlags);
1104
1105
  /**
1106
   * Set the sandbox flags for this document.
1107
   * @see nsSandboxFlags.h for the possible flags
1108
   */
1109
  void SetSandboxFlags(uint32_t sandboxFlags)
1110
0
  {
1111
0
    mSandboxFlags = sandboxFlags;
1112
0
  }
1113
1114
  /**
1115
   * Called when the document was decoded as UTF-8 and decoder encountered no
1116
   * errors.
1117
   */
1118
  void EnableEncodingMenu()
1119
0
  {
1120
0
    mEncodingMenuDisabled = false;
1121
0
  }
1122
1123
  /**
1124
   * Access HTTP header data (this may also get set from other
1125
   * sources, like HTML META tags).
1126
   */
1127
  void GetHeaderData(nsAtom* aHeaderField, nsAString& aData) const;
1128
  void SetHeaderData(nsAtom* aheaderField, const nsAString& aData);
1129
1130
  /**
1131
   * Create a new presentation shell that will use aContext for its
1132
   * presentation context (presentation contexts <b>must not</b> be
1133
   * shared among multiple presentation shells). The caller of this
1134
   * method is responsible for calling BeginObservingDocument() on the
1135
   * presshell if the presshell should observe document mutations.
1136
   */
1137
  already_AddRefed<nsIPresShell> CreateShell(
1138
    nsPresContext* aContext,
1139
    nsViewManager* aViewManager,
1140
    mozilla::UniquePtr<mozilla::ServoStyleSet> aStyleSet);
1141
  void DeleteShell();
1142
1143
  nsIPresShell* GetShell() const
1144
0
  {
1145
0
    return GetBFCacheEntry() ? nullptr : mPresShell;
1146
0
  }
1147
1148
  nsIPresShell* GetObservingShell() const
1149
0
  {
1150
0
    return mPresShell && mPresShell->IsObservingDocument()
1151
0
      ? mPresShell : nullptr;
1152
0
  }
1153
1154
  // Return whether the presshell for this document is safe to flush.
1155
  bool IsSafeToFlush() const;
1156
1157
  nsPresContext* GetPresContext() const
1158
0
  {
1159
0
    nsIPresShell* shell = GetShell();
1160
0
    return shell ? shell->GetPresContext() : nullptr;
1161
0
  }
1162
1163
  bool HasShellOrBFCacheEntry() const
1164
0
  {
1165
0
    return mPresShell || mBFCacheEntry;
1166
0
  }
1167
1168
  // Instead using this method, what you probably want is
1169
  // RemoveFromBFCacheSync() as we do in MessagePort and BroadcastChannel.
1170
  void DisallowBFCaching()
1171
0
  {
1172
0
    NS_ASSERTION(!mBFCacheEntry, "We're already in the bfcache!");
1173
0
    mBFCacheDisallowed = true;
1174
0
  }
1175
1176
  bool IsBFCachingAllowed() const
1177
0
  {
1178
0
    return !mBFCacheDisallowed;
1179
0
  }
1180
1181
  // Accepts null to clear the BFCache entry too.
1182
  void SetBFCacheEntry(nsIBFCacheEntry* aEntry);
1183
1184
  nsIBFCacheEntry* GetBFCacheEntry() const
1185
0
  {
1186
0
    return mBFCacheEntry;
1187
0
  }
1188
1189
  /**
1190
   * Return the parent document of this document. Will return null
1191
   * unless this document is within a compound document and has a
1192
   * parent. Note that this parent chain may cross chrome boundaries.
1193
   */
1194
  nsIDocument *GetParentDocument() const
1195
0
  {
1196
0
    return mParentDocument;
1197
0
  }
1198
1199
  /**
1200
   * Set the parent document of this document.
1201
   */
1202
  void SetParentDocument(nsIDocument* aParent)
1203
0
  {
1204
0
    mParentDocument = aParent;
1205
0
    if (aParent) {
1206
0
      mIgnoreDocGroupMismatches = aParent->mIgnoreDocGroupMismatches;
1207
0
    }
1208
0
  }
1209
1210
  /**
1211
   * Are plugins allowed in this document ?
1212
   */
1213
  bool GetAllowPlugins();
1214
1215
  /**
1216
   * Set the sub document for aContent to aSubDoc.
1217
   */
1218
  nsresult SetSubDocumentFor(Element* aContent, nsIDocument* aSubDoc);
1219
1220
  /**
1221
   * Get the sub document for aContent
1222
   */
1223
  nsIDocument* GetSubDocumentFor(nsIContent* aContent) const;
1224
1225
  /**
1226
   * Find the content node for which aDocument is a sub document.
1227
   */
1228
  Element* FindContentForSubDocument(nsIDocument* aDocument) const;
1229
1230
  /**
1231
   * Return the doctype for this document.
1232
   */
1233
  mozilla::dom::DocumentType* GetDoctype() const;
1234
1235
  /**
1236
   * Return the root element for this document.
1237
   */
1238
  Element* GetRootElement() const;
1239
1240
  mozilla::dom::Selection* GetSelection(mozilla::ErrorResult& aRv);
1241
1242
  already_AddRefed<mozilla::dom::Promise>
1243
    HasStorageAccess(mozilla::ErrorResult& aRv);
1244
  already_AddRefed<mozilla::dom::Promise>
1245
    RequestStorageAccess(mozilla::ErrorResult& aRv);
1246
1247
  /**
1248
   * Gets the event target to dispatch key events to if there is no focused
1249
   * content in the document.
1250
   */
1251
  virtual nsIContent* GetUnfocusedKeyEventTarget();
1252
1253
  /**
1254
   * Retrieve information about the viewport as a data structure.
1255
   * This will return information in the viewport META data section
1256
   * of the document. This can be used in lieu of ProcessViewportInfo(),
1257
   * which places the viewport information in the document header instead
1258
   * of returning it directly.
1259
   *
1260
   * @param aDisplaySize size of the on-screen display area for this
1261
   * document, in device pixels.
1262
   *
1263
   * NOTE: If the site is optimized for mobile (via the doctype), this
1264
   * will return viewport information that specifies default information.
1265
   */
1266
  nsViewportInfo GetViewportInfo(const mozilla::ScreenIntSize& aDisplaySize);
1267
1268
  /**
1269
   * It updates the viewport overflow type with the given two widths
1270
   * and the viewport setting of the document.
1271
   * This should only be called when there is out-of-reach overflow
1272
   * happens on the viewport, i.e. the viewport should be using
1273
   * `overflow: hidden`. And it should only be called on a top level
1274
   * content document.
1275
   */
1276
  void UpdateViewportOverflowType(nscoord aScrolledWidth,
1277
                                  nscoord aScrollportWidth);
1278
1279
  /**
1280
   * True iff this doc will ignore manual character encoding overrides.
1281
   */
1282
0
  virtual bool WillIgnoreCharsetOverride() {
1283
0
    return true;
1284
0
  }
1285
1286
  /**
1287
   * Return whether the document was created by a srcdoc iframe.
1288
   */
1289
0
  bool IsSrcdocDocument() const {
1290
0
    return mIsSrcdocDocument;
1291
0
  }
1292
1293
  /**
1294
   * Sets whether the document was created by a srcdoc iframe.
1295
   */
1296
0
  void SetIsSrcdocDocument(bool aIsSrcdocDocument) {
1297
0
    mIsSrcdocDocument = aIsSrcdocDocument;
1298
0
  }
1299
1300
  /*
1301
   * Gets the srcdoc string from within the channel (assuming both exist).
1302
   * Returns a void string if this isn't a srcdoc document or if
1303
   * the channel has not been set.
1304
   */
1305
  nsresult GetSrcdocData(nsAString& aSrcdocData);
1306
1307
0
  bool DidDocumentOpen() {
1308
0
    return mDidDocumentOpen;
1309
0
  }
1310
1311
  already_AddRefed<mozilla::dom::AnonymousContent>
1312
  InsertAnonymousContent(mozilla::dom::Element& aElement,
1313
                         mozilla::ErrorResult& aError);
1314
  void RemoveAnonymousContent(mozilla::dom::AnonymousContent& aContent,
1315
                              mozilla::ErrorResult& aError);
1316
  /**
1317
   * If aNode is a descendant of anonymous content inserted by
1318
   * InsertAnonymousContent, this method returns the root element of the
1319
   * inserted anonymous content (in other words, the clone of the aElement
1320
   * that was passed to InsertAnonymousContent).
1321
   */
1322
  Element* GetAnonRootIfInAnonymousContentContainer(nsINode* aNode) const;
1323
0
  nsTArray<RefPtr<mozilla::dom::AnonymousContent>>& GetAnonymousContents() {
1324
0
    return mAnonymousContents;
1325
0
  }
1326
1327
  mozilla::TimeStamp GetPageUnloadingEventTimeStamp() const
1328
0
  {
1329
0
    if (!mParentDocument) {
1330
0
      return mPageUnloadingEventTimeStamp;
1331
0
    }
1332
0
1333
0
    mozilla::TimeStamp parentTimeStamp(mParentDocument->GetPageUnloadingEventTimeStamp());
1334
0
    if (parentTimeStamp.IsNull()) {
1335
0
      return mPageUnloadingEventTimeStamp;
1336
0
    }
1337
0
1338
0
    if (!mPageUnloadingEventTimeStamp ||
1339
0
        parentTimeStamp < mPageUnloadingEventTimeStamp) {
1340
0
      return parentTimeStamp;
1341
0
    }
1342
0
1343
0
    return mPageUnloadingEventTimeStamp;
1344
0
  }
1345
1346
  void NotifyLayerManagerRecreated();
1347
1348
  /**
1349
   * Add an SVG element to the list of elements that need
1350
   * their mapped attributes resolved to a Servo declaration block.
1351
   *
1352
   * These are weak pointers, please manually unschedule them when an element
1353
   * is removed.
1354
   */
1355
  void ScheduleSVGForPresAttrEvaluation(nsSVGElement* aSVG)
1356
0
  {
1357
0
    mLazySVGPresElements.PutEntry(aSVG);
1358
0
  }
1359
1360
  // Unschedule an element scheduled by ScheduleFrameRequestCallback (e.g. for
1361
  // when it is destroyed)
1362
  void UnscheduleSVGForPresAttrEvaluation(nsSVGElement* aSVG)
1363
0
  {
1364
0
    mLazySVGPresElements.RemoveEntry(aSVG);
1365
0
  }
1366
1367
  // Resolve all SVG pres attrs scheduled in ScheduleSVGForPresAttrEvaluation
1368
  void ResolveScheduledSVGPresAttrs();
1369
1370
  mozilla::Maybe<mozilla::dom::ClientInfo> GetClientInfo() const;
1371
  mozilla::Maybe<mozilla::dom::ClientState> GetClientState() const;
1372
  mozilla::Maybe<mozilla::dom::ServiceWorkerDescriptor> GetController() const;
1373
1374
  // Returns the size of the mBlockedTrackingNodes array.
1375
  //
1376
  // This array contains nodes that have been blocked to prevent
1377
  // user tracking. They most likely have had their nsIChannel
1378
  // canceled by the URL classifier (Safebrowsing).
1379
  //
1380
  // A script can subsequently use GetBlockedTrackingNodes()
1381
  // to get a list of references to these nodes.
1382
  //
1383
  // Note:
1384
  // This expresses how many tracking nodes have been blocked for this
1385
  // document since its beginning, not how many of them are still around
1386
  // in the DOM tree. Weak references to blocked nodes are added in the
1387
  // mBlockedTrackingNodesArray but they are not removed when those nodes
1388
  // are removed from the tree or even garbage collected.
1389
  long BlockedTrackingNodeCount() const
1390
0
  {
1391
0
    return mBlockedTrackingNodes.Length();
1392
0
  }
1393
1394
  //
1395
  // Returns strong references to mBlockedTrackingNodes. (nsIDocument.h)
1396
  //
1397
  // This array contains nodes that have been blocked to prevent
1398
  // user tracking. They most likely have had their nsIChannel
1399
  // canceled by the URL classifier (Safebrowsing).
1400
  //
1401
  already_AddRefed<nsSimpleContentList> BlockedTrackingNodes() const;
1402
1403
protected:
1404
  friend class nsUnblockOnloadEvent;
1405
1406
  nsresult InitCSP(nsIChannel* aChannel);
1407
1408
  void PostUnblockOnloadEvent();
1409
1410
  void DoUnblockOnload();
1411
1412
  void ClearAllBoxObjects();
1413
1414
  void MaybeEndOutermostXBLUpdate();
1415
1416
  void DispatchContentLoadedEvents();
1417
1418
  void DispatchPageTransition(mozilla::dom::EventTarget* aDispatchTarget,
1419
                              const nsAString& aType,
1420
                              bool aPersisted,
1421
                              bool aOnlySystemGroup = false);
1422
1423
  // Call this before the document does something that will unbind all content.
1424
  // That will stop us from doing a lot of work as each element is removed.
1425
  void DestroyElementMaps();
1426
1427
  Element* GetRootElementInternal() const;
1428
  void DoNotifyPossibleTitleChange();
1429
1430
  void SetPageUnloadingEventTimeStamp()
1431
0
  {
1432
0
    MOZ_ASSERT(!mPageUnloadingEventTimeStamp);
1433
0
    mPageUnloadingEventTimeStamp = mozilla::TimeStamp::NowLoRes();
1434
0
  }
1435
1436
  void CleanUnloadEventsTimeStamp()
1437
0
  {
1438
0
    MOZ_ASSERT(mPageUnloadingEventTimeStamp);
1439
0
    mPageUnloadingEventTimeStamp = mozilla::TimeStamp();
1440
0
  }
1441
1442
  /**
1443
   * Clears any Servo element data stored on Elements in the document.
1444
   */
1445
  void ClearStaleServoData();
1446
1447
  /**
1448
   * Returns the top window root from the outer window.
1449
   */
1450
  already_AddRefed<nsPIWindowRoot> GetWindowRoot();
1451
1452
private:
1453
  class SelectorCacheKey
1454
  {
1455
    public:
1456
      explicit SelectorCacheKey(const nsAString& aString) : mKey(aString)
1457
0
      {
1458
0
        MOZ_COUNT_CTOR(SelectorCacheKey);
1459
0
      }
1460
1461
      nsString mKey;
1462
      nsExpirationState mState;
1463
1464
0
      nsExpirationState* GetExpirationState() { return &mState; }
1465
1466
      ~SelectorCacheKey()
1467
0
      {
1468
0
        MOZ_COUNT_DTOR(SelectorCacheKey);
1469
0
      }
1470
  };
1471
1472
  class SelectorCacheKeyDeleter;
1473
1474
public:
1475
  class SelectorCache final
1476
    : public nsExpirationTracker<SelectorCacheKey, 4>
1477
  {
1478
  public:
1479
    using SelectorList = mozilla::UniquePtr<RawServoSelectorList>;
1480
1481
    explicit SelectorCache(nsIEventTarget* aEventTarget);
1482
1483
    void CacheList(const nsAString& aSelector, SelectorList aSelectorList)
1484
0
    {
1485
0
      MOZ_ASSERT(NS_IsMainThread());
1486
0
      SelectorCacheKey* key = new SelectorCacheKey(aSelector);
1487
0
      mTable.Put(key->mKey, std::move(aSelectorList));
1488
0
      AddObject(key);
1489
0
    }
1490
1491
    void NotifyExpired(SelectorCacheKey* aSelector) final;
1492
1493
    // We do not call MarkUsed because it would just slow down lookups and
1494
    // because we're OK expiring things after a few seconds even if they're
1495
    // being used.  Returns whether we actually had an entry for aSelector.
1496
    //
1497
    // If we have an entry and the selector list returned has a null
1498
    // RawServoSelectorList*, that indicates that aSelector has already been
1499
    // parsed and is not a syntactically valid selector.
1500
    SelectorList* GetList(const nsAString& aSelector)
1501
0
    {
1502
0
      return mTable.GetValue(aSelector);
1503
0
    }
1504
1505
    ~SelectorCache();
1506
1507
  private:
1508
    nsDataHashtable<nsStringHashKey, SelectorList> mTable;
1509
  };
1510
1511
0
  SelectorCache& GetSelectorCache() {
1512
0
    if (!mSelectorCache) {
1513
0
      mSelectorCache =
1514
0
        mozilla::MakeUnique<SelectorCache>(
1515
0
          EventTargetFor(mozilla::TaskCategory::Other));
1516
0
    }
1517
0
    return *mSelectorCache;
1518
0
  }
1519
  // Get the root <html> element, or return null if there isn't one (e.g.
1520
  // if the root isn't <html>)
1521
  Element* GetHtmlElement() const;
1522
  // Returns the first child of GetHtmlContent which has the given tag,
1523
  // or nullptr if that doesn't exist.
1524
  Element* GetHtmlChildElement(nsAtom* aTag);
1525
  // Get the canonical <body> element, or return null if there isn't one (e.g.
1526
  // if the root isn't <html> or if the <body> isn't there)
1527
  mozilla::dom::HTMLBodyElement* GetBodyElement();
1528
  // Get the canonical <head> element, or return null if there isn't one (e.g.
1529
  // if the root isn't <html> or if the <head> isn't there)
1530
0
  Element* GetHeadElement() {
1531
0
    return GetHtmlChildElement(nsGkAtoms::head);
1532
0
  }
1533
  // Get the "body" in the sense of document.body: The first <body> or
1534
  // <frameset> that's a child of a root <html>
1535
  nsGenericHTMLElement* GetBody();
1536
  // Set the "body" in the sense of document.body.
1537
  void SetBody(nsGenericHTMLElement* aBody, mozilla::ErrorResult& rv);
1538
  // Get the "head" element in the sense of document.head.
1539
  mozilla::dom::HTMLSharedElement* GetHead();
1540
1541
  /**
1542
   * Accessors to the collection of stylesheets owned by this document.
1543
   * Style sheets are ordered, most significant last.
1544
   */
1545
1546
  mozilla::dom::StyleSheetList* StyleSheets()
1547
0
  {
1548
0
    return &DocumentOrShadowRoot::EnsureDOMStyleSheets();
1549
0
  }
1550
1551
  void InsertSheetAt(size_t aIndex, mozilla::StyleSheet&);
1552
1553
  /**
1554
   * Replace the stylesheets in aOldSheets with the stylesheets in
1555
   * aNewSheets. The two lists must have equal length, and the sheet
1556
   * at positon J in the first list will be replaced by the sheet at
1557
   * position J in the second list.  Some sheets in the second list
1558
   * may be null; if so the corresponding sheets in the first list
1559
   * will simply be removed.
1560
   */
1561
  void UpdateStyleSheets(
1562
      nsTArray<RefPtr<mozilla::StyleSheet>>& aOldSheets,
1563
      nsTArray<RefPtr<mozilla::StyleSheet>>& aNewSheets);
1564
1565
  /**
1566
   * Add a stylesheet to the document
1567
   *
1568
   * TODO(emilio): This is only used by parts of editor that are no longer in
1569
   * use by m-c or c-c, so remove.
1570
   */
1571
  void AddStyleSheet(mozilla::StyleSheet* aSheet)
1572
0
  {
1573
0
    MOZ_ASSERT(aSheet);
1574
0
    InsertSheetAt(SheetCount(), *aSheet);
1575
0
  }
1576
1577
  /**
1578
   * Remove a stylesheet from the document
1579
   */
1580
  void RemoveStyleSheet(mozilla::StyleSheet* aSheet);
1581
1582
  /**
1583
   * Notify the document that the applicable state of the sheet changed
1584
   * and that observers should be notified and style sets updated
1585
   */
1586
  void SetStyleSheetApplicableState(mozilla::StyleSheet* aSheet,
1587
                                    bool aApplicable);
1588
1589
  enum additionalSheetType {
1590
    eAgentSheet,
1591
    eUserSheet,
1592
    eAuthorSheet,
1593
    AdditionalSheetTypeCount
1594
  };
1595
1596
  nsresult LoadAdditionalStyleSheet(additionalSheetType aType,
1597
                                    nsIURI* aSheetURI);
1598
  nsresult AddAdditionalStyleSheet(additionalSheetType aType,
1599
                                   mozilla::StyleSheet* aSheet);
1600
  void RemoveAdditionalStyleSheet(additionalSheetType aType, nsIURI* sheetURI);
1601
1602
  mozilla::StyleSheet* GetFirstAdditionalAuthorSheet()
1603
0
  {
1604
0
    return mAdditionalSheets[eAuthorSheet].SafeElementAt(0);
1605
0
  }
1606
1607
  /**
1608
   * Assuming that aDocSheets is an array of document-level style
1609
   * sheets for this document, returns the index that aSheet should
1610
   * be inserted at to maintain document ordering.
1611
   *
1612
   * Type T has to cast to StyleSheet*.
1613
   *
1614
   * Defined in nsIDocumentInlines.h.
1615
   */
1616
  template<typename T>
1617
  size_t FindDocStyleSheetInsertionPoint(const nsTArray<T>& aDocSheets,
1618
                                         const mozilla::StyleSheet& aSheet);
1619
1620
  /**
1621
   * Get this document's CSSLoader.  This is guaranteed to not return null.
1622
   */
1623
0
  mozilla::css::Loader* CSSLoader() const {
1624
0
    return mCSSLoader;
1625
0
  }
1626
1627
  /**
1628
   * Get this document's StyleImageLoader.  This is guaranteed to not return null.
1629
   */
1630
0
  mozilla::css::ImageLoader* StyleImageLoader() const {
1631
0
    return mStyleImageLoader;
1632
0
  }
1633
1634
  /**
1635
   * Get the channel that was passed to StartDocumentLoad or Reset for this
1636
   * document.  Note that this may be null in some cases (eg if
1637
   * StartDocumentLoad or Reset were never called)
1638
   */
1639
  nsIChannel* GetChannel() const
1640
0
  {
1641
0
    return mChannel;
1642
0
  }
1643
1644
  /**
1645
   * Get this document's attribute stylesheet.  May return null if
1646
   * there isn't one.
1647
   */
1648
0
  nsHTMLStyleSheet* GetAttributeStyleSheet() const {
1649
0
    return mAttrStyleSheet;
1650
0
  }
1651
1652
  /**
1653
   * Get this document's inline style sheet.  May return null if there
1654
   * isn't one
1655
   */
1656
0
  nsHTMLCSSStyleSheet* GetInlineStyleSheet() const {
1657
0
    return mStyleAttrStyleSheet;
1658
0
  }
1659
1660
  virtual void SetScriptGlobalObject(nsIScriptGlobalObject* aGlobalObject);
1661
1662
  /**
1663
   * Get/set the object from which the context for the event/script handling can
1664
   * be got. Normally GetScriptHandlingObject() returns the same object as
1665
   * GetScriptGlobalObject(), but if the document is loaded as data,
1666
   * non-null may be returned, even if GetScriptGlobalObject() returns null.
1667
   * aHasHadScriptHandlingObject is set true if document has had the object
1668
   * for event/script handling. Do not process any events/script if the method
1669
   * returns null, but aHasHadScriptHandlingObject is true.
1670
   */
1671
  nsIScriptGlobalObject*
1672
    GetScriptHandlingObject(bool& aHasHadScriptHandlingObject) const
1673
0
  {
1674
0
    aHasHadScriptHandlingObject = mHasHadScriptHandlingObject;
1675
0
    return mScriptGlobalObject ? mScriptGlobalObject.get() :
1676
0
                                 GetScriptHandlingObjectInternal();
1677
0
  }
1678
  void SetScriptHandlingObject(nsIScriptGlobalObject* aScriptObject);
1679
1680
  /**
1681
   * Get the object that is used as the scope for all of the content
1682
   * wrappers whose owner document is this document. Unlike the script global
1683
   * object, this will only return null when the global object for this
1684
   * document is truly gone. Use this object when you're trying to find a
1685
   * content wrapper in XPConnect.
1686
   */
1687
  nsIGlobalObject* GetScopeObject() const;
1688
  void SetScopeObject(nsIGlobalObject* aGlobal);
1689
1690
  /**
1691
   * Return the window containing the document (the outer window).
1692
   */
1693
  nsPIDOMWindowOuter *GetWindow() const
1694
0
  {
1695
0
    return mWindow ? mWindow->GetOuterWindow() : GetWindowInternal();
1696
0
  }
1697
1698
  bool IsInBackgroundWindow() const
1699
0
  {
1700
0
    auto* outer = mWindow ? mWindow->GetOuterWindow() : nullptr;
1701
0
    return outer && outer->IsBackground();
1702
0
  }
1703
1704
  /**
1705
   * Return the inner window used as the script compilation scope for
1706
   * this document. If you're not absolutely sure you need this, use
1707
   * GetWindow().
1708
   */
1709
  nsPIDOMWindowInner* GetInnerWindow() const
1710
0
  {
1711
0
    return mRemovedFromDocShell ? nullptr : mWindow;
1712
0
  }
1713
1714
  /**
1715
   * Return the outer window ID.
1716
   */
1717
  uint64_t OuterWindowID() const
1718
0
  {
1719
0
    nsPIDOMWindowOuter* window = GetWindow();
1720
0
    return window ? window->WindowID() : 0;
1721
0
  }
1722
1723
  /**
1724
   * Return the inner window ID.
1725
   */
1726
  uint64_t InnerWindowID() const
1727
0
  {
1728
0
    nsPIDOMWindowInner* window = GetInnerWindow();
1729
0
    return window ? window->WindowID() : 0;
1730
0
  }
1731
1732
  bool IsTopLevelWindowInactive() const;
1733
1734
  /**
1735
   * Get the script loader for this document
1736
   */
1737
  mozilla::dom::ScriptLoader* ScriptLoader()
1738
0
  {
1739
0
    return mScriptLoader;
1740
0
  }
1741
1742
  /**
1743
   * Add/Remove an element to the document's id and name hashes
1744
   */
1745
  void AddToIdTable(Element* aElement, nsAtom* aId);
1746
  void RemoveFromIdTable(Element* aElement, nsAtom* aId);
1747
  void AddToNameTable(Element* aElement, nsAtom* aName);
1748
  void RemoveFromNameTable(Element* aElement, nsAtom* aName);
1749
1750
  /**
1751
   * Returns all elements in the fullscreen stack in the insertion order.
1752
   */
1753
  nsTArray<Element*> GetFullscreenStack() const;
1754
1755
  /**
1756
   * Asynchronously requests that the document make aElement the fullscreen
1757
   * element, and move into fullscreen mode. The current fullscreen element
1758
   * (if any) is pushed onto the fullscreen element stack, and it can be
1759
   * returned to fullscreen status by calling RestorePreviousFullscreenState().
1760
   *
1761
   * Note that requesting fullscreen in a document also makes the element which
1762
   * contains this document in this document's parent document fullscreen. i.e.
1763
   * the <iframe> or <browser> that contains this document is also mode
1764
   * fullscreen. This happens recursively in all ancestor documents.
1765
   */
1766
  void AsyncRequestFullscreen(mozilla::UniquePtr<FullscreenRequest>);
1767
1768
  // Do the "fullscreen element ready check" from the fullscreen spec.
1769
  // It returns true if the given element is allowed to go into fullscreen.
1770
  // It is responsive to dispatch "fullscreenerror" event when necessary.
1771
  bool FullscreenElementReadyCheck(const FullscreenRequest&);
1772
1773
  // This is called asynchronously by nsIDocument::AsyncRequestFullscreen()
1774
  // to move this document into fullscreen mode if allowed.
1775
  void RequestFullscreen(mozilla::UniquePtr<FullscreenRequest> aRequest);
1776
1777
  // Removes all elements from the fullscreen stack, removing full-scren
1778
  // styles from the top element in the stack.
1779
  void CleanupFullscreenState();
1780
1781
  // Pushes aElement onto the fullscreen stack, and removes fullscreen styles
1782
  // from the former fullscreen stack top, and its ancestors, and applies the
1783
  // styles to aElement. aElement becomes the new "fullscreen element".
1784
  bool FullscreenStackPush(Element* aElement);
1785
1786
  // Remove the top element from the fullscreen stack. Removes the fullscreen
1787
  // styles from the former top element, and applies them to the new top
1788
  // element, if there is one.
1789
  void FullscreenStackPop();
1790
1791
  /**
1792
   * Called when a frame in a child process has entered fullscreen or when a
1793
   * fullscreen frame in a child process changes to another origin.
1794
   * aFrameElement is the frame element which contains the child-process
1795
   * fullscreen document.
1796
   */
1797
  nsresult RemoteFrameFullscreenChanged(mozilla::dom::Element* aFrameElement);
1798
1799
  /**
1800
   * Called when a frame in a remote child document has rolled back fullscreen
1801
   * so that all its fullscreen element stacks are empty; we must continue the
1802
   * rollback in this parent process' doc tree branch which is fullscreen.
1803
   * Note that only one branch of the document tree can have its documents in
1804
   * fullscreen state at one time. We're in inconsistent state if a
1805
   * fullscreen document has a parent and that parent isn't fullscreen. We
1806
   * preserve this property across process boundaries.
1807
   */
1808
   nsresult RemoteFrameFullscreenReverted();
1809
1810
  /**
1811
   * Restores the previous fullscreen element to fullscreen status. If there
1812
   * is no former fullscreen element, this exits fullscreen, moving the
1813
   * top-level browser window out of fullscreen mode.
1814
   */
1815
  void RestorePreviousFullscreenState(
1816
    mozilla::UniquePtr<mozilla::FullscreenExit>);
1817
1818
  /**
1819
   * Returns true if this document is a fullscreen leaf document, i.e. it
1820
   * is in fullscreen mode and has no fullscreen children.
1821
   */
1822
  bool IsFullscreenLeaf();
1823
1824
  /**
1825
   * Returns the document which is at the root of this document's branch
1826
   * in the in-process document tree. Returns nullptr if the document isn't
1827
   * fullscreen.
1828
   */
1829
  nsIDocument* GetFullscreenRoot();
1830
1831
  /**
1832
   * Sets the fullscreen root to aRoot. This stores a weak reference to aRoot
1833
   * in this document.
1834
   */
1835
  void SetFullscreenRoot(nsIDocument* aRoot);
1836
1837
  /**
1838
   * Synchronously cleans up the fullscreen state on the given document.
1839
   *
1840
   * Calling this without performing fullscreen transition could lead
1841
   * to undesired effect (the transition happens after document state
1842
   * flips), hence it should only be called either by nsGlobalWindow
1843
   * when we have performed the transition, or when it is necessary to
1844
   * clean up the state immediately. Otherwise, AsyncExitFullscreen()
1845
   * should be called instead.
1846
   *
1847
   * aDocument must not be null.
1848
   */
1849
  static void ExitFullscreenInDocTree(nsIDocument* aDocument);
1850
1851
  /**
1852
   * Ask the document to exit fullscreen state asynchronously.
1853
   *
1854
   * Different from ExitFullscreenInDocTree(), this allows the window
1855
   * to perform fullscreen transition first if any.
1856
   *
1857
   * If aDocument is null, it will exit fullscreen from all documents
1858
   * in all windows.
1859
   */
1860
  static void AsyncExitFullscreen(nsIDocument* aDocument);
1861
1862
  /**
1863
   * Handles any pending fullscreen in aDocument or its subdocuments.
1864
   *
1865
   * Returns whether there is any fullscreen request handled.
1866
   */
1867
  static bool HandlePendingFullscreenRequests(nsIDocument* aDocument);
1868
1869
  void RequestPointerLock(Element* aElement, mozilla::dom::CallerType);
1870
  bool SetPointerLock(Element* aElement, int aCursorStyle);
1871
1872
  static void UnlockPointer(nsIDocument* aDoc = nullptr);
1873
1874
  // ScreenOrientation related APIs
1875
1876
  void SetCurrentOrientation(mozilla::dom::OrientationType aType,
1877
                             uint16_t aAngle)
1878
0
  {
1879
0
    mCurrentOrientationType = aType;
1880
0
    mCurrentOrientationAngle = aAngle;
1881
0
  }
1882
1883
  uint16_t CurrentOrientationAngle() const
1884
0
  {
1885
0
    return mCurrentOrientationAngle;
1886
0
  }
1887
  mozilla::dom::OrientationType CurrentOrientationType() const
1888
0
  {
1889
0
    return mCurrentOrientationType;
1890
0
  }
1891
  void SetOrientationPendingPromise(mozilla::dom::Promise* aPromise);
1892
  mozilla::dom::Promise* GetOrientationPendingPromise() const
1893
0
  {
1894
0
    return mOrientationPendingPromise;
1895
0
  }
1896
1897
  //----------------------------------------------------------------------
1898
1899
  // Document notification API's
1900
1901
  /**
1902
   * Add a new observer of document change notifications. Whenever
1903
   * content is changed, appended, inserted or removed the observers are
1904
   * informed.  An observer that is already observing the document must
1905
   * not be added without being removed first.
1906
   */
1907
  void AddObserver(nsIDocumentObserver* aObserver);
1908
1909
  /**
1910
   * Remove an observer of document change notifications. This will
1911
   * return false if the observer cannot be found.
1912
   */
1913
  bool RemoveObserver(nsIDocumentObserver* aObserver);
1914
1915
  // Observation hooks used to propagate notifications to document observers.
1916
  // BeginUpdate must be called before any batch of modifications of the
1917
  // content model or of style data, EndUpdate must be called afterward.
1918
  // To make this easy and painless, use the mozAutoDocUpdate helper class.
1919
  void BeginUpdate();
1920
  virtual void EndUpdate() = 0;
1921
0
  uint32_t UpdateNestingLevel() { return mUpdateNestLevel; }
1922
1923
  virtual void BeginLoad() = 0;
1924
  virtual void EndLoad() = 0;
1925
1926
  enum ReadyState { READYSTATE_UNINITIALIZED = 0, READYSTATE_LOADING = 1, READYSTATE_INTERACTIVE = 3, READYSTATE_COMPLETE = 4};
1927
  void SetReadyStateInternal(ReadyState rs);
1928
  ReadyState GetReadyStateEnum()
1929
0
  {
1930
0
    return mReadyState;
1931
0
  }
1932
1933
  // notify that a content node changed state.  This must happen under
1934
  // a scriptblocker but NOT within a begin/end update.
1935
  void ContentStateChanged(
1936
      nsIContent* aContent, mozilla::EventStates aStateMask);
1937
1938
  // Notify that a document state has changed.
1939
  // This should only be called by callers whose state is also reflected in the
1940
  // implementation of nsDocument::GetDocumentState.
1941
  void DocumentStatesChanged(mozilla::EventStates aStateMask);
1942
1943
  // Observation hooks for style data to propagate notifications
1944
  // to document observers
1945
  void StyleRuleChanged(mozilla::StyleSheet* aStyleSheet,
1946
                        mozilla::css::Rule* aStyleRule);
1947
  void StyleRuleAdded(mozilla::StyleSheet* aStyleSheet,
1948
                      mozilla::css::Rule* aStyleRule);
1949
  void StyleRuleRemoved(mozilla::StyleSheet* aStyleSheet,
1950
                        mozilla::css::Rule* aStyleRule);
1951
1952
  /**
1953
   * Flush notifications for this document and its parent documents
1954
   * (since those may affect the layout of this one).
1955
   */
1956
  void FlushPendingNotifications(mozilla::FlushType aType);
1957
1958
  /**
1959
   * Another variant of the above FlushPendingNotifications.  This function
1960
   * takes a ChangesToFlush to specify whether throttled animations are flushed
1961
   * or not.
1962
   * If in doublt, use the above FlushPendingNotifications.
1963
   */
1964
  void FlushPendingNotifications(mozilla::ChangesToFlush aFlush);
1965
1966
  /**
1967
   * Calls FlushPendingNotifications on any external resources this document
1968
   * has. If this document has no external resources or is an external resource
1969
   * itself this does nothing. This should only be called with
1970
   * aType >= FlushType::Style.
1971
   */
1972
  void FlushExternalResources(mozilla::FlushType aType);
1973
1974
  // Triggers an update of <svg:use> element shadow trees.
1975
  void UpdateSVGUseElementShadowTrees()
1976
0
  {
1977
0
    if (mSVGUseElementsNeedingShadowTreeUpdate.IsEmpty()) {
1978
0
      return;
1979
0
    }
1980
0
    DoUpdateSVGUseElementShadowTrees();
1981
0
  }
1982
1983
  nsBindingManager* BindingManager() const
1984
0
  {
1985
0
    return mNodeInfoManager->GetBindingManager();
1986
0
  }
1987
1988
  /**
1989
   * Only to be used inside Gecko, you can't really do anything with the
1990
   * pointer outside Gecko anyway.
1991
   */
1992
  nsNodeInfoManager* NodeInfoManager() const
1993
0
  {
1994
0
    return mNodeInfoManager;
1995
0
  }
1996
1997
  /**
1998
   * Reset the document using the given channel and loadgroup.  This works
1999
   * like ResetToURI, but also sets the document's channel to aChannel.
2000
   * The principal of the document will be set from the channel.
2001
   */
2002
  virtual void Reset(nsIChannel* aChannel, nsILoadGroup* aLoadGroup);
2003
2004
  /**
2005
   * Reset this document to aURI, aLoadGroup, and aPrincipal.  aURI must not be
2006
   * null.  If aPrincipal is null, a codebase principal based on aURI will be
2007
   * used.
2008
   */
2009
  virtual void ResetToURI(nsIURI* aURI,
2010
                          nsILoadGroup* aLoadGroup,
2011
                          nsIPrincipal* aPrincipal);
2012
2013
  /**
2014
   * Set the container (docshell) for this document. Virtual so that
2015
   * docshell can call it.
2016
   */
2017
  virtual void SetContainer(nsDocShell* aContainer);
2018
2019
  /**
2020
   * Get the container (docshell) for this document.
2021
   */
2022
  virtual nsISupports* GetContainer() const;
2023
2024
  /**
2025
   * Get the container's load context for this document.
2026
   */
2027
  nsILoadContext* GetLoadContext() const;
2028
2029
  /**
2030
   * Get docshell the for this document.
2031
   */
2032
  nsIDocShell* GetDocShell() const;
2033
2034
  /**
2035
   * Set and get XML declaration. If aVersion is null there is no declaration.
2036
   * aStandalone takes values -1, 0 and 1 indicating respectively that there
2037
   * was no standalone parameter in the declaration, that it was given as no,
2038
   * or that it was given as yes.
2039
   */
2040
  void SetXMLDeclaration(const char16_t* aVersion,
2041
                         const char16_t* aEncoding,
2042
                         const int32_t aStandalone);
2043
  void GetXMLDeclaration(nsAString& aVersion,
2044
                         nsAString& aEncoding,
2045
                         nsAString& Standalone);
2046
2047
  /**
2048
   * Returns true if this is what HTML 5 calls an "HTML document" (for example
2049
   * regular HTML document with Content-Type "text/html", image documents and
2050
   * media documents).  Returns false for XHTML and any other documents parsed
2051
   * by the XML parser.
2052
   */
2053
  bool IsHTMLDocument() const
2054
0
  {
2055
0
    return mType == eHTML;
2056
0
  }
2057
  bool IsHTMLOrXHTML() const
2058
0
  {
2059
0
    return mType == eHTML || mType == eXHTML;
2060
0
  }
2061
  bool IsXMLDocument() const
2062
0
  {
2063
0
    return !IsHTMLDocument();
2064
0
  }
2065
  bool IsSVGDocument() const
2066
0
  {
2067
0
    return mType == eSVG;
2068
0
  }
2069
  bool IsXULDocument() const
2070
0
  {
2071
0
    return mType == eXUL;
2072
0
  }
2073
  bool IsUnstyledDocument()
2074
0
  {
2075
0
    return IsLoadedAsData() || IsLoadedAsInteractiveData();
2076
0
  }
2077
  bool LoadsFullXULStyleSheetUpFront()
2078
0
  {
2079
0
    if (IsXULDocument()) {
2080
0
      return true;
2081
0
    }
2082
0
    if (IsSVGDocument()) {
2083
0
      return false;
2084
0
    }
2085
0
    return AllowXULXBL();
2086
0
  }
2087
2088
  bool IsScriptEnabled();
2089
2090
0
  bool IsTopLevelContentDocument() const { return mIsTopLevelContentDocument; }
2091
  void SetIsTopLevelContentDocument(bool aIsTopLevelContentDocument)
2092
0
  {
2093
0
    mIsTopLevelContentDocument = aIsTopLevelContentDocument;
2094
0
    // When a document is set as TopLevelContentDocument, it must be
2095
0
    // allowpaymentrequest. We handle the false case while a document is appended
2096
0
    // in SetSubDocumentFor
2097
0
    if (aIsTopLevelContentDocument) {
2098
0
      SetAllowPaymentRequest(true);
2099
0
    }
2100
0
  }
2101
2102
0
  bool IsContentDocument() const { return mIsContentDocument; }
2103
  void SetIsContentDocument(bool aIsContentDocument)
2104
0
  {
2105
0
    mIsContentDocument = aIsContentDocument;
2106
0
  }
2107
2108
  /**
2109
   * Create an element with the specified name, prefix and namespace ID.
2110
   * Returns null if element name parsing failed.
2111
   */
2112
  already_AddRefed<Element> CreateElem(const nsAString& aName,
2113
                                       nsAtom* aPrefix,
2114
                                       int32_t aNamespaceID,
2115
                                       const nsAString* aIs = nullptr);
2116
2117
  /**
2118
   * Get the security info (i.e. SSL state etc) that the document got
2119
   * from the channel/document that created the content of the
2120
   * document.
2121
   *
2122
   * @see nsIChannel
2123
   */
2124
  nsISupports *GetSecurityInfo()
2125
0
  {
2126
0
    return mSecurityInfo;
2127
0
  }
2128
2129
  /**
2130
   * Get the channel that failed to load and resulted in an error page, if it
2131
   * exists. This is only relevant to error pages.
2132
   */
2133
  nsIChannel* GetFailedChannel() const
2134
0
  {
2135
0
    return mFailedChannel;
2136
0
  }
2137
2138
  /**
2139
   * Set the channel that failed to load and resulted in an error page.
2140
   * This is only relevant to error pages.
2141
   */
2142
  void SetFailedChannel(nsIChannel* aChannel)
2143
0
  {
2144
0
    mFailedChannel = aChannel;
2145
0
  }
2146
2147
  /**
2148
   * Returns the default namespace ID used for elements created in this
2149
   * document.
2150
   */
2151
  int32_t GetDefaultNamespaceID() const
2152
0
  {
2153
0
    return mDefaultElementType;
2154
0
  }
2155
2156
  void DeleteAllProperties();
2157
  void DeleteAllPropertiesFor(nsINode* aNode);
2158
2159
  nsPropertyTable& PropertyTable()
2160
0
  {
2161
0
    return mPropertyTable;
2162
0
  }
2163
2164
  /**
2165
   * Sets the ID used to identify this part of the multipart document
2166
   */
2167
0
  void SetPartID(uint32_t aID) {
2168
0
    mPartID = aID;
2169
0
  }
2170
2171
  /**
2172
   * Return the ID used to identify this part of the multipart document
2173
   */
2174
0
  uint32_t GetPartID() const {
2175
0
    return mPartID;
2176
0
  }
2177
2178
  /**
2179
   * Sanitize the document by resetting all input elements and forms that have
2180
   * autocomplete=off to their default values.
2181
   */
2182
  void Sanitize();
2183
2184
  /**
2185
   * Enumerate all subdocuments.
2186
   * The enumerator callback should return true to continue enumerating, or
2187
   * false to stop.  This will never get passed a null aDocument.
2188
   */
2189
  typedef bool (*nsSubDocEnumFunc)(nsIDocument *aDocument, void *aData);
2190
  void EnumerateSubDocuments(nsSubDocEnumFunc aCallback, void *aData);
2191
2192
  /**
2193
   * Collect all the descendant documents for which |aCalback| returns true.
2194
   * The callback function must not mutate any state for the given document.
2195
   */
2196
  typedef bool (*nsDocTestFunc)(const nsIDocument* aDocument);
2197
  void CollectDescendantDocuments(
2198
    nsTArray<nsCOMPtr<nsIDocument>>& aDescendants,
2199
    nsDocTestFunc aCallback) const;
2200
2201
  /**
2202
   * Check whether it is safe to cache the presentation of this document
2203
   * and all of its subdocuments. This method checks the following conditions
2204
   * recursively:
2205
   *  - Some document types, such as plugin documents, cannot be safely cached.
2206
   *  - If there are any pending requests, we don't allow the presentation
2207
   *    to be cached.  Ideally these requests would be suspended and resumed,
2208
   *    but that is difficult in some cases, such as XMLHttpRequest.
2209
   *  - If there are any beforeunload or unload listeners, we must fire them
2210
   *    for correctness, but this likely puts the document into a state where
2211
   *    it would not function correctly if restored.
2212
   *
2213
   * |aNewRequest| should be the request for a new document which will
2214
   * replace this document in the docshell.  The new document's request
2215
   * will be ignored when checking for active requests.  If there is no
2216
   * request associated with the new document, this parameter may be null.
2217
   */
2218
  virtual bool CanSavePresentation(nsIRequest* aNewRequest);
2219
2220
  /**
2221
   * Notify the document that its associated ContentViewer is being destroyed.
2222
   * This releases circular references so that the document can go away.
2223
   * Destroy() is only called on documents that have a content viewer.
2224
   */
2225
  virtual void Destroy() = 0;
2226
2227
  /**
2228
   * Notify the document that its associated ContentViewer is no longer
2229
   * the current viewer for the docshell. The document might still
2230
   * be rendered in "zombie state" until the next document is ready.
2231
   * The document should save form control state.
2232
   */
2233
  virtual void RemovedFromDocShell() = 0;
2234
2235
  /**
2236
   * Get the layout history state that should be used to save and restore state
2237
   * for nodes in this document.  This may return null; if that happens state
2238
   * saving and restoration is not possible.
2239
   */
2240
  already_AddRefed<nsILayoutHistoryState> GetLayoutHistoryState() const;
2241
2242
  /**
2243
   * Methods that can be used to prevent onload firing while an event that
2244
   * should block onload is posted.  onload is guaranteed to not fire until
2245
   * either all calls to BlockOnload() have been matched by calls to
2246
   * UnblockOnload() or the load has been stopped altogether (by the user
2247
   * pressing the Stop button, say).
2248
   */
2249
  virtual void BlockOnload() = 0;
2250
  /**
2251
   * @param aFireSync whether to fire onload synchronously.  If false,
2252
   * onload will fire asynchronously after all onload blocks have been
2253
   * removed.  It will NOT fire from inside UnblockOnload.  If true,
2254
   * onload may fire from inside UnblockOnload.
2255
   */
2256
  virtual void UnblockOnload(bool aFireSync) = 0;
2257
2258
  void BlockDOMContentLoaded()
2259
0
  {
2260
0
    ++mBlockDOMContentLoaded;
2261
0
  }
2262
2263
  void UnblockDOMContentLoaded();
2264
2265
  /**
2266
   * Notification that the page has been shown, for documents which are loaded
2267
   * into a DOM window.  This corresponds to the completion of document load,
2268
   * or to the page's presentation being restored into an existing DOM window.
2269
   * This notification fires applicable DOM events to the content window.  See
2270
   * PageTransitionEvent.webidl for a description of the |aPersisted|
2271
   * parameter. If aDispatchStartTarget is null, the pageshow event is
2272
   * dispatched on the ScriptGlobalObject for this document, otherwise it's
2273
   * dispatched on aDispatchStartTarget. If |aOnlySystemGroup| is true, the
2274
   * event is only dispatched to listeners in the system group.
2275
   * Note: if aDispatchStartTarget isn't null, the showing state of the
2276
   * document won't be altered.
2277
   */
2278
  virtual void OnPageShow(bool aPersisted,
2279
                          mozilla::dom::EventTarget* aDispatchStartTarget,
2280
                          bool aOnlySystemGroup = false);
2281
2282
  /**
2283
   * Notification that the page has been hidden, for documents which are loaded
2284
   * into a DOM window.  This corresponds to the unloading of the document, or
2285
   * to the document's presentation being saved but removed from an existing
2286
   * DOM window.  This notification fires applicable DOM events to the content
2287
   * window.  See PageTransitionEvent.webidl for a description of the
2288
   * |aPersisted| parameter. If aDispatchStartTarget is null, the pagehide
2289
   * event is dispatched on the ScriptGlobalObject for this document,
2290
   * otherwise it's dispatched on aDispatchStartTarget. If |aOnlySystemGroup| is
2291
   * true, the event is only dispatched to listeners in the system group.
2292
   * Note: if aDispatchStartTarget isn't null, the showing state of the
2293
   * document won't be altered.
2294
   */
2295
  void OnPageHide(bool aPersisted,
2296
                  mozilla::dom::EventTarget* aDispatchStartTarget,
2297
                  bool aOnlySystemGroup = false);
2298
2299
  /*
2300
   * We record the set of links in the document that are relevant to
2301
   * style.
2302
   */
2303
  /**
2304
   * Notification that an element is a link that is relevant to style.
2305
   */
2306
  void AddStyleRelevantLink(mozilla::dom::Link* aLink)
2307
0
  {
2308
0
    NS_ASSERTION(aLink, "Passing in a null link.  Expect crashes RSN!");
2309
#ifdef DEBUG
2310
    nsPtrHashKey<mozilla::dom::Link>* entry = mStyledLinks.GetEntry(aLink);
2311
    NS_ASSERTION(!entry, "Document already knows about this Link!");
2312
    mStyledLinksCleared = false;
2313
#endif
2314
    mStyledLinks.PutEntry(aLink);
2315
0
  }
2316
2317
  /**
2318
   * Notification that an element is a link and its URI might have been
2319
   * changed or the element removed. If the element is still a link relevant
2320
   * to style, then someone must ensure that AddStyleRelevantLink is
2321
   * (eventually) called on it again.
2322
   */
2323
  void ForgetLink(mozilla::dom::Link* aLink)
2324
0
  {
2325
0
    NS_ASSERTION(aLink, "Passing in a null link.  Expect crashes RSN!");
2326
#ifdef DEBUG
2327
    nsPtrHashKey<mozilla::dom::Link>* entry = mStyledLinks.GetEntry(aLink);
2328
    NS_ASSERTION(entry || mStyledLinksCleared,
2329
                 "Document knows nothing about this Link!");
2330
#endif
2331
    mStyledLinks.RemoveEntry(aLink);
2332
0
  }
2333
2334
  // Refreshes the hrefs of all the links in the document.
2335
  void RefreshLinkHrefs();
2336
2337
  /**
2338
   * Resets and removes a box object from the document's box object cache
2339
   *
2340
   * @param aElement canonical nsIContent pointer of the box object's element
2341
   */
2342
  void ClearBoxObjectFor(nsIContent* aContent);
2343
2344
  /**
2345
   * Get the box object for an element. This is not exposed through a
2346
   * scriptable interface except for XUL documents.
2347
   */
2348
  already_AddRefed<mozilla::dom::BoxObject>
2349
    GetBoxObjectFor(mozilla::dom::Element* aElement, mozilla::ErrorResult& aRv);
2350
2351
  /**
2352
   * Support for window.matchMedia()
2353
   */
2354
2355
  already_AddRefed<mozilla::dom::MediaQueryList>
2356
    MatchMedia(const nsAString& aMediaQueryList,
2357
               mozilla::dom::CallerType aCallerType);
2358
2359
0
  mozilla::LinkedList<mozilla::dom::MediaQueryList>& MediaQueryLists() {
2360
0
    return mDOMMediaQueryLists;
2361
0
  }
2362
2363
  /**
2364
   * Get the compatibility mode for this document
2365
   */
2366
0
  nsCompatibility GetCompatibilityMode() const {
2367
0
    return mCompatMode;
2368
0
  }
2369
2370
  /**
2371
   * Check whether we've ever fired a DOMTitleChanged event for this
2372
   * document.
2373
   */
2374
  bool HaveFiredDOMTitleChange() const
2375
0
  {
2376
0
    return mHaveFiredTitleChange;
2377
0
  }
2378
2379
  Element* GetAnonymousElementByAttribute(nsIContent* aElement,
2380
                                          nsAtom* aAttrName,
2381
                                          const nsAString& aAttrValue) const;
2382
2383
  nsresult NodesFromRectHelper(float aX, float aY,
2384
                               float aTopSize, float aRightSize,
2385
                               float aBottomSize, float aLeftSize,
2386
                               bool aIgnoreRootScrollFrame,
2387
                               bool aFlushLayout,
2388
                               nsINodeList** aReturn);
2389
2390
  /**
2391
   * See FlushSkinBindings on nsBindingManager
2392
   */
2393
  void FlushSkinBindings();
2394
2395
  /**
2396
   * To batch DOMSubtreeModified, document needs to be informed when
2397
   * a mutation event might be dispatched, even if the event isn't actually
2398
   * created because there are no listeners for it.
2399
   *
2400
   * @param aTarget is the target for the mutation event.
2401
   */
2402
  void MayDispatchMutationEvent(nsINode* aTarget)
2403
0
  {
2404
0
    if (mSubtreeModifiedDepth > 0) {
2405
0
      mSubtreeModifiedTargets.AppendObject(aTarget);
2406
0
    }
2407
0
  }
2408
2409
  /**
2410
   * Marks as not-going-to-be-collected for the given generation of
2411
   * cycle collection.
2412
   */
2413
  void MarkUncollectableForCCGeneration(uint32_t aGeneration)
2414
0
  {
2415
0
    mMarkedCCGeneration = aGeneration;
2416
0
  }
2417
2418
  /**
2419
   * Gets the cycle collector generation this document is marked for.
2420
   */
2421
  uint32_t GetMarkedCCGeneration()
2422
0
  {
2423
0
    return mMarkedCCGeneration;
2424
0
  }
2425
2426
  /**
2427
   * Returns whether this document is cookie averse. See
2428
   * https://html.spec.whatwg.org/multipage/dom.html#cookie-averse-document-object
2429
   */
2430
  bool IsCookieAverse() const
2431
0
  {
2432
0
    // If we are a document that "has no browsing context."
2433
0
    if (!GetInnerWindow()) {
2434
0
      return true;
2435
0
    }
2436
0
2437
0
    // If we are a document "whose URL's scheme is not a network scheme."
2438
0
    // NB: Explicitly allow file: URIs to store cookies.
2439
0
    nsCOMPtr<nsIURI> codebaseURI;
2440
0
    NodePrincipal()->GetURI(getter_AddRefs(codebaseURI));
2441
0
2442
0
    if (!codebaseURI) {
2443
0
      return true;
2444
0
    }
2445
0
2446
0
    nsAutoCString scheme;
2447
0
    codebaseURI->GetScheme(scheme);
2448
0
    return !scheme.EqualsLiteral("http") &&
2449
0
           !scheme.EqualsLiteral("https") &&
2450
0
           !scheme.EqualsLiteral("ftp") &&
2451
0
           !scheme.EqualsLiteral("file");
2452
0
  }
2453
2454
  bool IsLoadedAsData()
2455
0
  {
2456
0
    return mLoadedAsData;
2457
0
  }
2458
2459
  bool IsLoadedAsInteractiveData()
2460
0
  {
2461
0
    return mLoadedAsInteractiveData;
2462
0
  }
2463
2464
  bool MayStartLayout()
2465
0
  {
2466
0
    return mMayStartLayout;
2467
0
  }
2468
2469
  virtual void SetMayStartLayout(bool aMayStartLayout);
2470
2471
  already_AddRefed<nsIDocumentEncoder> GetCachedEncoder();
2472
2473
  void SetCachedEncoder(already_AddRefed<nsIDocumentEncoder> aEncoder);
2474
2475
  // In case of failure, the document really can't initialize the frame loader.
2476
  nsresult InitializeFrameLoader(nsFrameLoader* aLoader);
2477
  // In case of failure, the caller must handle the error, for example by
2478
  // finalizing frame loader asynchronously.
2479
  nsresult FinalizeFrameLoader(nsFrameLoader* aLoader, nsIRunnable* aFinalizer);
2480
  // Removes the frame loader of aShell from the initialization list.
2481
  void TryCancelFrameLoaderInitialization(nsIDocShell* aShell);
2482
2483
  /**
2484
   * Check whether this document is a root document that is not an
2485
   * external resource.
2486
   */
2487
  bool IsRootDisplayDocument() const
2488
0
  {
2489
0
    return !mParentDocument && !mDisplayDocument;
2490
0
  }
2491
2492
0
  bool IsBeingUsedAsImage() const {
2493
0
    return mIsBeingUsedAsImage;
2494
0
  }
2495
2496
0
  void SetIsBeingUsedAsImage() {
2497
0
    mIsBeingUsedAsImage = true;
2498
0
  }
2499
2500
  bool IsSVGGlyphsDocument() const
2501
0
  {
2502
0
    return mIsSVGGlyphsDocument;
2503
0
  }
2504
2505
  void SetIsSVGGlyphsDocument()
2506
0
  {
2507
0
    mIsSVGGlyphsDocument = true;
2508
0
  }
2509
2510
0
  bool IsResourceDoc() const {
2511
0
    return IsBeingUsedAsImage() || // Are we a helper-doc for an SVG image?
2512
0
      mHasDisplayDocument;         // Are we an external resource doc?
2513
0
  }
2514
2515
  /**
2516
   * Get the document for which this document is an external resource.  This
2517
   * will be null if this document is not an external resource.  Otherwise,
2518
   * GetDisplayDocument() will return a non-null document, and
2519
   * GetDisplayDocument()->GetDisplayDocument() is guaranteed to be null.
2520
   */
2521
  nsIDocument* GetDisplayDocument() const
2522
0
  {
2523
0
    return mDisplayDocument;
2524
0
  }
2525
2526
  /**
2527
   * Set the display document for this document.  aDisplayDocument must not be
2528
   * null.
2529
   */
2530
  void SetDisplayDocument(nsIDocument* aDisplayDocument)
2531
0
  {
2532
0
    MOZ_ASSERT(!GetShell() &&
2533
0
               !GetContainer() &&
2534
0
               !GetWindow(),
2535
0
               "Shouldn't set mDisplayDocument on documents that already "
2536
0
               "have a presentation or a docshell or a window");
2537
0
    MOZ_ASSERT(aDisplayDocument, "Must not be null");
2538
0
    MOZ_ASSERT(aDisplayDocument != this, "Should be different document");
2539
0
    MOZ_ASSERT(!aDisplayDocument->GetDisplayDocument(),
2540
0
               "Display documents should not nest");
2541
0
    mDisplayDocument = aDisplayDocument;
2542
0
    mHasDisplayDocument = !!aDisplayDocument;
2543
0
  }
2544
2545
  /**
2546
   * Request an external resource document for aURI.  This will return the
2547
   * resource document if available.  If one is not available yet, it will
2548
   * start loading as needed, and the pending load object will be returned in
2549
   * aPendingLoad so that the caller can register an observer to wait for the
2550
   * load.  If this function returns null and doesn't return a pending load,
2551
   * that means that there is no resource document for this URI and won't be
2552
   * one in the future.
2553
   *
2554
   * @param aURI the URI to get
2555
   * @param aReferrer the referrer of the request
2556
   * @param aReferrerPolicy the referrer policy of the request
2557
   * @param aRequestingNode the node making the request
2558
   * @param aPendingLoad the pending load for this request, if any
2559
   */
2560
  nsIDocument* RequestExternalResource(nsIURI* aURI,
2561
                                       nsIURI* aReferrer,
2562
                                       uint32_t aReferrerPolicy,
2563
                                       nsINode* aRequestingNode,
2564
                                       ExternalResourceLoad** aPendingLoad);
2565
2566
  /**
2567
   * Enumerate the external resource documents associated with this document.
2568
   * The enumerator callback should return true to continue enumerating, or
2569
   * false to stop.  This callback will never get passed a null aDocument.
2570
   */
2571
  void EnumerateExternalResources(nsSubDocEnumFunc aCallback, void* aData);
2572
2573
  nsExternalResourceMap& ExternalResourceMap()
2574
0
  {
2575
0
    return mExternalResourceMap;
2576
0
  }
2577
2578
  /**
2579
   * Return whether the document is currently showing (in the sense of
2580
   * OnPageShow() having been called already and OnPageHide() not having been
2581
   * called yet.
2582
   */
2583
0
  bool IsShowing() const { return mIsShowing; }
2584
  /**
2585
   * Return whether the document is currently visible (in the sense of
2586
   * OnPageHide having been called and OnPageShow not yet having been called)
2587
   */
2588
0
  bool IsVisible() const { return mVisible; }
2589
2590
  /**
2591
   * Return whether the document and all its ancestors are visible in the sense of
2592
   * pageshow / hide.
2593
   */
2594
  bool IsVisibleConsideringAncestors() const;
2595
2596
  /**
2597
   * Return true when this document is active, i.e., an active document
2598
   * in a content viewer.  Note that this will return true for bfcached
2599
   * documents, so this does NOT match the "active document" concept in
2600
   * the WHATWG spec - see IsCurrentActiveDocument.
2601
   */
2602
0
  bool IsActive() const { return mDocumentContainer && !mRemovedFromDocShell; }
2603
2604
  /**
2605
   * Return true if this is the current active document for its
2606
   * docshell. Note that a docshell may have multiple active documents
2607
   * due to the bfcache -- this should be used when you need to
2608
   * differentiate the *current* active document from any active
2609
   * documents.
2610
   */
2611
  bool IsCurrentActiveDocument() const
2612
0
  {
2613
0
    nsPIDOMWindowInner* inner = GetInnerWindow();
2614
0
    return inner && inner->IsCurrentInnerWindow() && inner->GetDoc() == this;
2615
0
  }
2616
2617
  /**
2618
   * Returns whether this document should perform image loads.
2619
   */
2620
  bool ShouldLoadImages() const
2621
0
  {
2622
0
    // We check IsBeingUsedAsImage() so that SVG documents loaded as
2623
0
    // images can themselves have data: URL image references.
2624
0
    return IsCurrentActiveDocument() || IsBeingUsedAsImage();
2625
0
  }
2626
2627
  /**
2628
   * Register/Unregister the ActivityObserver into mActivityObservers to listen
2629
   * the document's activity changes such as OnPageHide, visibility, activity.
2630
   * The ActivityObserver objects can be nsIObjectLoadingContent or
2631
   * nsIDocumentActivity or HTMLMEdiaElement.
2632
   */
2633
  void RegisterActivityObserver(nsISupports* aSupports);
2634
  bool UnregisterActivityObserver(nsISupports* aSupports);
2635
  // Enumerate all the observers in mActivityObservers by the aEnumerator.
2636
  typedef void (* ActivityObserverEnumerator)(nsISupports*, void*);
2637
  void EnumerateActivityObservers(ActivityObserverEnumerator aEnumerator,
2638
                                  void* aData);
2639
2640
  // Indicates whether mAnimationController has been (lazily) initialized.
2641
  // If this returns true, we're promising that GetAnimationController()
2642
  // will have a non-null return value.
2643
0
  bool HasAnimationController()  { return !!mAnimationController; }
2644
2645
  // Getter for this document's SMIL Animation Controller. Performs lazy
2646
  // initialization, if this document supports animation and if
2647
  // mAnimationController isn't yet initialized.
2648
  //
2649
  // If HasAnimationController is true, this is guaranteed to return non-null.
2650
  nsSMILAnimationController* GetAnimationController();
2651
2652
  // Gets the tracker for animations that are waiting to start.
2653
  // Returns nullptr if there is no pending animation tracker for this document
2654
  // which will be the case if there have never been any CSS animations or
2655
  // transitions on elements in the document.
2656
  mozilla::PendingAnimationTracker* GetPendingAnimationTracker()
2657
0
  {
2658
0
    return mPendingAnimationTracker;
2659
0
  }
2660
2661
  // Gets the tracker for animations that are waiting to start and
2662
  // creates it if it doesn't already exist. As a result, the return value
2663
  // will never be nullptr.
2664
  mozilla::PendingAnimationTracker* GetOrCreatePendingAnimationTracker();
2665
2666
  /**
2667
   * Prevents user initiated events from being dispatched to the document and
2668
   * subdocuments.
2669
   */
2670
  void SuppressEventHandling(uint32_t aIncrease = 1);
2671
2672
  /**
2673
   * Unsuppress event handling.
2674
   * @param aFireEvents If true, delayed events (focus/blur) will be fired
2675
   *                    asynchronously.
2676
   */
2677
  void UnsuppressEventHandlingAndFireEvents(bool aFireEvents);
2678
2679
0
  uint32_t EventHandlingSuppressed() const { return mEventsSuppressed; }
2680
2681
0
  bool IsEventHandlingEnabled() {
2682
0
    return !EventHandlingSuppressed() && mScriptGlobalObject;
2683
0
  }
2684
2685
  void DecreaseEventSuppression()
2686
0
  {
2687
0
    MOZ_ASSERT(mEventsSuppressed);
2688
0
    --mEventsSuppressed;
2689
0
    UpdateFrameRequestCallbackSchedulingState();
2690
0
  }
2691
2692
  /**
2693
   * Increment https://html.spec.whatwg.org/#ignore-destructive-writes-counter
2694
   */
2695
0
  void IncrementIgnoreDestructiveWritesCounter() { ++mIgnoreDestructiveWritesCounter; }
2696
2697
  /**
2698
   * Decrement https://html.spec.whatwg.org/#ignore-destructive-writes-counter
2699
   */
2700
0
  void DecrementIgnoreDestructiveWritesCounter() { --mIgnoreDestructiveWritesCounter; }
2701
2702
0
  bool IsDNSPrefetchAllowed() const { return mAllowDNSPrefetch; }
2703
2704
  /**
2705
   * Returns true if this document is allowed to contain XUL element and
2706
   * use non-builtin XBL bindings.
2707
   */
2708
0
  bool AllowXULXBL() {
2709
0
    return mAllowXULXBL == eTriTrue ? true :
2710
0
           mAllowXULXBL == eTriFalse ? false :
2711
0
           InternalAllowXULXBL();
2712
0
  }
2713
2714
0
  void ForceEnableXULXBL() {
2715
0
    mAllowXULXBL = eTriTrue;
2716
0
  }
2717
2718
  /**
2719
   * Returns the template content owner document that owns the content of
2720
   * HTMLTemplateElement.
2721
   */
2722
  nsIDocument* GetTemplateContentsOwner();
2723
2724
  /**
2725
   * Returns true if this document is a static clone of a normal document.
2726
   *
2727
   * We create static clones for print preview and printing (possibly other
2728
   * things in future).
2729
   *
2730
   * Note that static documents are also "loaded as data" (if this method
2731
   * returns true, IsLoadedAsData() will also return true).
2732
   */
2733
0
  bool IsStaticDocument() { return mIsStaticDocument; }
2734
2735
  /**
2736
   * Clones the document along with any subdocuments, stylesheet, etc.
2737
   *
2738
   * The resulting document and everything it contains (including any
2739
   * sub-documents) are created purely via cloning.  The returned documents and
2740
   * any sub-documents are "loaded as data" documents to preserve the state as
2741
   * it was during the clone process (we don't want external resources to load
2742
   * and replace the cloned resources).
2743
   *
2744
   * @param aCloneContainer The container for the clone document.
2745
   */
2746
  virtual already_AddRefed<nsIDocument>
2747
  CreateStaticClone(nsIDocShell* aCloneContainer);
2748
2749
  /**
2750
   * If this document is a static clone, this returns the original
2751
   * document.
2752
   */
2753
  nsIDocument* GetOriginalDocument()
2754
0
  {
2755
0
    MOZ_ASSERT(!mOriginalDocument || !mOriginalDocument->GetOriginalDocument());
2756
0
    return mOriginalDocument;
2757
0
  }
2758
2759
  /**
2760
   * If this document is a static clone, let the original document know that
2761
   * we're going away and then release our reference to it.
2762
   */
2763
  void UnlinkOriginalDocumentIfStatic();
2764
2765
  /**
2766
   * These are called by the parser as it encounters <picture> tags, the end of
2767
   * said tags, and possible picture <source srcset> sources respectively. These
2768
   * are used to inform ResolvePreLoadImage() calls.  Unset attributes are
2769
   * expected to be marked void.
2770
   *
2771
   * NOTE that the parser does not attempt to track the current picture nesting
2772
   * level or whether the given <source> tag is within a picture -- it is only
2773
   * guaranteed to order these calls properly with respect to
2774
   * ResolvePreLoadImage.
2775
   */
2776
2777
  void PreloadPictureOpened()
2778
0
  {
2779
0
    mPreloadPictureDepth++;
2780
0
  }
2781
2782
  void PreloadPictureClosed();
2783
2784
  void PreloadPictureImageSource(const nsAString& aSrcsetAttr,
2785
                                 const nsAString& aSizesAttr,
2786
                                 const nsAString& aTypeAttr,
2787
                                 const nsAString& aMediaAttr);
2788
2789
  /**
2790
   * Called by the parser to resolve an image for preloading. The parser will
2791
   * call the PreloadPicture* functions to inform us of possible <picture>
2792
   * nesting and possible sources, which are used to inform URL selection
2793
   * responsive <picture> or <img srcset> images.  Unset attributes are expected
2794
   * to be marked void.
2795
   * If this image is for <picture> or <img srcset>, aIsImgSet will be set to
2796
   * true, false otherwise.
2797
   */
2798
  already_AddRefed<nsIURI>
2799
  ResolvePreloadImage(nsIURI *aBaseURI,
2800
                      const nsAString& aSrcAttr,
2801
                      const nsAString& aSrcsetAttr,
2802
                      const nsAString& aSizesAttr,
2803
                      bool *aIsImgSet);
2804
  /**
2805
   * Called by nsParser to preload images. Can be removed and code moved
2806
   * to nsPreloadURIs::PreloadURIs() in file nsParser.cpp whenever the
2807
   * parser-module is linked with gklayout-module.  aCrossOriginAttr should
2808
   * be a void string if the attr is not present.
2809
   * aIsImgSet is the value got from calling ResolvePreloadImage, it is true
2810
   * when this image is for loading <picture> or <img srcset> images.
2811
   */
2812
  void MaybePreLoadImage(nsIURI* uri,
2813
                         const nsAString& aCrossOriginAttr,
2814
                         ReferrerPolicyEnum aReferrerPolicy,
2815
                         bool aIsImgSet);
2816
2817
  /**
2818
   * Called by images to forget an image preload when they start doing
2819
   * the real load.
2820
   */
2821
  void ForgetImagePreload(nsIURI* aURI);
2822
2823
  /**
2824
   * Called by nsParser to preload style sheets.  Can also be merged into the
2825
   * parser if and when the parser is merged with libgklayout.  aCrossOriginAttr
2826
   * should be a void string if the attr is not present.
2827
   */
2828
  void PreloadStyle(nsIURI* aURI,
2829
                    const mozilla::Encoding* aEncoding,
2830
                    const nsAString& aCrossOriginAttr,
2831
                    ReferrerPolicyEnum aReferrerPolicy,
2832
                    const nsAString& aIntegrity);
2833
2834
  /**
2835
   * Called by the chrome registry to load style sheets.  Can be put
2836
   * back there if and when when that module is merged with libgklayout.
2837
   *
2838
   * This always does a synchronous load.  If aIsAgentSheet is true,
2839
   * it also uses the system principal and enables unsafe rules.
2840
   * DO NOT USE FOR UNTRUSTED CONTENT.
2841
   */
2842
  nsresult LoadChromeSheetSync(nsIURI* aURI, bool aIsAgentSheet,
2843
                               RefPtr<mozilla::StyleSheet>* aSheet);
2844
2845
  /**
2846
   * Returns true if the locale used for the document specifies a direction of
2847
   * right to left. For chrome documents, this comes from the chrome registry.
2848
   * This is used to determine the current state for the :-moz-locale-dir pseudoclass
2849
   * so once can know whether a document is expected to be rendered left-to-right
2850
   * or right-to-left.
2851
   */
2852
0
  virtual bool IsDocumentRightToLeft() { return false; }
2853
2854
  /**
2855
   * Called by Parser for link rel=preconnect
2856
   */
2857
  void MaybePreconnect(nsIURI* uri, mozilla::CORSMode aCORSMode);
2858
2859
  enum DocumentTheme {
2860
    Doc_Theme_Uninitialized, // not determined yet
2861
    Doc_Theme_None,
2862
    Doc_Theme_Neutral,
2863
    Doc_Theme_Dark,
2864
    Doc_Theme_Bright
2865
  };
2866
2867
  /**
2868
   * Set the document's pending state object (as serialized using structured
2869
   * clone).
2870
   */
2871
  void SetStateObject(nsIStructuredCloneContainer *scContainer);
2872
2873
  /**
2874
   * Returns Doc_Theme_None if there is no lightweight theme specified,
2875
   * Doc_Theme_Dark for a dark theme, Doc_Theme_Bright for a light theme, and
2876
   * Doc_Theme_Neutral for any other theme. This is used to determine the state
2877
   * of the pseudoclasses :-moz-lwtheme and :-moz-lwtheme-text.
2878
   */
2879
  DocumentTheme GetDocumentLWTheme();
2880
  DocumentTheme ThreadSafeGetDocumentLWTheme() const;
2881
0
  void ResetDocumentLWTheme() { mDocLWTheme = Doc_Theme_Uninitialized; }
2882
2883
  // Whether we're a media document or not.
2884
  enum class MediaDocumentKind
2885
  {
2886
    NotMedia,
2887
    Video,
2888
    Image,
2889
    Plugin,
2890
  };
2891
2892
  virtual enum MediaDocumentKind MediaDocumentKind() const
2893
0
  {
2894
0
    return MediaDocumentKind::NotMedia;
2895
0
  }
2896
2897
  /**
2898
   * Returns the document state.
2899
   * Document state bits have the form NS_DOCUMENT_STATE_* and are declared in
2900
   * nsIDocument.h.
2901
   */
2902
  mozilla::EventStates GetDocumentState() const
2903
  {
2904
    return mDocumentState;
2905
  }
2906
2907
  nsISupports* GetCurrentContentSink();
2908
2909
  void SetAutoFocusElement(Element* aAutoFocusElement);
2910
  void TriggerAutoFocus();
2911
2912
  void SetScrollToRef(nsIURI* aDocumentURI);
2913
  void ScrollToRef();
2914
  void ResetScrolledToRefAlready()
2915
0
  {
2916
0
    mScrolledToRefAlready = false;
2917
0
  }
2918
2919
  void SetChangeScrollPosWhenScrollingToRef(bool aValue)
2920
0
  {
2921
0
    mChangeScrollPosWhenScrollingToRef = aValue;
2922
0
  }
2923
2924
  using mozilla::dom::DocumentOrShadowRoot::GetElementById;
2925
  using mozilla::dom::DocumentOrShadowRoot::GetElementsByTagName;
2926
  using mozilla::dom::DocumentOrShadowRoot::GetElementsByTagNameNS;
2927
  using mozilla::dom::DocumentOrShadowRoot::GetElementsByClassName;
2928
2929
  mozilla::dom::DocumentTimeline* Timeline();
2930
  mozilla::LinkedList<mozilla::dom::DocumentTimeline>& Timelines()
2931
0
  {
2932
0
    return mTimelines;
2933
0
  }
2934
2935
  void GetAnimations(nsTArray<RefPtr<mozilla::dom::Animation>>& aAnimations);
2936
2937
  mozilla::dom::SVGSVGElement* GetSVGRootElement() const;
2938
2939
  nsresult ScheduleFrameRequestCallback(mozilla::dom::FrameRequestCallback& aCallback,
2940
                                        int32_t *aHandle);
2941
  void CancelFrameRequestCallback(int32_t aHandle);
2942
2943
  typedef nsTArray<RefPtr<mozilla::dom::FrameRequestCallback>> FrameRequestCallbackList;
2944
  /**
2945
   * Put this document's frame request callbacks into the provided
2946
   * list, and forget about them.
2947
   */
2948
  void TakeFrameRequestCallbacks(FrameRequestCallbackList& aCallbacks);
2949
2950
  /**
2951
   * @return true if this document's frame request callbacks should be
2952
   * throttled. We throttle requestAnimationFrame for documents which aren't
2953
   * visible (e.g. scrolled out of the viewport).
2954
   */
2955
  bool ShouldThrottleFrameRequests();
2956
2957
  // This returns true when the document tree is being teared down.
2958
0
  bool InUnlinkOrDeletion() { return mInUnlinkOrDeletion; }
2959
2960
  mozilla::dom::ImageTracker* ImageTracker();
2961
2962
  // AddPlugin adds a plugin-related element to mPlugins when the element is
2963
  // added to the tree.
2964
  void AddPlugin(nsIObjectLoadingContent* aPlugin)
2965
0
  {
2966
0
    MOZ_ASSERT(aPlugin);
2967
0
    mPlugins.PutEntry(aPlugin);
2968
0
  }
2969
2970
  // RemovePlugin removes a plugin-related element to mPlugins when the
2971
  // element is removed from the tree.
2972
  void RemovePlugin(nsIObjectLoadingContent* aPlugin)
2973
0
  {
2974
0
    MOZ_ASSERT(aPlugin);
2975
0
    mPlugins.RemoveEntry(aPlugin);
2976
0
  }
2977
2978
  // GetPlugins returns the plugin-related elements from
2979
  // the frame and any subframes.
2980
  void GetPlugins(nsTArray<nsIObjectLoadingContent*>& aPlugins);
2981
2982
  // Adds an element to mResponsiveContent when the element is
2983
  // added to the tree.
2984
  void AddResponsiveContent(mozilla::dom::HTMLImageElement* aContent)
2985
0
  {
2986
0
    MOZ_ASSERT(aContent);
2987
0
    mResponsiveContent.PutEntry(aContent);
2988
0
  }
2989
2990
  // Removes an element from mResponsiveContent when the element is
2991
  // removed from the tree.
2992
  void RemoveResponsiveContent(mozilla::dom::HTMLImageElement* aContent)
2993
0
  {
2994
0
    MOZ_ASSERT(aContent);
2995
0
    mResponsiveContent.RemoveEntry(aContent);
2996
0
  }
2997
2998
  void ScheduleSVGUseElementShadowTreeUpdate(mozilla::dom::SVGUseElement&);
2999
  void UnscheduleSVGUseElementShadowTreeUpdate(mozilla::dom::SVGUseElement& aElement)
3000
0
  {
3001
0
    mSVGUseElementsNeedingShadowTreeUpdate.RemoveEntry(&aElement);
3002
0
  }
3003
3004
  bool SVGUseElementNeedsShadowTreeUpdate(mozilla::dom::SVGUseElement& aElement) const
3005
0
  {
3006
0
    return mSVGUseElementsNeedingShadowTreeUpdate.GetEntry(&aElement);
3007
0
  }
3008
3009
  using ShadowRootSet = nsTHashtable<nsPtrHashKey<mozilla::dom::ShadowRoot>>;
3010
3011
  void AddComposedDocShadowRoot(mozilla::dom::ShadowRoot& aShadowRoot)
3012
0
  {
3013
0
    mComposedShadowRoots.PutEntry(&aShadowRoot);
3014
0
  }
3015
3016
  void RemoveComposedDocShadowRoot(mozilla::dom::ShadowRoot& aShadowRoot)
3017
0
  {
3018
0
    mComposedShadowRoots.RemoveEntry(&aShadowRoot);
3019
0
  }
3020
3021
  // If you're considering using this, you probably want to use
3022
  // ShadowRoot::IsComposedDocParticipant instead. This is just for
3023
  // sanity-checking.
3024
  bool IsComposedDocShadowRoot(mozilla::dom::ShadowRoot& aShadowRoot)
3025
0
  {
3026
0
    return mComposedShadowRoots.Contains(&aShadowRoot);
3027
0
  }
3028
3029
  const ShadowRootSet& ComposedShadowRoots() const
3030
0
  {
3031
0
    return mComposedShadowRoots;
3032
0
  }
3033
3034
  // Notifies any responsive content added by AddResponsiveContent upon media
3035
  // features values changing.
3036
  void NotifyMediaFeatureValuesChanged();
3037
3038
  nsresult GetStateObject(nsIVariant** aResult);
3039
3040
  nsDOMNavigationTiming* GetNavigationTiming() const
3041
0
  {
3042
0
    return mTiming;
3043
0
  }
3044
3045
  void SetNavigationTiming(nsDOMNavigationTiming* aTiming);
3046
3047
  nsContentList* ImageMapList();
3048
3049
  // Add aLink to the set of links that need their status resolved.
3050
  void RegisterPendingLinkUpdate(mozilla::dom::Link* aLink);
3051
3052
  // Update state on links in mLinksToUpdate.  This function must be called
3053
  // prior to selector matching that needs to differentiate between :link and
3054
  // :visited.  In particular, it does _not_ need to be called before doing any
3055
  // selector matching that uses TreeMatchContext::eNeverMatchVisited.  The only
3056
  // reason we haven't moved all calls to this function entirely inside the
3057
  // TreeMatchContext constructor is to not call it all the time during various
3058
  // style system and frame construction operations (though it would likely be a
3059
  // no-op for all but the first call).
3060
  //
3061
  // XXXbz Does this really need to be called before selector matching?  All it
3062
  // will do is ensure all the links involved are registered to observe history,
3063
  // which won't synchronously change their state to :visited anyway!  So
3064
  // calling this won't affect selector matching done immediately afterward, as
3065
  // far as I can tell.
3066
  void FlushPendingLinkUpdates();
3067
3068
  void FlushPendingLinkUpdatesFromRunnable();
3069
3070
#define DEPRECATED_OPERATION(_op) e##_op,
3071
  enum DeprecatedOperations {
3072
#include "nsDeprecatedOperationList.h"
3073
    eDeprecatedOperationCount
3074
  };
3075
#undef DEPRECATED_OPERATION
3076
  bool HasWarnedAbout(DeprecatedOperations aOperation) const;
3077
  void WarnOnceAbout(DeprecatedOperations aOperation,
3078
                     bool asError = false) const;
3079
3080
#define DOCUMENT_WARNING(_op) e##_op,
3081
  enum DocumentWarnings {
3082
#include "nsDocumentWarningList.h"
3083
    eDocumentWarningCount
3084
  };
3085
#undef DOCUMENT_WARNING
3086
  bool HasWarnedAbout(DocumentWarnings aWarning) const;
3087
  void WarnOnceAbout(DocumentWarnings aWarning,
3088
                     bool asError = false,
3089
                     const char16_t **aParams = nullptr,
3090
                     uint32_t aParamsLength = 0) const;
3091
3092
  // Posts an event to call UpdateVisibilityState
3093
  void PostVisibilityUpdateEvent();
3094
3095
0
  bool IsSyntheticDocument() const { return mIsSyntheticDocument; }
3096
3097
  // Adds the size of a given node, which must not be a document node, to the
3098
  // window sizes passed-in.
3099
  static void AddSizeOfNodeTree(nsINode&, nsWindowSizes&);
3100
3101
  // Note: nsIDocument is a sub-class of nsINode, which has a
3102
  // SizeOfExcludingThis function.  However, because nsIDocument objects can
3103
  // only appear at the top of the DOM tree, we have a specialized measurement
3104
  // function which returns multiple sizes.
3105
  virtual void DocAddSizeOfExcludingThis(nsWindowSizes& aWindowSizes) const;
3106
  // DocAddSizeOfIncludingThis doesn't need to be overridden by sub-classes
3107
  // because nsIDocument inherits from nsINode;  see the comment above the
3108
  // declaration of nsINode::SizeOfIncludingThis.
3109
  virtual void DocAddSizeOfIncludingThis(nsWindowSizes& aWindowSizes) const;
3110
3111
  void ConstructUbiNode(void* storage) override;
3112
3113
  bool MayHaveDOMMutationObservers()
3114
0
  {
3115
0
    return mMayHaveDOMMutationObservers;
3116
0
  }
3117
3118
  void SetMayHaveDOMMutationObservers()
3119
0
  {
3120
0
    mMayHaveDOMMutationObservers = true;
3121
0
  }
3122
3123
  bool MayHaveAnimationObservers()
3124
0
  {
3125
0
    return mMayHaveAnimationObservers;
3126
0
  }
3127
3128
  void SetMayHaveAnimationObservers()
3129
0
  {
3130
0
    mMayHaveAnimationObservers = true;
3131
0
  }
3132
3133
  bool IsInSyncOperation()
3134
0
  {
3135
0
    return mInSyncOperationCount != 0;
3136
0
  }
3137
3138
  void SetIsInSyncOperation(bool aSync)
3139
0
  {
3140
0
    if (aSync) {
3141
0
      ++mInSyncOperationCount;
3142
0
    } else {
3143
0
      --mInSyncOperationCount;
3144
0
    }
3145
0
  }
3146
3147
  bool CreatingStaticClone() const
3148
0
  {
3149
0
    return mCreatingStaticClone;
3150
0
  }
3151
3152
  /**
3153
   * Creates a new element in the HTML namespace with a local name given by
3154
   * aTag.
3155
   */
3156
  already_AddRefed<Element> CreateHTMLElement(nsAtom* aTag);
3157
3158
  // WebIDL API
3159
  nsIGlobalObject* GetParentObject() const
3160
0
  {
3161
0
    return GetScopeObject();
3162
0
  }
3163
  static already_AddRefed<nsIDocument>
3164
    Constructor(const GlobalObject& aGlobal,
3165
                mozilla::ErrorResult& rv);
3166
  mozilla::dom::DOMImplementation* GetImplementation(mozilla::ErrorResult& rv);
3167
  MOZ_MUST_USE nsresult GetURL(nsString& retval) const;
3168
  MOZ_MUST_USE nsresult GetDocumentURI(nsString& retval) const;
3169
  // Return the URI for the document.
3170
  // The returned value may differ if the document is loaded via XHR, and
3171
  // when accessed from chrome privileged script and
3172
  // from content privileged script for compatibility.
3173
  void GetDocumentURIFromJS(nsString& aDocumentURI,
3174
                            mozilla::dom::CallerType aCallerType,
3175
                            mozilla::ErrorResult& aRv) const;
3176
  void GetCompatMode(nsString& retval) const;
3177
  void GetCharacterSet(nsAString& retval) const;
3178
  // Skip GetContentType, because our NS_IMETHOD version above works fine here.
3179
  // GetDoctype defined above
3180
  Element* GetDocumentElement() const
3181
0
  {
3182
0
    return GetRootElement();
3183
0
  }
3184
3185
  enum ElementCallbackType {
3186
    eConnected,
3187
    eDisconnected,
3188
    eAdopted,
3189
    eAttributeChanged,
3190
    eGetCustomInterface
3191
  };
3192
3193
  nsIDocument* GetTopLevelContentDocument();
3194
3195
  // Returns the associated XUL window if this is a top-level chrome document,
3196
  // null otherwise.
3197
  already_AddRefed<nsIXULWindow> GetXULWindowIfToplevelChrome() const;
3198
3199
  already_AddRefed<Element>
3200
  CreateElement(const nsAString& aTagName,
3201
                const mozilla::dom::ElementCreationOptionsOrString& aOptions,
3202
                mozilla::ErrorResult& rv);
3203
  already_AddRefed<Element>
3204
  CreateElementNS(const nsAString& aNamespaceURI,
3205
                  const nsAString& aQualifiedName,
3206
                  const mozilla::dom::ElementCreationOptionsOrString& aOptions,
3207
                  mozilla::ErrorResult& rv);
3208
  already_AddRefed<Element>
3209
  CreateXULElement(const nsAString& aTagName,
3210
                   const mozilla::dom::ElementCreationOptionsOrString& aOptions,
3211
                   mozilla::ErrorResult& aRv);
3212
  already_AddRefed<mozilla::dom::DocumentFragment>
3213
    CreateDocumentFragment() const;
3214
  already_AddRefed<nsTextNode> CreateTextNode(const nsAString& aData) const;
3215
  already_AddRefed<nsTextNode> CreateEmptyTextNode() const;
3216
  already_AddRefed<mozilla::dom::Comment>
3217
    CreateComment(const nsAString& aData) const;
3218
  already_AddRefed<mozilla::dom::ProcessingInstruction>
3219
    CreateProcessingInstruction(const nsAString& target, const nsAString& data,
3220
                                mozilla::ErrorResult& rv) const;
3221
  already_AddRefed<nsINode>
3222
    ImportNode(nsINode& aNode, bool aDeep, mozilla::ErrorResult& rv) const;
3223
  nsINode* AdoptNode(nsINode& aNode, mozilla::ErrorResult& rv);
3224
  already_AddRefed<mozilla::dom::Event>
3225
    CreateEvent(const nsAString& aEventType,
3226
                mozilla::dom::CallerType aCallerType,
3227
                mozilla::ErrorResult& rv) const;
3228
  already_AddRefed<nsRange> CreateRange(mozilla::ErrorResult& rv);
3229
  already_AddRefed<mozilla::dom::NodeIterator>
3230
    CreateNodeIterator(nsINode& aRoot, uint32_t aWhatToShow,
3231
                       mozilla::dom::NodeFilter* aFilter,
3232
                       mozilla::ErrorResult& rv) const;
3233
  already_AddRefed<mozilla::dom::TreeWalker>
3234
    CreateTreeWalker(nsINode& aRoot, uint32_t aWhatToShow,
3235
                     mozilla::dom::NodeFilter* aFilter, mozilla::ErrorResult& rv) const;
3236
  // Deprecated WebIDL bits
3237
  already_AddRefed<mozilla::dom::CDATASection>
3238
    CreateCDATASection(const nsAString& aData, mozilla::ErrorResult& rv);
3239
  already_AddRefed<mozilla::dom::Attr>
3240
    CreateAttribute(const nsAString& aName, mozilla::ErrorResult& rv);
3241
  already_AddRefed<mozilla::dom::Attr>
3242
    CreateAttributeNS(const nsAString& aNamespaceURI,
3243
                      const nsAString& aQualifiedName,
3244
                      mozilla::ErrorResult& rv);
3245
  void GetInputEncoding(nsAString& aInputEncoding) const;
3246
  already_AddRefed<mozilla::dom::Location> GetLocation() const;
3247
  void GetReferrer(nsAString& aReferrer) const;
3248
  void GetLastModified(nsAString& aLastModified) const;
3249
  void GetReadyState(nsAString& aReadyState) const;
3250
3251
  void GetTitle(nsAString& aTitle);
3252
  void SetTitle(const nsAString& aTitle, mozilla::ErrorResult& rv);
3253
  void GetDir(nsAString& aDirection) const;
3254
  void SetDir(const nsAString& aDirection);
3255
  nsIHTMLCollection* Images();
3256
  nsIHTMLCollection* Embeds();
3257
  nsIHTMLCollection* Plugins()
3258
0
  {
3259
0
    return Embeds();
3260
0
  }
3261
  nsIHTMLCollection* Links();
3262
  nsIHTMLCollection* Forms();
3263
  nsIHTMLCollection* Scripts();
3264
  already_AddRefed<nsContentList> GetElementsByName(const nsAString& aName)
3265
0
  {
3266
0
    return GetFuncStringContentList<nsCachableElementsByNameNodeList>(this,
3267
0
                                                                      MatchNameAttribute,
3268
0
                                                                      nullptr,
3269
0
                                                                      UseExistingNameString,
3270
0
                                                                      aName);
3271
0
  }
3272
  nsPIDOMWindowOuter* GetDefaultView() const
3273
0
  {
3274
0
    return GetWindow();
3275
0
  }
3276
  Element* GetActiveElement();
3277
  bool HasFocus(mozilla::ErrorResult& rv) const;
3278
  nsIHTMLCollection* Applets();
3279
  nsIHTMLCollection* Anchors();
3280
  mozilla::TimeStamp LastFocusTime() const;
3281
  void SetLastFocusTime(const mozilla::TimeStamp& aFocusTime);
3282
  // Event handlers are all on nsINode already
3283
  bool MozSyntheticDocument() const
3284
0
  {
3285
0
    return IsSyntheticDocument();
3286
0
  }
3287
  Element* GetCurrentScript();
3288
  void ReleaseCapture() const;
3289
  void MozSetImageElement(const nsAString& aImageElementId, Element* aElement);
3290
  nsIURI* GetDocumentURIObject() const;
3291
  // Not const because all the fullscreen goop is not const
3292
  bool FullscreenEnabled(mozilla::dom::CallerType aCallerType);
3293
  Element* FullscreenStackTop();
3294
  bool Fullscreen()
3295
0
  {
3296
0
    return !!GetFullscreenElement();
3297
0
  }
3298
  already_AddRefed<mozilla::dom::Promise> ExitFullscreen(ErrorResult&);
3299
  void ExitPointerLock()
3300
0
  {
3301
0
    UnlockPointer(this);
3302
0
  }
3303
3304
  static bool IsUnprefixedFullscreenEnabled(JSContext* aCx, JSObject* aObject);
3305
3306
#ifdef MOZILLA_INTERNAL_API
3307
  bool Hidden() const
3308
0
  {
3309
0
    return mVisibilityState != mozilla::dom::VisibilityState::Visible;
3310
0
  }
3311
  mozilla::dom::VisibilityState VisibilityState() const
3312
0
  {
3313
0
    return mVisibilityState;
3314
0
  }
3315
#endif
3316
  void GetSelectedStyleSheetSet(nsAString& aSheetSet);
3317
  void SetSelectedStyleSheetSet(const nsAString& aSheetSet);
3318
  void GetLastStyleSheetSet(nsAString& aSheetSet)
3319
0
  {
3320
0
    aSheetSet = mLastStyleSheetSet;
3321
0
  }
3322
  const nsString& GetCurrentStyleSheetSet() const
3323
0
  {
3324
0
    return mLastStyleSheetSet.IsEmpty()
3325
0
      ? mPreferredStyleSheetSet
3326
0
      : mLastStyleSheetSet;
3327
0
  }
3328
  void SetPreferredStyleSheetSet(const nsAString&);
3329
  void GetPreferredStyleSheetSet(nsAString& aSheetSet)
3330
0
  {
3331
0
    aSheetSet = mPreferredStyleSheetSet;
3332
0
  }
3333
  mozilla::dom::DOMStringList* StyleSheetSets();
3334
  void EnableStyleSheetsForSet(const nsAString& aSheetSet);
3335
3336
  /**
3337
   * Retrieve the location of the caret position (DOM node and character
3338
   * offset within that node), given a point.
3339
   *
3340
   * @param aX Horizontal point at which to determine the caret position, in
3341
   *           page coordinates.
3342
   * @param aY Vertical point at which to determine the caret position, in
3343
   *           page coordinates.
3344
   */
3345
  already_AddRefed<nsDOMCaretPosition>
3346
    CaretPositionFromPoint(float aX, float aY);
3347
3348
  Element* GetScrollingElement();
3349
  // A way to check whether a given element is what would get returned from
3350
  // GetScrollingElement.  It can be faster than comparing to the return value
3351
  // of GetScrollingElement() due to being able to avoid flushes in various
3352
  // cases.  This method assumes that null is NOT passed.
3353
  bool IsScrollingElement(Element* aElement);
3354
3355
  // QuerySelector and QuerySelectorAll already defined on nsINode
3356
  nsINodeList* GetAnonymousNodes(Element& aElement);
3357
  Element* GetAnonymousElementByAttribute(Element& aElement,
3358
                                          const nsAString& aAttrName,
3359
                                          const nsAString& aAttrValue);
3360
  Element* GetBindingParent(nsINode& aNode);
3361
  void LoadBindingDocument(const nsAString& aURI,
3362
                           nsIPrincipal& aSubjectPrincipal,
3363
                           mozilla::ErrorResult& rv);
3364
  mozilla::dom::XPathExpression*
3365
    CreateExpression(const nsAString& aExpression,
3366
                     mozilla::dom::XPathNSResolver* aResolver,
3367
                     mozilla::ErrorResult& rv);
3368
  nsINode* CreateNSResolver(nsINode& aNodeResolver);
3369
  already_AddRefed<mozilla::dom::XPathResult>
3370
    Evaluate(JSContext* aCx, const nsAString& aExpression, nsINode& aContextNode,
3371
             mozilla::dom::XPathNSResolver* aResolver, uint16_t aType,
3372
             JS::Handle<JSObject*> aResult, mozilla::ErrorResult& rv);
3373
  // Touch event handlers already on nsINode
3374
  already_AddRefed<mozilla::dom::Touch>
3375
    CreateTouch(nsGlobalWindowInner* aView, mozilla::dom::EventTarget* aTarget,
3376
                int32_t aIdentifier, int32_t aPageX, int32_t aPageY,
3377
                int32_t aScreenX, int32_t aScreenY, int32_t aClientX,
3378
                int32_t aClientY, int32_t aRadiusX, int32_t aRadiusY,
3379
                float aRotationAngle, float aForce);
3380
  already_AddRefed<mozilla::dom::TouchList> CreateTouchList();
3381
  already_AddRefed<mozilla::dom::TouchList>
3382
    CreateTouchList(mozilla::dom::Touch& aTouch,
3383
                    const mozilla::dom::Sequence<mozilla::OwningNonNull<mozilla::dom::Touch> >& aTouches);
3384
  already_AddRefed<mozilla::dom::TouchList>
3385
    CreateTouchList(const mozilla::dom::Sequence<mozilla::OwningNonNull<mozilla::dom::Touch> >& aTouches);
3386
3387
  void SetStyleSheetChangeEventsEnabled(bool aValue)
3388
0
  {
3389
0
    mStyleSheetChangeEventsEnabled = aValue;
3390
0
  }
3391
3392
  bool StyleSheetChangeEventsEnabled() const
3393
0
  {
3394
0
    return mStyleSheetChangeEventsEnabled;
3395
0
  }
3396
3397
  already_AddRefed<mozilla::dom::Promise> BlockParsing(mozilla::dom::Promise& aPromise,
3398
                                                       const mozilla::dom::BlockParsingOptions& aOptions,
3399
                                                       mozilla::ErrorResult& aRv);
3400
3401
  already_AddRefed<nsIURI> GetMozDocumentURIIfNotForErrorPages();
3402
3403
  mozilla::dom::Promise* GetDocumentReadyForIdle(mozilla::ErrorResult& aRv);
3404
3405
  nsIDOMXULCommandDispatcher* GetCommandDispatcher();
3406
  already_AddRefed<nsINode> GetPopupNode();
3407
  void SetPopupNode(nsINode* aNode);
3408
  nsINode* GetPopupRangeParent(ErrorResult& aRv);
3409
  int32_t GetPopupRangeOffset(ErrorResult& aRv);
3410
  already_AddRefed<nsINode> GetTooltipNode();
3411
0
  void SetTooltipNode(nsINode* aNode) { /* do nothing */ }
3412
3413
  // ParentNode
3414
  nsIHTMLCollection* Children();
3415
  uint32_t ChildElementCount();
3416
3417
  /**
3418
   * Asserts IsHTMLOrXHTML, and can't return null.
3419
   * Defined inline in nsHTMLDocument.h
3420
   */
3421
  inline nsHTMLDocument* AsHTMLDocument();
3422
3423
  /**
3424
   * Asserts IsSVGDocument, and can't return null.
3425
   * Defined inline in SVGDocument.h
3426
   */
3427
  inline mozilla::dom::SVGDocument* AsSVGDocument();
3428
3429
  /**
3430
   * Asserts IsXULDocument, and can't return null.
3431
   * Defined inline in XULDocument.h
3432
   */
3433
  inline mozilla::dom::XULDocument* AsXULDocument();
3434
3435
  /*
3436
   * Given a node, get a weak reference to it and append that reference to
3437
   * mBlockedTrackingNodes. Can be used later on to look up a node in it.
3438
   * (e.g., by the UI)
3439
   */
3440
  void AddBlockedTrackingNode(nsINode *node)
3441
0
  {
3442
0
    if (!node) {
3443
0
      return;
3444
0
    }
3445
0
3446
0
    nsWeakPtr weakNode = do_GetWeakReference(node);
3447
0
3448
0
    if (weakNode) {
3449
0
      mBlockedTrackingNodes.AppendElement(weakNode);
3450
0
    }
3451
0
  }
3452
3453
  gfxUserFontSet* GetUserFontSet(bool aFlushUserFontSet = true);
3454
  void FlushUserFontSet();
3455
  void MarkUserFontSetDirty();
3456
0
  mozilla::dom::FontFaceSet* GetFonts() { return mFontFaceSet; }
3457
3458
  // FontFaceSource
3459
  mozilla::dom::FontFaceSet* Fonts();
3460
3461
0
  bool DidFireDOMContentLoaded() const { return mDidFireDOMContentLoaded; }
3462
3463
  bool IsSynthesized();
3464
3465
  enum class UseCounterReportKind {
3466
    // Flush the document's use counters only; the use counters for any
3467
    // external resource documents will be flushed when the external
3468
    // resource documents themselves are destroyed.
3469
    eDefault,
3470
3471
    // Flush use counters for the document and for its external resource
3472
    // documents. (Should only be necessary for tests, where we need
3473
    // flushing to happen synchronously and deterministically.)
3474
    eIncludeExternalResources,
3475
  };
3476
3477
  void ReportUseCounters(UseCounterReportKind aKind = UseCounterReportKind::eDefault);
3478
3479
  void SetDocumentUseCounter(mozilla::UseCounter aUseCounter)
3480
0
  {
3481
0
    if (!mUseCounters[aUseCounter]) {
3482
0
      mUseCounters[aUseCounter] = true;
3483
0
    }
3484
0
  }
3485
3486
  const StyleUseCounters* GetStyleUseCounters()
3487
0
  {
3488
0
    return mStyleUseCounters.get();
3489
0
  }
3490
3491
  void SetPageUseCounter(mozilla::UseCounter aUseCounter);
3492
3493
  void SetDocumentAndPageUseCounter(mozilla::UseCounter aUseCounter)
3494
0
  {
3495
0
    SetDocumentUseCounter(aUseCounter);
3496
0
    SetPageUseCounter(aUseCounter);
3497
0
  }
3498
3499
  void PropagateUseCounters(nsIDocument* aParentDocument);
3500
3501
  // Called to track whether this document has had any interaction.
3502
  // This is used to track whether we should permit "beforeunload".
3503
  void SetUserHasInteracted();
3504
  bool UserHasInteracted()
3505
0
  {
3506
0
    return mUserHasInteracted;
3507
0
  }
3508
  void ResetUserInteractionTimer();
3509
3510
  // This should be called when this document receives events which are likely
3511
  // to be user interaction with the document, rather than the byproduct of
3512
  // interaction with the browser (i.e. a keypress to scroll the view port,
3513
  // keyboard shortcuts, etc). This is used to decide whether we should
3514
  // permit autoplay audible media. This also gesture activates all other
3515
  // content documents in this tab.
3516
  void NotifyUserGestureActivation();
3517
3518
  // Return true if NotifyUserGestureActivation() has been called on any
3519
  // document in the document tree.
3520
  bool HasBeenUserGestureActivated();
3521
3522
  // This document is a WebExtension page, it might be a background page, a
3523
  // popup, a visible tab, a visible iframe ...e.t.c.
3524
  bool IsExtensionPage() const;
3525
3526
  bool HasScriptsBlockedBySandbox();
3527
3528
  bool InlineScriptAllowedByCSP();
3529
3530
  void ReportHasScrollLinkedEffect();
3531
  bool HasScrollLinkedEffect() const
3532
0
  {
3533
0
    return mHasScrollLinkedEffect;
3534
0
  }
3535
3536
  mozilla::dom::DocGroup* GetDocGroup() const;
3537
3538
  void AddIntersectionObserver(mozilla::dom::DOMIntersectionObserver* aObserver)
3539
0
  {
3540
0
    MOZ_ASSERT(!mIntersectionObservers.Contains(aObserver),
3541
0
               "Intersection observer already in the list");
3542
0
    mIntersectionObservers.PutEntry(aObserver);
3543
0
  }
3544
3545
  void RemoveIntersectionObserver(mozilla::dom::DOMIntersectionObserver* aObserver)
3546
0
  {
3547
0
    mIntersectionObservers.RemoveEntry(aObserver);
3548
0
  }
3549
3550
  bool HasIntersectionObservers() const
3551
0
  {
3552
0
    return !mIntersectionObservers.IsEmpty();
3553
0
  }
3554
3555
  void UpdateIntersectionObservations();
3556
  void ScheduleIntersectionObserverNotification();
3557
  void NotifyIntersectionObservers();
3558
3559
  // Dispatch a runnable related to the document.
3560
  nsresult Dispatch(mozilla::TaskCategory aCategory,
3561
                    already_AddRefed<nsIRunnable>&& aRunnable) final;
3562
3563
  virtual nsISerialEventTarget*
3564
  EventTargetFor(mozilla::TaskCategory aCategory) const override;
3565
3566
  virtual mozilla::AbstractThread*
3567
  AbstractMainThreadFor(mozilla::TaskCategory aCategory) override;
3568
3569
  // The URLs passed to these functions should match what
3570
  // JS::DescribeScriptedCaller() returns, since these APIs are used to
3571
  // determine whether some code is being called from a tracking script.
3572
  void NoteScriptTrackingStatus(const nsACString& aURL, bool isTracking);
3573
  bool IsScriptTracking(const nsACString& aURL) const;
3574
3575
  // For more information on Flash classification, see
3576
  // toolkit/components/url-classifier/flash-block-lists.rst
3577
  mozilla::dom::FlashClassification DocumentFlashClassification();
3578
3579
  /**
3580
   * Localization
3581
   *
3582
   * For more information on DocumentL10n see
3583
   * intl/l10n/docs/fluent_tutorial.rst
3584
   */
3585
3586
public:
3587
  /**
3588
   * This is a public method exposed on Document WebIDL
3589
   * to chrome only documents.
3590
   */
3591
  mozilla::dom::DocumentL10n* GetL10n();
3592
3593
  /**
3594
   * This method should be called when the container
3595
   * of l10n resources parsing is completed.
3596
   *
3597
   * It triggers initial async fetch of the resources
3598
   * as early as possible.
3599
   *
3600
   * In HTML case this is </head>.
3601
   * In XUL case this is </linkset>.
3602
   */
3603
  void OnL10nResourceContainerParsed();
3604
3605
  /**
3606
   * This method should be called when a link element
3607
   * with rel="localization" is being added to the
3608
   * l10n resource container element.
3609
   */
3610
  void LocalizationLinkAdded(Element* aLinkElement);
3611
3612
  /**
3613
   * This method should be called when a link element
3614
   * with rel="localization" is being removed.
3615
   */
3616
  void LocalizationLinkRemoved(Element* aLinkElement);
3617
3618
protected:
3619
  /**
3620
   * This method should be collect as soon as the
3621
   * parsing of the document is completed.
3622
   *
3623
   * In HTML this happens when readyState becomes
3624
   * `interactive`.
3625
   * In XUL it happens at `DoneWalking`, during
3626
   * `MozBeforeInitialXULLayout`.
3627
   *
3628
   * It triggers the initial translation of the
3629
   * document.
3630
   */
3631
  void TriggerInitialDocumentTranslation();
3632
3633
  RefPtr<mozilla::dom::DocumentL10n> mDocumentL10n;
3634
3635
private:
3636
  void InitializeLocalization(nsTArray<nsString>& aResourceIds);
3637
3638
  nsTArray<nsString> mL10nResources;
3639
3640
public:
3641
  bool IsThirdParty();
3642
3643
  bool IsScopedStyleEnabled();
3644
3645
  nsINode* GetServoRestyleRoot() const
3646
0
  {
3647
0
    return mServoRestyleRoot;
3648
0
  }
3649
3650
  uint32_t GetServoRestyleRootDirtyBits() const
3651
0
  {
3652
0
    MOZ_ASSERT(mServoRestyleRoot);
3653
0
    MOZ_ASSERT(mServoRestyleRootDirtyBits);
3654
0
    return mServoRestyleRootDirtyBits;
3655
0
  }
3656
3657
  void ClearServoRestyleRoot()
3658
0
  {
3659
0
    mServoRestyleRoot = nullptr;
3660
0
    mServoRestyleRootDirtyBits = 0;
3661
0
  }
3662
3663
  inline void SetServoRestyleRoot(nsINode* aRoot, uint32_t aDirtyBits);
3664
  inline void SetServoRestyleRootDirtyBits(uint32_t aDirtyBits);
3665
3666
  bool ShouldThrowOnDynamicMarkupInsertion()
3667
0
  {
3668
0
    return mThrowOnDynamicMarkupInsertionCounter;
3669
0
  }
3670
3671
  void IncrementThrowOnDynamicMarkupInsertionCounter()
3672
0
  {
3673
0
    ++mThrowOnDynamicMarkupInsertionCounter;
3674
0
  }
3675
3676
  void DecrementThrowOnDynamicMarkupInsertionCounter()
3677
0
  {
3678
0
    MOZ_ASSERT(mThrowOnDynamicMarkupInsertionCounter);
3679
0
    --mThrowOnDynamicMarkupInsertionCounter;
3680
0
  }
3681
3682
  bool ShouldIgnoreOpens() const
3683
0
  {
3684
0
    return mIgnoreOpensDuringUnloadCounter;
3685
0
  }
3686
3687
  void IncrementIgnoreOpensDuringUnloadCounter()
3688
0
  {
3689
0
    ++mIgnoreOpensDuringUnloadCounter;
3690
0
  }
3691
3692
  void DecrementIgnoreOpensDuringUnloadCounter()
3693
0
  {
3694
0
    MOZ_ASSERT(mIgnoreOpensDuringUnloadCounter);
3695
0
    --mIgnoreOpensDuringUnloadCounter;
3696
0
  }
3697
3698
  void IncrementTrackerCount()
3699
0
  {
3700
0
    MOZ_ASSERT(!GetSameTypeParentDocument());
3701
0
    ++mNumTrackersFound;
3702
0
  }
3703
3704
  void IncrementTrackerBlockedCount()
3705
0
  {
3706
0
    MOZ_ASSERT(!GetSameTypeParentDocument());
3707
0
    ++mNumTrackersBlocked;
3708
0
  }
3709
3710
  void NoteTrackerBlockedReason(
3711
    mozilla::Telemetry::LABELS_DOCUMENT_ANALYTICS_TRACKER_FASTBLOCKED aLabel)
3712
0
  {
3713
0
    MOZ_ASSERT(!GetSameTypeParentDocument());
3714
0
    mTrackerBlockedReasons += aLabel;
3715
0
  }
3716
3717
  uint32_t NumTrackersFound()
3718
0
  {
3719
0
    MOZ_ASSERT(!GetSameTypeParentDocument() || mNumTrackersFound == 0);
3720
0
3721
0
    return mNumTrackersFound;
3722
0
  }
3723
3724
  uint32_t NumTrackersBlocked()
3725
0
  {
3726
0
    MOZ_ASSERT(!GetSameTypeParentDocument() || mNumTrackersBlocked == 0);
3727
0
3728
0
    return mNumTrackersBlocked;
3729
0
  }
3730
3731
  bool AllowPaymentRequest() const
3732
0
  {
3733
0
    return mAllowPaymentRequest;
3734
0
  }
3735
3736
  void SetAllowPaymentRequest(bool aAllowPaymentRequest)
3737
0
  {
3738
0
    mAllowPaymentRequest = aAllowPaymentRequest;
3739
0
  }
3740
3741
  bool IsShadowDOMEnabled() const
3742
0
  {
3743
0
    return mIsShadowDOMEnabled;
3744
0
  }
3745
3746
  bool ModuleScriptsEnabled();
3747
3748
  /**
3749
   * Find the (non-anonymous) content in this document for aFrame. It will
3750
   * be aFrame's content node if that content is in this document and not
3751
   * anonymous. Otherwise, when aFrame is in a subdocument, we use the frame
3752
   * element containing the subdocument containing aFrame, and/or find the
3753
   * nearest non-anonymous ancestor in this document.
3754
   * Returns null if there is no such element.
3755
   */
3756
  nsIContent* GetContentInThisDocument(nsIFrame* aFrame) const;
3757
3758
  void ReportShadowDOMUsage();
3759
3760
  // Sets flags for media autoplay telemetry.
3761
  void SetDocTreeHadAudibleMedia();
3762
  void SetDocTreeHadPlayRevoked();
3763
3764
protected:
3765
  void DoUpdateSVGUseElementShadowTrees();
3766
3767
  already_AddRefed<nsIPrincipal> MaybeDowngradePrincipal(nsIPrincipal* aPrincipal);
3768
3769
  void EnsureOnloadBlocker();
3770
3771
  void SendToConsole(nsCOMArray<nsISecurityConsoleMessage>& aMessages);
3772
3773
  // Returns true if the scheme for the url for this document is "about".
3774
  bool IsAboutPage() const;
3775
3776
  bool ContainsEMEContent();
3777
  bool ContainsMSEContent();
3778
3779
  void MaybeInitializeFinalizeFrameLoaders();
3780
3781
  /**
3782
   * Returns the title element of the document as defined by the HTML
3783
   * specification, or null if there isn't one.  For documents whose root
3784
   * element is an <svg:svg>, this is the first <svg:title> element that's a
3785
   * child of the root.  For other documents, it's the first HTML title element
3786
   * in the document.
3787
   */
3788
  Element* GetTitleElement();
3789
3790
  // Retrieves the classification of the Flash plugins in the document based on
3791
  // the classification lists.
3792
  mozilla::dom::FlashClassification PrincipalFlashClassification();
3793
3794
  // Attempts to determine the Flash classification of this page based on the
3795
  // the classification lists and the classification of parent documents.
3796
  mozilla::dom::FlashClassification ComputeFlashClassification();
3797
3798
  void RecordNavigationTiming(ReadyState aReadyState);
3799
3800
  // This method may fire a DOM event; if it does so it will happen
3801
  // synchronously.
3802
  void UpdateVisibilityState();
3803
3804
  // Recomputes the visibility state but doesn't set the new value.
3805
  mozilla::dom::VisibilityState ComputeVisibilityState() const;
3806
3807
  // Since we wouldn't automatically play media from non-visited page, we need
3808
  // to notify window when the page was first visited.
3809
  void MaybeActiveMediaComponents();
3810
3811
  // Apply the fullscreen state to the document, and trigger related
3812
  // events. It returns false if the fullscreen element ready check
3813
  // fails and nothing gets changed.
3814
  bool ApplyFullscreen(mozilla::UniquePtr<FullscreenRequest> aRequest);
3815
3816
  bool GetUseCounter(mozilla::UseCounter aUseCounter)
3817
0
  {
3818
0
    return mUseCounters[aUseCounter];
3819
0
  }
3820
3821
  void SetChildDocumentUseCounter(mozilla::UseCounter aUseCounter)
3822
0
  {
3823
0
    if (!mChildDocumentUseCounters[aUseCounter]) {
3824
0
      mChildDocumentUseCounters[aUseCounter] = true;
3825
0
    }
3826
0
  }
3827
3828
  bool GetChildDocumentUseCounter(mozilla::UseCounter aUseCounter)
3829
0
  {
3830
0
    return mChildDocumentUseCounters[aUseCounter];
3831
0
  }
3832
3833
  void UpdateDocumentStates(mozilla::EventStates);
3834
3835
  void RemoveDocStyleSheetsFromStyleSets();
3836
  void RemoveStyleSheetsFromStyleSets(
3837
      const nsTArray<RefPtr<mozilla::StyleSheet>>& aSheets,
3838
      mozilla::SheetType aType);
3839
  void ResetStylesheetsToURI(nsIURI* aURI);
3840
  void FillStyleSet(mozilla::ServoStyleSet* aStyleSet);
3841
  void AddStyleSheetToStyleSets(mozilla::StyleSheet* aSheet);
3842
  void RemoveStyleSheetFromStyleSets(mozilla::StyleSheet* aSheet);
3843
  void NotifyStyleSheetAdded(mozilla::StyleSheet* aSheet, bool aDocumentSheet);
3844
  void NotifyStyleSheetRemoved(mozilla::StyleSheet* aSheet, bool aDocumentSheet);
3845
  void NotifyStyleSheetApplicableStateChanged();
3846
  // Just like EnableStyleSheetsForSet, but doesn't check whether
3847
  // aSheetSet is null and allows the caller to control whether to set
3848
  // aSheetSet as the preferred set in the CSSLoader.
3849
  void EnableStyleSheetsForSetInternal(const nsAString& aSheetSet,
3850
                                       bool aUpdateCSSLoader);
3851
3852
private:
3853
  mutable std::bitset<eDeprecatedOperationCount> mDeprecationWarnedAbout;
3854
  mutable std::bitset<eDocumentWarningCount> mDocWarningWarnedAbout;
3855
3856
  // Lazy-initialization to have mDocGroup initialized in prior to the
3857
  // SelectorCaches.
3858
  mozilla::UniquePtr<SelectorCache> mSelectorCache;
3859
3860
protected:
3861
  friend class nsDocumentOnStack;
3862
3863
  void IncreaseStackRefCnt()
3864
0
  {
3865
0
    ++mStackRefCnt;
3866
0
  }
3867
3868
  void DecreaseStackRefCnt()
3869
0
  {
3870
0
    if (--mStackRefCnt == 0 && mNeedsReleaseAfterStackRefCntRelease) {
3871
0
      mNeedsReleaseAfterStackRefCntRelease = false;
3872
0
      NS_RELEASE_THIS();
3873
0
    }
3874
0
  }
3875
3876
  ~nsIDocument();
3877
3878
  // Never ever call this. Only call GetWindow!
3879
  nsPIDOMWindowOuter* GetWindowInternal() const;
3880
3881
  // Never ever call this. Only call GetScriptHandlingObject!
3882
  nsIScriptGlobalObject* GetScriptHandlingObjectInternal() const;
3883
3884
  // Never ever call this. Only call AllowXULXBL!
3885
  bool InternalAllowXULXBL();
3886
3887
  /**
3888
   * These methods should be called before and after dispatching
3889
   * a mutation event.
3890
   * To make this easy and painless, use the mozAutoSubtreeModified helper class.
3891
   */
3892
  void WillDispatchMutationEvent(nsINode* aTarget);
3893
  void MutationEventDispatched(nsINode* aTarget);
3894
  friend class mozAutoSubtreeModified;
3895
3896
  virtual Element* GetNameSpaceElement() override
3897
0
  {
3898
0
    return GetRootElement();
3899
0
  }
3900
3901
  void SetContentTypeInternal(const nsACString& aType);
3902
3903
  nsCString GetContentTypeInternal() const
3904
0
  {
3905
0
    return mContentType;
3906
0
  }
3907
3908
  mozilla::dom::XPathEvaluator* XPathEvaluator();
3909
3910
  // Update our frame request callback scheduling state, if needed.  This will
3911
  // schedule or unschedule them, if necessary, and update
3912
  // mFrameRequestCallbacksScheduled.  aOldShell should only be passed when
3913
  // mPresShell is becoming null; in that case it will be used to get hold of
3914
  // the relevant refresh driver.
3915
  void UpdateFrameRequestCallbackSchedulingState(nsIPresShell* aOldShell = nullptr);
3916
3917
  // Helper for GetScrollingElement/IsScrollingElement.
3918
  bool IsPotentiallyScrollable(mozilla::dom::HTMLBodyElement* aBody);
3919
3920
  // Return the same type parent docuement if exists, or return null.
3921
  nsIDocument* GetSameTypeParentDocument();
3922
3923
  void MaybeAllowStorageForOpener();
3924
3925
  void MaybeStoreUserInteractionAsPermission();
3926
3927
  // Helpers for GetElementsByName.
3928
  static bool MatchNameAttribute(mozilla::dom::Element* aElement,
3929
                                 int32_t aNamespaceID,
3930
                                 nsAtom* aAtom, void* aData);
3931
  static void* UseExistingNameString(nsINode* aRootNode, const nsString* aName);
3932
3933
  void MaybeResolveReadyForIdle();
3934
3935
  nsCString mReferrer;
3936
  nsString mLastModified;
3937
3938
  nsCOMPtr<nsIURI> mDocumentURI;
3939
  nsCOMPtr<nsIURI> mOriginalURI;
3940
  nsCOMPtr<nsIURI> mChromeXHRDocURI;
3941
  nsCOMPtr<nsIURI> mDocumentBaseURI;
3942
  nsCOMPtr<nsIURI> mChromeXHRDocBaseURI;
3943
3944
  // A lazily-constructed URL data for style system to resolve URL value.
3945
  RefPtr<mozilla::URLExtraData> mCachedURLData;
3946
3947
  nsWeakPtr mDocumentLoadGroup;
3948
3949
  bool mReferrerPolicySet;
3950
  ReferrerPolicyEnum mReferrerPolicy;
3951
3952
  bool mBlockAllMixedContent;
3953
  bool mBlockAllMixedContentPreloads;
3954
  bool mUpgradeInsecureRequests;
3955
  bool mUpgradeInsecurePreloads;
3956
3957
  mozilla::WeakPtr<nsDocShell> mDocumentContainer;
3958
3959
  NotNull<const Encoding*> mCharacterSet;
3960
  int32_t mCharacterSetSource;
3961
3962
  // This is just a weak pointer; the parent document owns its children.
3963
  nsIDocument* mParentDocument;
3964
3965
  // A reference to the element last returned from GetRootElement().
3966
  mozilla::dom::Element* mCachedRootElement;
3967
3968
  // This is a weak reference, but we hold a strong reference to mNodeInfo,
3969
  // which in turn holds a strong reference to this mNodeInfoManager.
3970
  nsNodeInfoManager* mNodeInfoManager;
3971
  RefPtr<mozilla::css::Loader> mCSSLoader;
3972
  RefPtr<mozilla::css::ImageLoader> mStyleImageLoader;
3973
  RefPtr<nsHTMLStyleSheet> mAttrStyleSheet;
3974
  RefPtr<nsHTMLCSSStyleSheet> mStyleAttrStyleSheet;
3975
3976
  // Tracking for images in the document.
3977
  RefPtr<mozilla::dom::ImageTracker> mImageTracker;
3978
3979
  // A hashtable of ShadowRoots belonging to the composed doc.
3980
  //
3981
  // See ShadowRoot::Bind and ShadowRoot::Unbind.
3982
  ShadowRootSet mComposedShadowRoots;
3983
3984
  using SVGUseElementSet =
3985
    nsTHashtable<nsPtrHashKey<mozilla::dom::SVGUseElement>>;
3986
3987
  // The set of <svg:use> elements that need a shadow tree reclone because the
3988
  // tree they map to has changed.
3989
  SVGUseElementSet mSVGUseElementsNeedingShadowTreeUpdate;
3990
3991
  // The set of all object, embed, video/audio elements or
3992
  // nsIObjectLoadingContent or nsIDocumentActivity for which this is the owner
3993
  // document. (They might not be in the document.)
3994
  //
3995
  // These are non-owning pointers, the elements are responsible for removing
3996
  // themselves when they go away.
3997
  nsAutoPtr<nsTHashtable<nsPtrHashKey<nsISupports> > > mActivityObservers;
3998
3999
  // A hashtable of styled links keyed by address pointer.
4000
  nsTHashtable<nsPtrHashKey<mozilla::dom::Link>> mStyledLinks;
4001
#ifdef DEBUG
4002
  // Indicates whether mStyledLinks was cleared or not.  This is used to track
4003
  // state so we can provide useful assertions to consumers of ForgetLink and
4004
  // AddStyleRelevantLink.
4005
  bool mStyledLinksCleared;
4006
#endif
4007
4008
  // The array of all links that need their status resolved.  Links must add themselves
4009
  // to this set by calling RegisterPendingLinkUpdate when added to a document.
4010
  static const size_t kSegmentSize = 128;
4011
4012
  typedef mozilla::SegmentedVector<nsCOMPtr<mozilla::dom::Link>,
4013
                                   kSegmentSize,
4014
                                   InfallibleAllocPolicy>
4015
    LinksToUpdateList;
4016
4017
  LinksToUpdateList mLinksToUpdate;
4018
4019
  // SMIL Animation Controller, lazily-initialized in GetAnimationController
4020
  RefPtr<nsSMILAnimationController> mAnimationController;
4021
4022
  // Table of element properties for this document.
4023
  nsPropertyTable mPropertyTable;
4024
4025
  // Our cached .children collection
4026
  nsCOMPtr<nsIHTMLCollection> mChildrenCollection;
4027
4028
  // Various DOM lists
4029
  RefPtr<nsContentList> mImages;
4030
  RefPtr<nsContentList> mEmbeds;
4031
  RefPtr<nsContentList> mLinks;
4032
  RefPtr<nsContentList> mForms;
4033
  RefPtr<nsContentList> mScripts;
4034
  nsCOMPtr<nsIHTMLCollection> mApplets;
4035
  RefPtr<nsContentList> mAnchors;
4036
4037
  // container for per-context fonts (downloadable, SVG, etc.)
4038
  RefPtr<mozilla::dom::FontFaceSet> mFontFaceSet;
4039
4040
  // Last time this document or a one of its sub-documents was focused.  If
4041
  // focus has never occurred then mLastFocusTime.IsNull() will be true.
4042
  mozilla::TimeStamp mLastFocusTime;
4043
4044
  mozilla::EventStates mDocumentState;
4045
4046
  RefPtr<mozilla::dom::Promise> mReadyForIdle;
4047
4048
  // True if BIDI is enabled.
4049
  bool mBidiEnabled : 1;
4050
  // True if a MathML element has ever been owned by this document.
4051
  bool mMathMLEnabled : 1;
4052
4053
  // True if this document is the initial document for a window.  This should
4054
  // basically be true only for documents that exist in newly-opened windows or
4055
  // documents created to satisfy a GetDocument() on a window when there's no
4056
  // document in it.
4057
  bool mIsInitialDocumentInWindow : 1;
4058
4059
  bool mIgnoreDocGroupMismatches : 1;
4060
4061
  // True if we're loaded as data and therefor has any dangerous stuff, such
4062
  // as scripts and plugins, disabled.
4063
  bool mLoadedAsData : 1;
4064
4065
  // This flag is only set in XMLDocument, for e.g. documents used in XBL. We
4066
  // don't want animations to play in such documents, so we need to store the
4067
  // flag here so that we can check it in nsDocument::GetAnimationController.
4068
  bool mLoadedAsInteractiveData : 1;
4069
4070
  // If true, whoever is creating the document has gotten it to the
4071
  // point where it's safe to start layout on it.
4072
  bool mMayStartLayout : 1;
4073
4074
  // True iff we've ever fired a DOMTitleChanged event for this document
4075
  bool mHaveFiredTitleChange : 1;
4076
4077
  // State for IsShowing(). mIsShowing starts off false. It becomes true when
4078
  // OnPageShow happens and becomes false when OnPageHide happens. So it's false
4079
  // before the initial load completes and when we're in bfcache or unloaded,
4080
  // true otherwise.
4081
  bool mIsShowing : 1;
4082
4083
  // State for IsVisible(). mVisible starts off true. It becomes false when
4084
  // OnPageHide happens, and becomes true again when OnPageShow happens.  So
4085
  // it's false only when we're in bfcache or unloaded.
4086
  bool mVisible : 1;
4087
4088
  // True if our content viewer has been removed from the docshell
4089
  // (it may still be displayed, but in zombie state). Form control data
4090
  // has been saved.
4091
  bool mRemovedFromDocShell : 1;
4092
4093
  // True iff DNS prefetch is allowed for this document.  Note that if the
4094
  // document has no window, DNS prefetch won't be performed no matter what.
4095
  bool mAllowDNSPrefetch : 1;
4096
4097
  // True when this document is a static clone of a normal document
4098
  bool mIsStaticDocument : 1;
4099
4100
  // True while this document is being cloned to a static document.
4101
  bool mCreatingStaticClone : 1;
4102
4103
  // True iff the document is being unlinked or deleted.
4104
  bool mInUnlinkOrDeletion : 1;
4105
4106
  // True if document has ever had script handling object.
4107
  bool mHasHadScriptHandlingObject : 1;
4108
4109
  // True if we're an SVG document being used as an image.
4110
  bool mIsBeingUsedAsImage : 1;
4111
4112
  // True is this document is synthetic : stand alone image, video, audio
4113
  // file, etc.
4114
  bool mIsSyntheticDocument : 1;
4115
4116
  // True is there is a pending runnable which will call FlushPendingLinkUpdates().
4117
  bool mHasLinksToUpdateRunnable : 1;
4118
4119
  // True if we're flushing pending link updates.
4120
  bool mFlushingPendingLinkUpdates : 1;
4121
4122
  // True if a DOMMutationObserver is perhaps attached to a node in the document.
4123
  bool mMayHaveDOMMutationObservers : 1;
4124
4125
  // True if an nsIAnimationObserver is perhaps attached to a node in the document.
4126
  bool mMayHaveAnimationObservers : 1;
4127
4128
  // True if a document has loaded Mixed Active Script (see nsMixedContentBlocker.cpp)
4129
  bool mHasMixedActiveContentLoaded : 1;
4130
4131
  // True if a document has blocked Mixed Active Script (see nsMixedContentBlocker.cpp)
4132
  bool mHasMixedActiveContentBlocked : 1;
4133
4134
  // True if a document has loaded Mixed Display/Passive Content (see nsMixedContentBlocker.cpp)
4135
  bool mHasMixedDisplayContentLoaded : 1;
4136
4137
  // True if a document has blocked Mixed Display/Passive Content (see nsMixedContentBlocker.cpp)
4138
  bool mHasMixedDisplayContentBlocked : 1;
4139
4140
  // True if a document loads a plugin object that attempts to load mixed content subresources through necko(see nsMixedContentBlocker.cpp)
4141
  bool mHasMixedContentObjectSubrequest : 1;
4142
4143
  // True if a document load has a CSP attached.
4144
  bool mHasCSP : 1;
4145
4146
  // True if a document load has a CSP with unsafe-eval attached.
4147
  bool mHasUnsafeEvalCSP : 1;
4148
4149
  // True if a document load has a CSP with unsafe-inline attached.
4150
  bool mHasUnsafeInlineCSP : 1;
4151
4152
  // True if a document has blocked Tracking Content
4153
  bool mHasTrackingContentBlocked : 1;
4154
4155
  // True if a document has blocked Slow Tracking Content
4156
  bool mHasSlowTrackingContentBlocked : 1;
4157
4158
  // True if a document has blocked All Cookies
4159
  bool mHasAllCookiesBlocked : 1;
4160
4161
  // True if a document has blocked Tracking Cookies
4162
  bool mHasTrackingCookiesBlocked : 1;
4163
4164
  // True if a document has blocked Foreign Cookies
4165
  bool mHasForeignCookiesBlocked : 1;
4166
4167
  // True if a document has blocked Cookies By Site Permission
4168
  bool mHasCookiesBlockedByPermission : 1;
4169
4170
  // True if a document has loaded Tracking Content
4171
  bool mHasTrackingContentLoaded : 1;
4172
4173
  // True if DisallowBFCaching has been called on this document.
4174
  bool mBFCacheDisallowed : 1;
4175
4176
  bool mHasHadDefaultView : 1;
4177
4178
  // Whether style sheet change events will be dispatched for this document
4179
  bool mStyleSheetChangeEventsEnabled : 1;
4180
4181
  // Whether the document was created by a srcdoc iframe.
4182
  bool mIsSrcdocDocument : 1;
4183
4184
  // Records whether we've done a document.open. If this is true, it's possible
4185
  // for nodes from this document to have outdated wrappers in their wrapper
4186
  // caches.
4187
  bool mDidDocumentOpen : 1;
4188
4189
  // Whether this document has a display document and thus is considered to
4190
  // be a resource document.  Normally this is the same as !!mDisplayDocument,
4191
  // but mDisplayDocument is cleared during Unlink.  mHasDisplayDocument is
4192
  // valid in the document's destructor.
4193
  bool mHasDisplayDocument : 1;
4194
4195
  // Is the current mFontFaceSet valid?
4196
  bool mFontFaceSetDirty : 1;
4197
4198
  // Has GetUserFontSet() been called?
4199
  bool mGetUserFontSetCalled : 1;
4200
4201
  // True if we have fired the DOMContentLoaded event, or don't plan to fire one
4202
  // (e.g. we're not being parsed at all).
4203
  bool mDidFireDOMContentLoaded : 1;
4204
4205
  // True if ReportHasScrollLinkedEffect() has been called.
4206
  bool mHasScrollLinkedEffect : 1;
4207
4208
  // True if we have frame request callbacks scheduled with the refresh driver.
4209
  // This should generally be updated only via
4210
  // UpdateFrameRequestCallbackSchedulingState.
4211
  bool mFrameRequestCallbacksScheduled : 1;
4212
4213
  bool mIsTopLevelContentDocument : 1;
4214
4215
  bool mIsContentDocument : 1;
4216
4217
  // True if we have called BeginLoad and are expecting a paired EndLoad call.
4218
  bool mDidCallBeginLoad : 1;
4219
4220
  // True if the document is allowed to use PaymentRequest.
4221
  bool mAllowPaymentRequest : 1;
4222
4223
  // True if the encoding menu should be disabled.
4224
  bool mEncodingMenuDisabled : 1;
4225
4226
  // True if dom.webcomponents.shadowdom.enabled pref is set when document is
4227
  // created.
4228
  bool mIsShadowDOMEnabled : 1;
4229
4230
  // True if this document is for an SVG-in-OpenType font.
4231
  bool mIsSVGGlyphsDocument : 1;
4232
4233
  // True if the document is being destroyed.
4234
  bool mInDestructor: 1;
4235
4236
  // True if the document has been detached from its content viewer.
4237
  bool mIsGoingAway: 1;
4238
4239
  bool mInXBLUpdate: 1;
4240
4241
  bool mNeedsReleaseAfterStackRefCntRelease: 1;
4242
4243
  // Whether we have filled our pres shell's style set with the document's
4244
  // additional sheets and sheets from the nsStyleSheetService.
4245
  bool mStyleSetFilled: 1;
4246
4247
  // Keeps track of whether we have a pending
4248
  // 'style-sheet-applicable-state-changed' notification.
4249
  bool mSSApplicableStateNotificationPending: 1;
4250
4251
  // True if this document has ever had an HTML or SVG <title> element
4252
  // bound to it
4253
  bool mMayHaveTitleElement: 1;
4254
4255
  bool mDOMLoadingSet: 1;
4256
  bool mDOMInteractiveSet: 1;
4257
  bool mDOMCompleteSet: 1;
4258
  bool mAutoFocusFired: 1;
4259
4260
  bool mScrolledToRefAlready : 1;
4261
  bool mChangeScrollPosWhenScrollingToRef : 1;
4262
4263
  bool mHasWarnedAboutBoxObjects: 1;
4264
4265
  bool mDelayFrameLoaderInitialization: 1;
4266
4267
  bool mSynchronousDOMContentLoaded: 1;
4268
4269
  // Set to true when the document is possibly controlled by the ServiceWorker.
4270
  // Used to prevent multiple requests to ServiceWorkerManager.
4271
  bool mMaybeServiceWorkerControlled: 1;
4272
4273
  // These member variables cache information about the viewport so we don't
4274
  // have to recalculate it each time.
4275
  bool mValidWidth: 1;
4276
  bool mValidHeight: 1;
4277
  bool mAutoSize: 1;
4278
  bool mAllowZoom: 1;
4279
  bool mAllowDoubleTapZoom: 1;
4280
  bool mValidScaleFloat: 1;
4281
  bool mValidMaxScale: 1;
4282
  bool mScaleStrEmpty: 1;
4283
  bool mWidthStrEmpty: 1;
4284
4285
  // Parser aborted. True if the parser of this document was forcibly
4286
  // terminated instead of letting it finish at its own pace.
4287
  bool mParserAborted: 1;
4288
4289
  // Whether we have reported use counters for this document with Telemetry yet.
4290
  // Normally this is only done at document destruction time, but for image
4291
  // documents (SVG documents) that are not guaranteed to be destroyed, we
4292
  // report use counters when the image cache no longer has any imgRequestProxys
4293
  // pointing to them.  We track whether we ever reported use counters so
4294
  // that we only report them once for the document.
4295
  bool mReportedUseCounters: 1;
4296
4297
  bool mHasReportedShadowDOMUsage: 1;
4298
4299
  // True if this document contained, either directly or in a subdocument,
4300
  // an HTMLMediaElement that played audibly. This should only be set on
4301
  // top level content documents.
4302
  bool mDocTreeHadAudibleMedia: 1;
4303
  // True if this document contained, either directly or in a subdocument,
4304
  // an HTMLMediaElement that was playing inaudibly and became audible and we
4305
  // paused the HTMLMediaElement because it wasn't allowed to autoplay audibly.
4306
  // This should only be set on top level content documents.
4307
  bool mDocTreeHadPlayRevoked: 1;
4308
4309
#ifdef DEBUG
4310
public:
4311
  bool mWillReparent: 1;
4312
protected:
4313
#endif
4314
4315
  uint8_t mPendingFullscreenRequests;
4316
4317
  uint8_t mXMLDeclarationBits;
4318
4319
  // Currently active onload blockers.
4320
  uint32_t mOnloadBlockCount;
4321
4322
  // Onload blockers which haven't been activated yet.
4323
  uint32_t mAsyncOnloadBlockCount;
4324
4325
  // Compatibility mode
4326
  nsCompatibility mCompatMode;
4327
4328
  // Our readyState
4329
  ReadyState mReadyState;
4330
4331
#ifdef MOZILLA_INTERNAL_API
4332
  // Our visibility state
4333
  mozilla::dom::VisibilityState mVisibilityState;
4334
  static_assert(sizeof(mozilla::dom::VisibilityState) == sizeof(uint8_t),
4335
                "Error size of mVisibilityState and mDummy");
4336
#else
4337
  uint8_t mDummy;
4338
#endif
4339
4340
  enum Type {
4341
    eUnknown, // should never be used
4342
    eHTML,
4343
    eXHTML,
4344
    eGenericXML,
4345
    eSVG,
4346
    eXUL
4347
  };
4348
4349
  Type mType;
4350
4351
  uint8_t mDefaultElementType;
4352
4353
  enum Tri {
4354
    eTriUnset = 0,
4355
    eTriFalse,
4356
    eTriTrue
4357
  };
4358
4359
  Tri mAllowXULXBL;
4360
4361
  // The document's script global object, the object from which the
4362
  // document can get its script context and scope. This is the
4363
  // *inner* window object.
4364
  nsCOMPtr<nsIScriptGlobalObject> mScriptGlobalObject;
4365
4366
  // If mIsStaticDocument is true, mOriginalDocument points to the original
4367
  // document.
4368
  nsCOMPtr<nsIDocument> mOriginalDocument;
4369
4370
  // The bidi options for this document.  What this bitfield means is
4371
  // defined in nsBidiUtils.h
4372
  uint32_t mBidiOptions;
4373
4374
  // The sandbox flags on the document. These reflect the value of the sandbox attribute of the
4375
  // associated IFRAME or CSP-protectable content, if existent. These are set at load time and
4376
  // are immutable - see nsSandboxFlags.h for the possible flags.
4377
  uint32_t mSandboxFlags;
4378
4379
  nsCString mContentLanguage;
4380
4381
  // The channel that got passed to nsDocument::StartDocumentLoad(), if any.
4382
  nsCOMPtr<nsIChannel> mChannel;
4383
private:
4384
  nsCString mContentType;
4385
protected:
4386
  // For document.write() we may need a different content type than mContentType.
4387
  nsCString mContentTypeForWriteCalls;
4388
4389
  // The document's security info
4390
  nsCOMPtr<nsISupports> mSecurityInfo;
4391
4392
  // The channel that failed to load and resulted in an error page.
4393
  // This only applies to error pages. Might be null.
4394
  nsCOMPtr<nsIChannel> mFailedChannel;
4395
4396
  // if this document is part of a multipart document,
4397
  // the ID can be used to distinguish it from the other parts.
4398
  uint32_t mPartID;
4399
4400
  // Cycle collector generation in which we're certain that this document
4401
  // won't be collected
4402
  uint32_t mMarkedCCGeneration;
4403
4404
  nsIPresShell* mPresShell;
4405
4406
  nsCOMArray<nsINode> mSubtreeModifiedTargets;
4407
  uint32_t mSubtreeModifiedDepth;
4408
4409
  // All images in process of being preloaded.  This is a hashtable so
4410
  // we can remove them as the real image loads start; that way we
4411
  // make sure to not keep the image load going when no one cares
4412
  // about it anymore.
4413
  nsRefPtrHashtable<nsURIHashKey, imgIRequest> mPreloadingImages;
4414
4415
  // A list of preconnects initiated by the preloader. This prevents
4416
  // the same uri from being used more than once, and allows the dom
4417
  // builder to not repeat the work of the preloader.
4418
  nsDataHashtable<nsURIHashKey, bool> mPreloadedPreconnects;
4419
4420
  // Current depth of picture elements from parser
4421
  uint32_t mPreloadPictureDepth;
4422
4423
  // Set if we've found a URL for the current picture
4424
  nsString mPreloadPictureFoundSource;
4425
4426
  // If we're an external resource document, this will be non-null and will
4427
  // point to our "display document": the one that all resource lookups should
4428
  // go to.
4429
  nsCOMPtr<nsIDocument> mDisplayDocument;
4430
4431
  uint32_t mEventsSuppressed;
4432
4433
  /**
4434
   * https://html.spec.whatwg.org/#ignore-destructive-writes-counter
4435
   */
4436
  uint32_t mIgnoreDestructiveWritesCounter;
4437
4438
  /**
4439
   * The current frame request callback handle
4440
   */
4441
  int32_t mFrameRequestCallbackCounter;
4442
4443
  // Count of live static clones of this document.
4444
  uint32_t mStaticCloneCount;
4445
4446
  // Array of nodes that have been blocked to prevent user tracking.
4447
  // They most likely have had their nsIChannel canceled by the URL
4448
  // classifier. (Safebrowsing)
4449
  //
4450
  // Weak nsINode pointers are used to allow nodes to disappear.
4451
  nsTArray<nsWeakPtr> mBlockedTrackingNodes;
4452
4453
  // Weak reference to mScriptGlobalObject QI:d to nsPIDOMWindow,
4454
  // updated on every set of mScriptGlobalObject.
4455
  nsPIDOMWindowInner* mWindow;
4456
4457
  nsCOMPtr<nsIDocumentEncoder> mCachedEncoder;
4458
4459
  struct FrameRequest;
4460
4461
  nsTArray<FrameRequest> mFrameRequestCallbacks;
4462
4463
  // This object allows us to evict ourself from the back/forward cache.  The
4464
  // pointer is non-null iff we're currently in the bfcache.
4465
  nsIBFCacheEntry *mBFCacheEntry;
4466
4467
  // Our base target.
4468
  nsString mBaseTarget;
4469
4470
  nsCOMPtr<nsIStructuredCloneContainer> mStateObjectContainer;
4471
  nsCOMPtr<nsIVariant> mStateObjectCached;
4472
4473
  uint32_t mInSyncOperationCount;
4474
4475
  mozilla::UniquePtr<mozilla::dom::XPathEvaluator> mXPathEvaluator;
4476
4477
  nsTArray<RefPtr<mozilla::dom::AnonymousContent>> mAnonymousContents;
4478
4479
  uint32_t mBlockDOMContentLoaded;
4480
4481
  // Our live MediaQueryLists
4482
  mozilla::LinkedList<mozilla::dom::MediaQueryList> mDOMMediaQueryLists;
4483
4484
  // Array of observers
4485
  nsTObserverArray<nsIDocumentObserver*> mObservers;
4486
4487
  // Flags for use counters used directly by this document.
4488
  std::bitset<mozilla::eUseCounter_Count> mUseCounters;
4489
  // Flags for use counters used by any child documents of this document.
4490
  std::bitset<mozilla::eUseCounter_Count> mChildDocumentUseCounters;
4491
  // Flags for whether we've notified our top-level "page" of a use counter
4492
  // for this child document.
4493
  std::bitset<mozilla::eUseCounter_Count> mNotifiedPageForUseCounter;
4494
4495
  // The CSS property use counters.
4496
  mozilla::UniquePtr<StyleUseCounters> mStyleUseCounters;
4497
4498
  // Whether the user has interacted with the document or not:
4499
  bool mUserHasInteracted;
4500
4501
  // We constantly update the user-interaction anti-tracking permission at any
4502
  // user-interaction using a timer. This boolean value is set to true when this
4503
  // timer is scheduled.
4504
  bool mHasUserInteractionTimerScheduled;
4505
4506
  // Whether the user has interacted with the document via a restricted
4507
  // set of gestures which are likely to be interaction with the document,
4508
  // and not events that are fired as a byproduct of the user interacting
4509
  // with the browser (events for like scrolling the page, keyboard short
4510
  // cuts, etc).
4511
  bool mUserGestureActivated;
4512
4513
  mozilla::TimeStamp mPageUnloadingEventTimeStamp;
4514
4515
  RefPtr<mozilla::dom::DocGroup> mDocGroup;
4516
4517
  // The set of all the tracking script URLs.  URLs are added to this set by
4518
  // calling NoteScriptTrackingStatus().  Currently we assume that a URL not
4519
  // existing in the set means the corresponding script isn't a tracking script.
4520
  nsTHashtable<nsCStringHashKey> mTrackingScripts;
4521
4522
  // List of ancestor principals.  This is set at the point a document
4523
  // is connected to a docshell and not mutated thereafter.
4524
  nsTArray<nsCOMPtr<nsIPrincipal>> mAncestorPrincipals;
4525
  // List of ancestor outerWindowIDs that correspond to the ancestor principals.
4526
  nsTArray<uint64_t> mAncestorOuterWindowIDs;
4527
4528
  // Pointer to our parser if we're currently in the process of being
4529
  // parsed into.
4530
  nsCOMPtr<nsIParser> mParser;
4531
4532
  nsrefcnt mStackRefCnt;
4533
4534
  // Weak reference to our sink for in case we no longer have a parser.  This
4535
  // will allow us to flush out any pending stuff from the sink even if
4536
  // EndLoad() has already happened.
4537
  nsWeakPtr mWeakSink;
4538
4539
  // Our update nesting level
4540
  uint32_t mUpdateNestLevel;
4541
4542
  enum ViewportType : uint8_t {
4543
    DisplayWidthHeight,
4544
    Specified,
4545
    Unknown
4546
  };
4547
4548
  ViewportType mViewportType;
4549
4550
  // Enum for how content in this document overflows viewport causing
4551
  // out-of-reach issue. Currently it only takes horizontal overflow
4552
  // into consideration. This enum and the corresponding field is only
4553
  // set and read on a top level content document.
4554
  enum class ViewportOverflowType : uint8_t {
4555
    // Viewport doesn't have out-of-reach overflow content, either
4556
    // because the content doesn't overflow, or the viewport doesn't
4557
    // have "overflow: hidden".
4558
    NoOverflow,
4559
4560
    // All following items indicates that the content overflows the
4561
    // scroll port which causing out-of-reach content.
4562
4563
    // Meta viewport is disabled or the document is in desktop mode.
4564
    Desktop,
4565
    // The content does not overflow the minimum-scale size. When there
4566
    // is no minimum scale specified, the default value used by Blink,
4567
    // 0.25, is used for this matter.
4568
    ButNotMinScaleSize,
4569
    // The content overflows the minimum-scale size.
4570
    MinScaleSize,
4571
  };
4572
  ViewportOverflowType mViewportOverflowType;
4573
4574
  PLDHashTable* mSubDocuments;
4575
4576
  nsDocHeaderData* mHeaderData;
4577
4578
  RefPtr<PrincipalFlashClassifier> mPrincipalFlashClassifier;
4579
  mozilla::dom::FlashClassification mFlashClassification;
4580
  // Do not use this value directly. Call the |IsThirdParty()| method, which
4581
  // caches its result here.
4582
  mozilla::Maybe<bool> mIsThirdParty;
4583
4584
  nsRevocableEventPtr<nsRunnableMethod<nsIDocument, void, false>>
4585
    mPendingTitleChangeEvent;
4586
4587
  RefPtr<nsDOMNavigationTiming> mTiming;
4588
4589
  // Recorded time of change to 'loading' state.
4590
  mozilla::TimeStamp mLoadingTimeStamp;
4591
4592
  nsWeakPtr mAutoFocusElement;
4593
4594
  nsCString mScrollToRef;
4595
4596
  // Weak reference to the scope object (aka the script global object)
4597
  // that, unlike mScriptGlobalObject, is never unset once set. This
4598
  // is a weak reference to avoid leaks due to circular references.
4599
  nsWeakPtr mScopeObject;
4600
4601
  // Array of intersection observers
4602
  nsTHashtable<nsPtrHashKey<mozilla::dom::DOMIntersectionObserver>>
4603
    mIntersectionObservers;
4604
4605
  // Stack of fullscreen elements. When we request fullscreen we push the
4606
  // fullscreen element onto this stack, and when we cancel fullscreen we
4607
  // pop one off this stack, restoring the previous fullscreen state
4608
  nsTArray<nsWeakPtr> mFullscreenStack;
4609
4610
  // The root of the doc tree in which this document is in. This is only
4611
  // non-null when this document is in fullscreen mode.
4612
  nsWeakPtr mFullscreenRoot;
4613
4614
  RefPtr<mozilla::dom::DOMImplementation> mDOMImplementation;
4615
4616
  RefPtr<nsContentList> mImageMaps;
4617
4618
  // A set of responsive images keyed by address pointer.
4619
  nsTHashtable<nsPtrHashKey<mozilla::dom::HTMLImageElement>> mResponsiveContent;
4620
4621
  // Tracking for plugins in the document.
4622
  nsTHashtable<nsPtrHashKey<nsIObjectLoadingContent>> mPlugins;
4623
4624
  RefPtr<mozilla::dom::DocumentTimeline> mDocumentTimeline;
4625
  mozilla::LinkedList<mozilla::dom::DocumentTimeline> mTimelines;
4626
4627
  RefPtr<mozilla::dom::ScriptLoader> mScriptLoader;
4628
4629
  nsRefPtrHashtable<nsPtrHashKey<nsIContent>, mozilla::dom::BoxObject>*
4630
    mBoxObjectTable;
4631
4632
  // Tracker for animations that are waiting to start.
4633
  // nullptr until GetOrCreatePendingAnimationTracker is called.
4634
  RefPtr<mozilla::PendingAnimationTracker> mPendingAnimationTracker;
4635
4636
  // A document "without a browsing context" that owns the content of
4637
  // HTMLTemplateElement.
4638
  nsCOMPtr<nsIDocument> mTemplateContentsOwner;
4639
4640
  nsExternalResourceMap mExternalResourceMap;
4641
4642
  // ScreenOrientation "pending promise" as described by
4643
  // http://www.w3.org/TR/screen-orientation/
4644
  RefPtr<mozilla::dom::Promise> mOrientationPendingPromise;
4645
4646
  uint16_t mCurrentOrientationAngle;
4647
  mozilla::dom::OrientationType mCurrentOrientationType;
4648
4649
  nsTArray<RefPtr<nsFrameLoader>> mInitializableFrameLoaders;
4650
  nsTArray<nsCOMPtr<nsIRunnable>> mFrameLoaderFinalizers;
4651
  RefPtr<nsRunnableMethod<nsIDocument>> mFrameLoaderRunner;
4652
4653
  // The layout history state that should be used by nodes in this
4654
  // document.  We only actually store a pointer to it when:
4655
  // 1)  We have no script global object.
4656
  // 2)  We haven't had Destroy() called on us yet.
4657
  nsCOMPtr<nsILayoutHistoryState> mLayoutHistoryState;
4658
4659
  // These member variables cache information about the viewport so we don't
4660
  // have to recalculate it each time.
4661
  mozilla::LayoutDeviceToScreenScale mScaleMinFloat;
4662
  mozilla::LayoutDeviceToScreenScale mScaleMaxFloat;
4663
  mozilla::LayoutDeviceToScreenScale mScaleFloat;
4664
  mozilla::CSSToLayoutDeviceScale mPixelRatio;
4665
  mozilla::CSSSize mViewportSize;
4666
4667
  RefPtr<mozilla::EventListenerManager> mListenerManager;
4668
4669
  nsCOMPtr<nsIRunnable> mMaybeEndOutermostXBLUpdateRunner;
4670
  nsCOMPtr<nsIRequest> mOnloadBlocker;
4671
4672
  nsTArray<RefPtr<mozilla::StyleSheet>> mAdditionalSheets[AdditionalSheetTypeCount];
4673
4674
  // Member to store out last-selected stylesheet set.
4675
  nsString mLastStyleSheetSet;
4676
  nsString mPreferredStyleSheetSet;
4677
4678
  RefPtr<nsDOMStyleSheetSetList> mStyleSheetSetList;
4679
4680
  // We lazily calculate declaration blocks for SVG elements with mapped
4681
  // attributes in Servo mode. This list contains all elements which need lazy
4682
  // resolution.
4683
  nsTHashtable<nsPtrHashKey<nsSVGElement>> mLazySVGPresElements;
4684
4685
  // Restyle root for servo's style system.
4686
  //
4687
  // We store this as an nsINode, rather than as an Element, so that we can store
4688
  // the Document node as the restyle root if the entire document (along with all
4689
  // document-level native-anonymous content) needs to be restyled.
4690
  //
4691
  // We also track which "descendant" bits (normal/animation-only/lazy-fc) the
4692
  // root corresponds to.
4693
  nsCOMPtr<nsINode> mServoRestyleRoot;
4694
  uint32_t mServoRestyleRootDirtyBits;
4695
4696
  // Used in conjunction with the create-an-element-for-the-token algorithm to
4697
  // prevent custom element constructors from being able to use document.open(),
4698
  // document.close(), and document.write() when they are invoked by the parser.
4699
  uint32_t mThrowOnDynamicMarkupInsertionCounter;
4700
4701
  // Count of unload/beforeunload/pagehide operations in progress.
4702
  uint32_t mIgnoreOpensDuringUnloadCounter;
4703
4704
  nsCOMPtr<nsIDOMXULCommandDispatcher> mCommandDispatcher; // [OWNER] of the focus tracker
4705
4706
  // At the moment, trackers might be blocked by Tracking Protection or FastBlock.
4707
  // In order to know the numbers of trackers detected and blocked, we add
4708
  // these two values here and those are shared by TP and FB.
4709
  uint32_t mNumTrackersFound;
4710
  uint32_t mNumTrackersBlocked;
4711
4712
  mozilla::EnumSet<mozilla::Telemetry::LABELS_DOCUMENT_ANALYTICS_TRACKER_FASTBLOCKED>
4713
    mTrackerBlockedReasons;
4714
4715
  // document lightweight theme for use with :-moz-lwtheme, :-moz-lwtheme-brighttext
4716
  // and :-moz-lwtheme-darktext
4717
  DocumentTheme                         mDocLWTheme;
4718
};
4719
4720
NS_DEFINE_STATIC_IID_ACCESSOR(nsIDocument, NS_IDOCUMENT_IID)
4721
4722
/**
4723
 * mozAutoSubtreeModified batches DOM mutations so that a DOMSubtreeModified
4724
 * event is dispatched, if necessary, when the outermost mozAutoSubtreeModified
4725
 * object is deleted.
4726
 */
4727
class MOZ_STACK_CLASS mozAutoSubtreeModified
4728
{
4729
public:
4730
  /**
4731
   * @param aSubTreeOwner The document in which a subtree will be modified.
4732
   * @param aTarget       The target of the possible DOMSubtreeModified event.
4733
   *                      Can be nullptr, in which case mozAutoSubtreeModified
4734
   *                      is just used to batch DOM mutations.
4735
   */
4736
  mozAutoSubtreeModified(nsIDocument* aSubtreeOwner, nsINode* aTarget)
4737
0
  {
4738
0
    UpdateTarget(aSubtreeOwner, aTarget);
4739
0
  }
4740
4741
  ~mozAutoSubtreeModified()
4742
0
  {
4743
0
    UpdateTarget(nullptr, nullptr);
4744
0
  }
4745
4746
  void UpdateTarget(nsIDocument* aSubtreeOwner, nsINode* aTarget)
4747
0
  {
4748
0
    if (mSubtreeOwner) {
4749
0
      mSubtreeOwner->MutationEventDispatched(mTarget);
4750
0
    }
4751
0
4752
0
    mTarget = aTarget;
4753
0
    mSubtreeOwner = aSubtreeOwner;
4754
0
    if (mSubtreeOwner) {
4755
0
      mSubtreeOwner->WillDispatchMutationEvent(mTarget);
4756
0
    }
4757
0
  }
4758
4759
private:
4760
  nsCOMPtr<nsINode>     mTarget;
4761
  nsCOMPtr<nsIDocument> mSubtreeOwner;
4762
};
4763
4764
class MOZ_STACK_CLASS nsAutoSyncOperation
4765
{
4766
public:
4767
  explicit nsAutoSyncOperation(nsIDocument* aDocument);
4768
  ~nsAutoSyncOperation();
4769
private:
4770
  nsCOMArray<nsIDocument> mDocuments;
4771
  uint32_t                mMicroTaskLevel;
4772
};
4773
4774
class MOZ_RAII AutoSetThrowOnDynamicMarkupInsertionCounter final {
4775
  public:
4776
    explicit AutoSetThrowOnDynamicMarkupInsertionCounter(
4777
      nsIDocument* aDocument)
4778
      : mDocument(aDocument)
4779
0
    {
4780
0
      mDocument->IncrementThrowOnDynamicMarkupInsertionCounter();
4781
0
    }
4782
4783
0
    ~AutoSetThrowOnDynamicMarkupInsertionCounter() {
4784
0
      mDocument->DecrementThrowOnDynamicMarkupInsertionCounter();
4785
0
    }
4786
4787
  private:
4788
    nsIDocument* mDocument;
4789
};
4790
4791
class MOZ_RAII IgnoreOpensDuringUnload final
4792
{
4793
public:
4794
  explicit IgnoreOpensDuringUnload(nsIDocument* aDoc)
4795
    : mDoc(aDoc)
4796
0
  {
4797
0
    mDoc->IncrementIgnoreOpensDuringUnloadCounter();
4798
0
  }
4799
4800
  ~IgnoreOpensDuringUnload()
4801
0
  {
4802
0
    mDoc->DecrementIgnoreOpensDuringUnloadCounter();
4803
0
  }
4804
private:
4805
  nsIDocument* mDoc;
4806
};
4807
4808
// XXX These belong somewhere else
4809
nsresult
4810
NS_NewHTMLDocument(nsIDocument** aInstancePtrResult, bool aLoadedAsData = false);
4811
4812
nsresult
4813
NS_NewXMLDocument(nsIDocument** aInstancePtrResult, bool aLoadedAsData = false,
4814
                  bool aIsPlainDocument = false);
4815
4816
nsresult
4817
NS_NewSVGDocument(nsIDocument** aInstancePtrResult);
4818
4819
nsresult
4820
NS_NewImageDocument(nsIDocument** aInstancePtrResult);
4821
4822
nsresult
4823
NS_NewVideoDocument(nsIDocument** aInstancePtrResult);
4824
4825
// Note: it's the caller's responsibility to create or get aPrincipal as needed
4826
// -- this method will not attempt to get a principal based on aDocumentURI.
4827
// Also, both aDocumentURI and aBaseURI must not be null.
4828
nsresult
4829
NS_NewDOMDocument(nsIDocument** aInstancePtrResult,
4830
                  const nsAString& aNamespaceURI,
4831
                  const nsAString& aQualifiedName,
4832
                  mozilla::dom::DocumentType* aDoctype,
4833
                  nsIURI* aDocumentURI,
4834
                  nsIURI* aBaseURI,
4835
                  nsIPrincipal* aPrincipal,
4836
                  bool aLoadedAsData,
4837
                  nsIGlobalObject* aEventObject,
4838
                  DocumentFlavor aFlavor);
4839
4840
// This is used only for xbl documents created from the startup cache.
4841
// Non-cached documents are created in the same manner as xml documents.
4842
nsresult
4843
NS_NewXBLDocument(nsIDocument** aInstancePtrResult,
4844
                  nsIURI* aDocumentURI,
4845
                  nsIURI* aBaseURI,
4846
                  nsIPrincipal* aPrincipal);
4847
4848
nsresult
4849
NS_NewPluginDocument(nsIDocument** aInstancePtrResult);
4850
4851
inline nsIDocument*
4852
nsINode::GetOwnerDocument() const
4853
0
{
4854
0
  nsIDocument* ownerDoc = OwnerDoc();
4855
0
4856
0
  return ownerDoc != this ? ownerDoc : nullptr;
4857
0
}
4858
4859
inline nsINode*
4860
nsINode::OwnerDocAsNode() const
4861
0
{
4862
0
  return OwnerDoc();
4863
0
}
4864
4865
// ShouldUseXBLScope is defined here as a template so that we can get the faster
4866
// version of IsInAnonymousSubtree if we're statically known to be an
4867
// nsIContent.  we could try defining ShouldUseXBLScope separately on nsINode
4868
// and nsIContent, but then we couldn't put its nsINode implementation here
4869
// (because this header does not include nsIContent) and we can't put it in
4870
// nsIContent.h, because the definition of nsIContent::IsInAnonymousSubtree is
4871
// in nsIContentInlines.h.  And then we get include hell from people trying to
4872
// call nsINode::GetParentObject but not including nsIContentInlines.h and with
4873
// no really good way to include it.
4874
template<typename T>
4875
inline bool ShouldUseXBLScope(const T* aNode)
4876
0
{
4877
0
  return aNode->IsInAnonymousSubtree();
4878
0
}
Unexecuted instantiation: bool ShouldUseXBLScope<nsINode>(nsINode const*)
Unexecuted instantiation: bool ShouldUseXBLScope<nsIContent>(nsIContent const*)
4879
4880
template<typename T>
4881
inline bool ShouldUseUAWidgetScope(const T* aNode)
4882
0
{
4883
0
  return aNode->IsInUAWidget();
4884
0
}
4885
4886
inline mozilla::dom::ParentObject
4887
nsINode::GetParentObject() const
4888
0
{
4889
0
  mozilla::dom::ParentObject p(OwnerDoc());
4890
0
    // Note that mReflectionScope is a no-op for chrome, and other places
4891
0
    // where we don't check this value.
4892
0
  if (ShouldUseXBLScope(this)) {
4893
0
    p.mReflectionScope = mozilla::dom::ReflectionScope::XBL;
4894
0
  } else if (ShouldUseUAWidgetScope(this)) {
4895
0
    p.mReflectionScope = mozilla::dom::ReflectionScope::UAWidget;
4896
0
  }
4897
0
  return p;
4898
0
}
4899
4900
inline nsIDocument*
4901
nsINode::AsDocument()
4902
0
{
4903
0
  MOZ_ASSERT(IsDocument());
4904
0
  return static_cast<nsIDocument*>(this);
4905
0
}
4906
4907
inline const nsIDocument*
4908
nsINode::AsDocument() const
4909
0
{
4910
0
  MOZ_ASSERT(IsDocument());
4911
0
  return static_cast<const nsIDocument*>(this);
4912
0
}
4913
4914
#endif /* nsIDocument_h___ */