File: WindowContext.cpp

package info (click to toggle)
firefox 148.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,719,656 kB
  • sloc: cpp: 7,618,171; javascript: 6,701,506; ansic: 3,781,787; python: 1,418,364; xml: 638,647; asm: 438,962; java: 186,285; sh: 62,885; makefile: 19,010; objc: 13,092; perl: 12,763; yacc: 4,583; cs: 3,846; pascal: 3,448; lex: 1,720; ruby: 1,003; php: 436; lisp: 258; awk: 247; sql: 66; sed: 54; csh: 10; exp: 6
file content (880 lines) | stat: -rw-r--r-- 30,700 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "mozilla/dom/WindowContext.h"
#include "mozilla/dom/WindowGlobalActorsBinding.h"
#include "mozilla/dom/WindowGlobalChild.h"
#include "mozilla/dom/WindowGlobalParent.h"
#include "mozilla/dom/SyncedContextInlines.h"
#include "mozilla/dom/BrowsingContext.h"
#include "mozilla/dom/CloseWatcherManager.h"
#include "mozilla/dom/Document.h"
#include "mozilla/dom/DocumentPictureInPicture.h"
#include "mozilla/dom/UserActivationIPCUtils.h"
#include "mozilla/dom/WorkerCommon.h"
#include "mozilla/PermissionDelegateIPCUtils.h"
#include "mozilla/StaticPrefs_dom.h"
#include "mozilla/StaticPtr.h"
#include "mozilla/ClearOnShutdown.h"
#include "nsGlobalWindowInner.h"
#include "nsIScriptError.h"
#include "nsIWebProgressListener.h"
#include "nsIXULRuntime.h"
#include "nsRFPTargetSetIDL.h"
#include "nsRefPtrHashtable.h"
#include "nsContentUtils.h"

namespace mozilla {
namespace dom {

// Explicit specialization of the `Transaction` type. Required by the `extern
// template class` declaration in the header.
template class syncedcontext::Transaction<WindowContext>;

static LazyLogModule gWindowContextLog("WindowContext");
static LazyLogModule gWindowContextSyncLog("WindowContextSync");

extern mozilla::LazyLogModule gUserInteractionPRLog;

#define USER_ACTIVATION_LOG(msg, ...) \
  MOZ_LOG(gUserInteractionPRLog, LogLevel::Debug, (msg, ##__VA_ARGS__))

using WindowContextByIdMap = nsTHashMap<nsUint64HashKey, WindowContext*>;
static StaticAutoPtr<WindowContextByIdMap> gWindowContexts;

/* static */
LogModule* WindowContext::GetLog() { return gWindowContextLog; }

/* static */
LogModule* WindowContext::GetSyncLog() { return gWindowContextSyncLog; }

/* static */
already_AddRefed<WindowContext> WindowContext::GetById(
    uint64_t aInnerWindowId) {
  if (!gWindowContexts) {
    return nullptr;
  }
  return do_AddRef(gWindowContexts->Get(aInnerWindowId));
}

BrowsingContextGroup* WindowContext::Group() const {
  return mBrowsingContext->Group();
}

WindowGlobalParent* WindowContext::Canonical() {
  MOZ_RELEASE_ASSERT(XRE_IsParentProcess());
  return static_cast<WindowGlobalParent*>(this);
}

bool WindowContext::IsCurrent() const {
  return mBrowsingContext->mCurrentWindowContext == this;
}

bool WindowContext::IsInBFCache() {
  if (mozilla::SessionHistoryInParent()) {
    return mBrowsingContext->IsInBFCache();
  }
  return TopWindowContext()->GetWindowStateSaved();
}

already_AddRefed<nsIRFPTargetSetIDL>
WindowContext::GetOverriddenFingerprintingSettingsWebIDL() const {
  Maybe<RFPTargetSet> overriddenFingerprintingSettings =
      GetOverriddenFingerprintingSettings();
  if (overriddenFingerprintingSettings.isNothing()) {
    return nullptr;
  }

  nsCOMPtr<nsIRFPTargetSetIDL> protections =
      new nsRFPTargetSetIDL(overriddenFingerprintingSettings.ref());
  return protections.forget();
}

nsGlobalWindowInner* WindowContext::GetInnerWindow() const {
  return mWindowGlobalChild ? mWindowGlobalChild->GetWindowGlobal() : nullptr;
}

Document* WindowContext::GetDocument() const {
  nsGlobalWindowInner* innerWindow = GetInnerWindow();
  return innerWindow ? innerWindow->GetDocument() : nullptr;
}

Document* WindowContext::GetExtantDoc() const {
  nsGlobalWindowInner* innerWindow = GetInnerWindow();
  return innerWindow ? innerWindow->GetExtantDoc() : nullptr;
}

WindowGlobalChild* WindowContext::GetWindowGlobalChild() const {
  return mWindowGlobalChild;
}

WindowContext* WindowContext::GetParentWindowContext() {
  return mBrowsingContext->GetParentWindowContext();
}

WindowContext* WindowContext::TopWindowContext() {
  WindowContext* current = this;
  while (current->GetParentWindowContext()) {
    current = current->GetParentWindowContext();
  }
  return current;
}

bool WindowContext::IsTop() const { return mBrowsingContext->IsTop(); }

bool WindowContext::SameOriginWithTop() const {
  return mBrowsingContext->SameOriginWithTop();
}

nsIGlobalObject* WindowContext::GetParentObject() const {
  return xpc::NativeGlobal(xpc::PrivilegedJunkScope());
}

void WindowContext::AppendChildBrowsingContext(
    BrowsingContext* aBrowsingContext) {
  MOZ_DIAGNOSTIC_ASSERT(Group() == aBrowsingContext->Group(),
                        "Mismatched groups?");
  MOZ_DIAGNOSTIC_ASSERT(!mChildren.Contains(aBrowsingContext));

  ClearLightDOMChildren();

  mChildren.AppendElement(aBrowsingContext);
  if (!aBrowsingContext->IsEmbedderTypeObjectOrEmbed()) {
    mNonSyntheticChildren.AppendElement(aBrowsingContext);
  }

  // If we're the current WindowContext in our BrowsingContext, make sure to
  // clear any cached `children` value.
  if (IsCurrent()) {
    BrowsingContext_Binding::ClearCachedChildrenValue(mBrowsingContext);
  }
}

void WindowContext::RemoveChildBrowsingContext(
    BrowsingContext* aBrowsingContext) {
  MOZ_DIAGNOSTIC_ASSERT(Group() == aBrowsingContext->Group(),
                        "Mismatched groups?");
  ClearLightDOMChildren();

  mChildren.RemoveElement(aBrowsingContext);
  mNonSyntheticChildren.RemoveElement(aBrowsingContext);

  // If we're the current WindowContext in our BrowsingContext, make sure to
  // clear any cached `children` value.
  if (IsCurrent()) {
    BrowsingContext_Binding::ClearCachedChildrenValue(mBrowsingContext);
  }
}

void WindowContext::UpdateChildSynthetic(BrowsingContext* aBrowsingContext,
                                         bool aIsSynthetic) {
  if (aIsSynthetic) {
    mNonSyntheticChildren.RemoveElement(aBrowsingContext);
  } else {
    // The same BrowsingContext will be reused for error pages, so it can be in
    // the list already.
    if (!mNonSyntheticChildren.Contains(aBrowsingContext)) {
      mNonSyntheticChildren.AppendElement(aBrowsingContext);
    }
  }
}

void WindowContext::ClearLightDOMChildren() {
  mNonSyntheticLightDOMChildren.reset();
}

void WindowContext::EnsureLightDOMChildren() {
  if (mNonSyntheticLightDOMChildren.isSome()) {
    return;
  }
  mNonSyntheticLightDOMChildren.emplace();

  for (const RefPtr<BrowsingContext>& bc : mNonSyntheticChildren) {
    if (Element* el = bc->GetEmbedderElement(); el && el->IsInShadowTree()) {
      continue;
    }
    mNonSyntheticLightDOMChildren->AppendElement(bc);
  }
}

BrowsingContext* WindowContext::NonSyntheticLightDOMChildAt(uint32_t aIndex) {
  EnsureLightDOMChildren();
  return aIndex < mNonSyntheticLightDOMChildren->Length()
             ? mNonSyntheticLightDOMChildren->ElementAt(aIndex).get()
             : nullptr;
}

uint32_t WindowContext::NonSyntheticLightDOMChildrenCount() {
  EnsureLightDOMChildren();
  return mNonSyntheticLightDOMChildren->Length();
}

void WindowContext::SendCommitTransaction(ContentParent* aParent,
                                          const BaseTransaction& aTxn,
                                          uint64_t aEpoch) {
  (void)aParent->SendCommitWindowContextTransaction(this, aTxn, aEpoch);
}

void WindowContext::SendCommitTransaction(ContentChild* aChild,
                                          const BaseTransaction& aTxn,
                                          uint64_t aEpoch) {
  aChild->SendCommitWindowContextTransaction(this, aTxn, aEpoch);
}

bool WindowContext::CheckOnlyOwningProcessCanSet(ContentParent* aSource) {
  if (IsInProcess()) {
    return true;
  }

  if (XRE_IsParentProcess() && aSource) {
    return Canonical()->GetContentParent() == aSource;
  }

  return false;
}

bool WindowContext::CanSet(FieldIndex<IDX_IsSecure>, const bool& aIsSecure,
                           ContentParent* aSource) {
  return CheckOnlyOwningProcessCanSet(aSource);
}

bool WindowContext::CanSet(FieldIndex<IDX_NeedsBeforeUnload>,
                           const bool& aHasBeforeUnload,
                           ContentParent* aSource) {
  return CheckOnlyOwningProcessCanSet(aSource);
}

bool WindowContext::CanSet(FieldIndex<IDX_NeedsTraverse>,
                           const bool& aNeedsTraverse, ContentParent* aSource) {
  return CheckOnlyOwningProcessCanSet(aSource);
}

bool WindowContext::CanSet(FieldIndex<IDX_CookieBehavior>,
                           const Maybe<uint32_t>& aValue,
                           ContentParent* aSource) {
  return CheckOnlyOwningProcessCanSet(aSource);
}

bool WindowContext::CanSet(FieldIndex<IDX_IsOnContentBlockingAllowList>,
                           const bool& aValue, ContentParent* aSource) {
  return CheckOnlyOwningProcessCanSet(aSource);
}

bool WindowContext::CanSet(FieldIndex<IDX_IsThirdPartyWindow>,
                           const bool& IsThirdPartyWindow,
                           ContentParent* aSource) {
  return CheckOnlyOwningProcessCanSet(aSource);
}

bool WindowContext::CanSet(FieldIndex<IDX_IsThirdPartyTrackingResourceWindow>,
                           const bool& aIsThirdPartyTrackingResourceWindow,
                           ContentParent* aSource) {
  return CheckOnlyOwningProcessCanSet(aSource);
}

bool WindowContext::CanSet(FieldIndex<IDX_UsingStorageAccess>,
                           const bool& aUsingStorageAccess,
                           ContentParent* aSource) {
  return CheckOnlyOwningProcessCanSet(aSource);
}

bool WindowContext::CanSet(FieldIndex<IDX_ShouldResistFingerprinting>,
                           const bool& aShouldResistFingerprinting,
                           ContentParent* aSource) {
  return CheckOnlyOwningProcessCanSet(aSource);
}

bool WindowContext::CanSet(FieldIndex<IDX_OverriddenFingerprintingSettings>,
                           const Maybe<RFPTargetSet>& aValue,
                           ContentParent* aSource) {
  return CheckOnlyOwningProcessCanSet(aSource);
}

bool WindowContext::CanSet(FieldIndex<IDX_IsSecureContext>,
                           const bool& aIsSecureContext,
                           ContentParent* aSource) {
  return CheckOnlyOwningProcessCanSet(aSource);
}

bool WindowContext::CanSet(FieldIndex<IDX_IsOriginalFrameSource>,
                           const bool& aIsOriginalFrameSource,
                           ContentParent* aSource) {
  return CheckOnlyOwningProcessCanSet(aSource);
}

bool WindowContext::CanSet(FieldIndex<IDX_DocTreeHadMedia>, const bool& aValue,
                           ContentParent* aSource) {
  return IsTop();
}

bool WindowContext::CanSet(FieldIndex<IDX_AutoplayPermission>,
                           const uint32_t& aValue, ContentParent* aSource) {
  return CheckOnlyOwningProcessCanSet(aSource);
}

bool WindowContext::CanSet(FieldIndex<IDX_ShortcutsPermission>,
                           const uint32_t& aValue, ContentParent* aSource) {
  return IsTop() && CheckOnlyOwningProcessCanSet(aSource);
}

bool WindowContext::CanSet(FieldIndex<IDX_ActiveMediaSessionContextId>,
                           const Maybe<uint64_t>& aValue,
                           ContentParent* aSource) {
  return IsTop();
}

bool WindowContext::CanSet(FieldIndex<IDX_PopupPermission>, const uint32_t&,
                           ContentParent* aSource) {
  return CheckOnlyOwningProcessCanSet(aSource);
}

bool WindowContext::CanSet(
    FieldIndex<IDX_DelegatedPermissions>,
    const PermissionDelegateHandler::DelegatedPermissionList& aValue,
    ContentParent* aSource) {
  return CheckOnlyOwningProcessCanSet(aSource);
}

bool WindowContext::CanSet(
    FieldIndex<IDX_DelegatedExactHostMatchPermissions>,
    const PermissionDelegateHandler::DelegatedPermissionList& aValue,
    ContentParent* aSource) {
  return CheckOnlyOwningProcessCanSet(aSource);
}

bool WindowContext::CanSet(FieldIndex<IDX_IsLocalIP>, const bool& aValue,
                           ContentParent* aSource) {
  return CheckOnlyOwningProcessCanSet(aSource);
}

bool WindowContext::CanSet(FieldIndex<IDX_AllowJavascript>, bool aValue,
                           ContentParent* aSource) {
  return (XRE_IsParentProcess() && !aSource) ||
         CheckOnlyOwningProcessCanSet(aSource);
}

void WindowContext::DidSet(FieldIndex<IDX_AllowJavascript>, bool aOldValue) {
  RecomputeCanExecuteScripts();
}

bool WindowContext::CanSet(FieldIndex<IDX_HasActivePeerConnections>, bool,
                           ContentParent*) {
  return XRE_IsParentProcess() && IsTop();
}

void WindowContext::ProcessCloseRequest() {
  MOZ_ASSERT(XRE_IsParentProcess(), "Window must be Global Parent");
  BrowsingContext* top = mBrowsingContext->Top();
  top->PreOrderWalk([&](BrowsingContext* aBrowsingContext) {
    CanonicalBrowsingContext* canonical = aBrowsingContext->Canonical();
    if (WindowGlobalParent* parent = canonical->GetCurrentWindowGlobal()) {
      (void)parent->SendProcessCloseRequest(aBrowsingContext);
    }
  });
}

void WindowContext::RecomputeCanExecuteScripts(bool aApplyChanges) {
  const bool old = mCanExecuteScripts;
  if (!AllowJavascript()) {
    // Scripting has been explicitly disabled on our WindowContext.
    mCanExecuteScripts = false;
  } else {
    // Otherwise, inherit.
    mCanExecuteScripts = mBrowsingContext->CanExecuteScripts();
  }

  if (aApplyChanges && old != mCanExecuteScripts) {
    // Inform our active DOM window.
    if (nsGlobalWindowInner* window = GetInnerWindow()) {
      // Only update scriptability if the window is current. Windows will have
      // scriptability disabled when entering the bfcache and updated when
      // coming out.
      if (window->IsCurrentInnerWindow()) {
        auto& scriptability =
            xpc::Scriptability::Get(window->GetGlobalJSObject());
        scriptability.SetWindowAllowsScript(mCanExecuteScripts);
      }
    }

    for (const RefPtr<BrowsingContext>& child : Children()) {
      child->RecomputeCanExecuteScripts();
    }
  }
}

void WindowContext::DidSet(FieldIndex<IDX_SHEntryHasUserInteraction>,
                           bool aOldValue) {
  MOZ_ASSERT(
      TopWindowContext() == this,
      "SHEntryHasUserInteraction can only be set on the top window context");
  // This field is set when the child notifies us of new user interaction, so we
  // also set the currently active shentry in the parent as having interaction.
  if (XRE_IsParentProcess() && mBrowsingContext) {
    SessionHistoryEntry* activeEntry =
        mBrowsingContext->Canonical()->GetActiveSessionHistoryEntry();
    if (activeEntry && GetSHEntryHasUserInteraction()) {
      activeEntry->SetHasUserInteraction(true);
    }
  }
}

void WindowContext::DidSet(FieldIndex<IDX_HasActivePeerConnections>,
                           bool aOldValue) {
  MOZ_ASSERT(
      TopWindowContext() == this,
      "IDX_HasActivePeerConnections can only be set on the top window context");

  BrowsingContext* top = mBrowsingContext->Top();

  top->PreOrderWalk([&](BrowsingContext* aBrowsingContext) {
    WindowContext* windowContext = aBrowsingContext->GetCurrentWindowContext();
    if (windowContext) {
      auto* win{windowContext->GetInnerWindow()};
      if (win && (aOldValue != win->HasActivePeerConnections())) {
        dom::UpdateWorkersPeerConnections(*win,
                                          win->HasActivePeerConnections());
      }
    }
  });
}

void WindowContext::DidSet(FieldIndex<IDX_UserActivationStateAndModifiers>) {
  MOZ_ASSERT_IF(!IsInProcess(), mLastActivationTimestamp.IsNull());
  USER_ACTIVATION_LOG("Set user gesture activation 0x%02" PRIu8
                      " for %s browsing context 0x%08" PRIx64,
                      GetUserActivationStateAndModifiers(),
                      XRE_IsParentProcess() ? "Parent" : "Child", Id());
  if (IsInProcess()) {
    USER_ACTIVATION_LOG(
        "Set user gesture start time for %s browsing context 0x%08" PRIx64,
        XRE_IsParentProcess() ? "Parent" : "Child", Id());
    if (GetUserActivationState() == UserActivation::State::FullActivated) {
      mLastActivationTimestamp = TimeStamp::Now();
    } else if (GetUserActivationState() == UserActivation::State::None) {
      mLastActivationTimestamp = TimeStamp();
    }
  }
}

void WindowContext::DidSet(FieldIndex<IDX_HasReportedShadowDOMUsage>,
                           bool aOldValue) {
  if (!aOldValue && GetHasReportedShadowDOMUsage() && IsInProcess()) {
    MOZ_ASSERT(TopWindowContext() == this);
    if (mBrowsingContext) {
      Document* topLevelDoc = mBrowsingContext->GetDocument();
      if (topLevelDoc) {
        nsAutoString uri;
        (void)topLevelDoc->GetDocumentURI(uri);
        if (!uri.IsEmpty()) {
          nsAutoString msg = u"Shadow DOM used in ["_ns + uri +
                             u"] or in some of its subdocuments."_ns;
          nsContentUtils::ReportToConsoleNonLocalized(
              msg, nsIScriptError::infoFlag, "DOM"_ns, topLevelDoc);
        }
      }
    }
  }
}

bool WindowContext::CanSet(FieldIndex<IDX_WindowStateSaved>, bool aValue,
                           ContentParent* aSource) {
  return !mozilla::SessionHistoryInParent() && IsTop() &&
         CheckOnlyOwningProcessCanSet(aSource);
}

void WindowContext::CreateFromIPC(IPCInitializer&& aInit) {
  MOZ_RELEASE_ASSERT(XRE_IsContentProcess(),
                     "Should be a WindowGlobalParent in the parent");

  RefPtr<BrowsingContext> bc = BrowsingContext::Get(aInit.mBrowsingContextId);
  MOZ_RELEASE_ASSERT(bc);

  if (bc->IsDiscarded()) {
    // If we have already closed our browsing context, the
    // WindowGlobalChild actor is bound to be destroyed soon and it's
    // safe to ignore creating the WindowContext.
    return;
  }

  RefPtr<WindowContext> context = new WindowContext(
      bc, aInit.mInnerWindowId, aInit.mOuterWindowId, std::move(aInit.mFields));
  context->Init();
}

void WindowContext::Init() {
  MOZ_LOG(GetLog(), LogLevel::Debug,
          ("Registering 0x%" PRIx64 " (bc=0x%" PRIx64 ")", mInnerWindowId,
           mBrowsingContext->Id()));

  // Register the WindowContext in the `WindowContextByIdMap`.
  if (!gWindowContexts) {
    gWindowContexts = new WindowContextByIdMap();
    ClearOnShutdown(&gWindowContexts);
  }
  auto& entry = gWindowContexts->LookupOrInsert(mInnerWindowId);
  MOZ_RELEASE_ASSERT(!entry, "Duplicate WindowContext for ID!");
  entry = this;

  // Register this to the browsing context.
  mBrowsingContext->RegisterWindowContext(this);
  Group()->Register(this);
}

void WindowContext::Discard() {
  MOZ_LOG(GetLog(), LogLevel::Debug,
          ("Discarding 0x%" PRIx64 " (bc=0x%" PRIx64 ")", mInnerWindowId,
           mBrowsingContext->Id()));
  if (mIsDiscarded) {
    return;
  }

  mIsDiscarded = true;
  if (gWindowContexts) {
    gWindowContexts->Remove(InnerWindowId());
  }
  mBrowsingContext->UnregisterWindowContext(this);
  Group()->Unregister(this);
}

void WindowContext::AddSecurityState(uint32_t aStateFlags) {
  MOZ_ASSERT(TopWindowContext() == this);
  MOZ_ASSERT((aStateFlags &
              (nsIWebProgressListener::STATE_LOADED_MIXED_DISPLAY_CONTENT |
               nsIWebProgressListener::STATE_LOADED_MIXED_ACTIVE_CONTENT |
               nsIWebProgressListener::STATE_BLOCKED_MIXED_DISPLAY_CONTENT |
               nsIWebProgressListener::STATE_BLOCKED_MIXED_ACTIVE_CONTENT |
               nsIWebProgressListener::STATE_HTTPS_ONLY_MODE_UPGRADED |
               nsIWebProgressListener::STATE_HTTPS_ONLY_MODE_UPGRADE_FAILED |
               nsIWebProgressListener::STATE_HTTPS_ONLY_MODE_UPGRADED_FIRST)) ==
                 aStateFlags,
             "Invalid flags specified!");

  if (XRE_IsParentProcess()) {
    Canonical()->AddSecurityState(aStateFlags);
  } else {
    ContentChild* child = ContentChild::GetSingleton();
    child->SendAddSecurityState(this, aStateFlags);
  }
}

void WindowContext::NotifyUserGestureActivation(
    UserActivation::Modifiers
        aModifiers /* = UserActivation::Modifiers::None() */) {
  UserActivation::StateAndModifiers stateAndModifiers;
  stateAndModifiers.SetState(UserActivation::State::FullActivated);
  stateAndModifiers.SetModifiers(aModifiers);
  if (auto* innerWindow = GetInnerWindow()) {
    innerWindow->EnsureCloseWatcherManager()->NotifyUserInteraction();
  }
  (void)SetUserActivationStateAndModifiers(stateAndModifiers.GetRawData());
}

void WindowContext::NotifyResetUserGestureActivation() {
  UserActivation::StateAndModifiers stateAndModifiers;
  stateAndModifiers.SetState(UserActivation::State::None);
  (void)SetUserActivationStateAndModifiers(stateAndModifiers.GetRawData());
}

bool WindowContext::HasBeenUserGestureActivated() {
  return GetUserActivationState() != UserActivation::State::None;
}

const TimeStamp& WindowContext::GetUserGestureStart() const {
  MOZ_ASSERT(IsInProcess());
  return mLastActivationTimestamp;
}

// https://html.spec.whatwg.org/#transient-activation
bool WindowContext::HasValidTransientUserGestureActivation() {
  MOZ_ASSERT(IsInProcess());

  if (GetUserActivationState() != UserActivation::State::FullActivated) {
    // mLastActivationTimestamp should be null if the document hasn't ever been
    // activated by user gesture
    MOZ_ASSERT_IF(GetUserActivationState() == UserActivation::State::None,
                  mLastActivationTimestamp.IsNull());
    return false;
  }

  MOZ_ASSERT(
      !mLastActivationTimestamp.IsNull(),
      "mLastActivationTimestamp shouldn't be null if the document has ever "
      "been activated by user gesture");

  TimeDuration timeout = TimeDuration::FromMilliseconds(
      StaticPrefs::dom_user_activation_transient_timeout());

  // "When the current high resolution time given W is greater than or equal to
  // the last activation timestamp in W, and less than the last activation
  // timestamp in W plus the transient activation duration, then W is said to
  // have transient activation."
  return timeout <= TimeDuration() ||
         (TimeStamp::Now() - mLastActivationTimestamp) <= timeout;
}

template <typename F>
static void ConsumeUserGestureActivationBetweenPiP(BrowsingContext* aTop,
                                                   F&& aCallback) {
  // https://wicg.github.io/document-picture-in-picture/#user-activation-propagation
  // Monkey patch to consume user activation
  if (aTop->GetIsDocumentPiP()) {
    // 4. If top is a PIP window, then extend navigables with the opener
    // window's inclusive decendant navigables
    RefPtr<BrowsingContext> opener = aTop->GetOpener();
    if (!opener) {
      return;
    }
    opener->GetBrowsingContext()->PreOrderWalk(aCallback);
  } else {
    // 5. Get top-level navigable's last opened PiP window
    nsPIDOMWindowOuter* outer = aTop->GetDOMWindow();
    NS_ENSURE_TRUE_VOID(outer);
    nsPIDOMWindowInner* inner = outer->GetCurrentInnerWindow();
    NS_ENSURE_TRUE_VOID(inner);
    DocumentPictureInPicture* dpip = inner->GetExtantDocumentPictureInPicture();
    if (!dpip) {
      return;
    }
    nsGlobalWindowInner* pip = dpip->GetWindow();
    if (!pip) {
      return;
    }

    // 6. Extend navigables with the inclusive descendant navigables of the PIP
    // window.
    BrowsingContext* pipBC = pip->GetBrowsingContext();
    NS_ENSURE_TRUE_VOID(pipBC);
    WindowContext* pipWC = pipBC->GetCurrentWindowContext();
    NS_ENSURE_TRUE_VOID(pipWC);
    pipBC->PreOrderWalk(aCallback);
  }
}

// https://html.spec.whatwg.org/#consume-user-activation
bool WindowContext::ConsumeTransientUserGestureActivation() {
  MOZ_ASSERT(IsInProcess());
  // 1. If W's navigable is null, then return.
  if (!IsCurrent()) {
    return false;
  }

  if (!HasValidTransientUserGestureActivation()) {
    return false;
  }

  // 2. Let top be W's navigable's top-level traversable.
  BrowsingContext* top = mBrowsingContext->Top();

  // 3. Let navigables be the inclusive descendant navigables of top's active
  // document.
  auto callback = [&](BrowsingContext* aBrowsingContext) {
    // 4. Let windows be the list of Window objects constructed by taking the
    // active window of each item in navigables.
    WindowContext* windowContext = aBrowsingContext->GetCurrentWindowContext();

    // 5. For each window in windows, if window's last activation timestamp is
    // not positive infinity, then set window's last activation timestamp to
    // negative infinity.
    if (windowContext && windowContext->GetUserActivationState() ==
                             UserActivation::State::FullActivated) {
      auto stateAndModifiers = UserActivation::StateAndModifiers(
          GetUserActivationStateAndModifiers());
      // Setting UserActivationStateAndModifiers will trigger
      // DidSet(FieldIndex<IDX_UserActivationStateAndModifiers>),
      // which in turn updates mLastActivationTimestamp.
      stateAndModifiers.SetState(UserActivation::State::HasBeenActivated);
      (void)windowContext->SetUserActivationStateAndModifiers(
          stateAndModifiers.GetRawData());
    }
  };
  top->PreOrderWalk(callback);

  ConsumeUserGestureActivationBetweenPiP(top, callback);

  return true;
}

// https://html.spec.whatwg.org/multipage/interaction.html#history-action-activation
bool WindowContext::HasValidHistoryActivation() const {
  MOZ_ASSERT(IsInProcess());
  return mHistoryActivation != mLastActivationTimestamp;
}

// https://html.spec.whatwg.org/multipage/interaction.html#consume-history-action-user-activation
// Step 1-2
void WindowContext::ConsumeHistoryActivation() {
  MOZ_ASSERT(IsInProcess());

  // 1. If W's navigable is null, then return.

  // 2. Let top be W's navigable's top-level traversable.
  RefPtr<BrowsingContext> top = mBrowsingContext->Top();

  // Consuming a history activation must happen across all child processes,
  // including for example cross-origin iframes. As such we need to send an
  // message over the IPC boundary to ensure out of processes contexts also
  // consume their activations.
  MOZ_ASSERT(XRE_IsContentProcess());
  ContentChild::GetSingleton()->SendConsumeHistoryActivation(top);

  // Update the local process children immediately.
  top->ConsumeHistoryActivation();
}

void WindowContext::UpdateLastHistoryActivation() {
  mHistoryActivation = mLastActivationTimestamp;
}

bool WindowContext::GetTransientUserGestureActivationModifiers(
    UserActivation::Modifiers* aModifiers) {
  if (!HasValidTransientUserGestureActivation()) {
    return false;
  }

  auto stateAndModifiers =
      UserActivation::StateAndModifiers(GetUserActivationStateAndModifiers());
  *aModifiers = stateAndModifiers.GetModifiers();
  return true;
}

bool WindowContext::CanShowPopup() {
  uint32_t permit = GetPopupPermission();
  if (permit == nsIPermissionManager::ALLOW_ACTION) {
    return true;
  }
  if (permit == nsIPermissionManager::DENY_ACTION) {
    return false;
  }

  return !StaticPrefs::dom_disable_open_during_load();
}

void WindowContext::TransientSetHasActivePeerConnections() {
  if (!IsTop()) {
    return;
  }

  mFields.SetWithoutSyncing<IDX_HasActivePeerConnections>(true);
}

WindowContext::IPCInitializer WindowContext::GetIPCInitializer() {
  IPCInitializer init;
  init.mInnerWindowId = mInnerWindowId;
  init.mOuterWindowId = mOuterWindowId;
  init.mBrowsingContextId = mBrowsingContext->Id();
  init.mFields = mFields.RawValues();
  return init;
}

WindowContext::WindowContext(BrowsingContext* aBrowsingContext,
                             uint64_t aInnerWindowId, uint64_t aOuterWindowId,
                             FieldValues&& aInit)
    : mFields(std::move(aInit)),
      mInnerWindowId(aInnerWindowId),
      mOuterWindowId(aOuterWindowId),
      mBrowsingContext(aBrowsingContext) {
  MOZ_ASSERT(mBrowsingContext);
  MOZ_ASSERT(mInnerWindowId);
  MOZ_ASSERT(mOuterWindowId);
  RecomputeCanExecuteScripts(/* aApplyChanges */ false);
}

WindowContext::~WindowContext() {
  if (gWindowContexts) {
    gWindowContexts->Remove(InnerWindowId());
  }
}

JSObject* WindowContext::WrapObject(JSContext* cx,
                                    JS::Handle<JSObject*> aGivenProto) {
  return WindowContext_Binding::Wrap(cx, this, aGivenProto);
}

NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(WindowContext)
  NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
  NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END

NS_IMPL_CYCLE_COLLECTING_ADDREF(WindowContext)
NS_IMPL_CYCLE_COLLECTING_RELEASE(WindowContext)

NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE_CLASS(WindowContext)

NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(WindowContext)
  if (gWindowContexts) {
    gWindowContexts->Remove(tmp->InnerWindowId());
  }

  NS_IMPL_CYCLE_COLLECTION_UNLINK(mBrowsingContext)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mChildren)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mNonSyntheticChildren)
  NS_IMPL_CYCLE_COLLECTION_UNLINK(mNonSyntheticLightDOMChildren);
  NS_IMPL_CYCLE_COLLECTION_UNLINK_PRESERVED_WRAPPER
NS_IMPL_CYCLE_COLLECTION_UNLINK_END

NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(WindowContext)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mBrowsingContext)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mChildren)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mNonSyntheticChildren)
  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mNonSyntheticLightDOMChildren)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END

}  // namespace dom
}  // namespace mozilla

namespace IPC {

using mozilla::dom::MaybeDiscarded;
using mozilla::dom::WindowContext;

void ParamTraits<MaybeDiscarded<WindowContext>>::Write(
    MessageWriter* aWriter, const MaybeDiscarded<WindowContext>& aParam) {
  uint64_t id = aParam.ContextId();
  WriteParam(aWriter, id);
}

bool ParamTraits<MaybeDiscarded<WindowContext>>::Read(
    MessageReader* aReader, MaybeDiscarded<WindowContext>* aResult) {
  uint64_t id = 0;
  if (!ReadParam(aReader, &id)) {
    return false;
  }

  if (id == 0) {
    *aResult = nullptr;
  } else if (RefPtr<WindowContext> wc = WindowContext::GetById(id)) {
    if (!wc->Group()->IsKnownForMessageReader(aReader)) {
      return false;
    }

    *aResult = std::move(wc);
  } else {
    aResult->SetDiscarded(id);
  }
  return true;
}

void ParamTraits<WindowContext::IPCInitializer>::Write(
    MessageWriter* aWriter, const WindowContext::IPCInitializer& aInit) {
  // Write actor ID parameters.
  WriteParam(aWriter, aInit.mInnerWindowId);
  WriteParam(aWriter, aInit.mOuterWindowId);
  WriteParam(aWriter, aInit.mBrowsingContextId);
  WriteParam(aWriter, aInit.mFields);
}

bool ParamTraits<WindowContext::IPCInitializer>::Read(
    MessageReader* aReader, WindowContext::IPCInitializer* aInit) {
  // Read actor ID parameters.
  return ReadParam(aReader, &aInit->mInnerWindowId) &&
         ReadParam(aReader, &aInit->mOuterWindowId) &&
         ReadParam(aReader, &aInit->mBrowsingContextId) &&
         ReadParam(aReader, &aInit->mFields);
}

template struct ParamTraits<WindowContext::BaseTransaction>;

}  // namespace IPC