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 
7 #include "ScreenOrientation.h"
8 #include "nsIDocShell.h"
9 #include "mozilla/dom/Document.h"
10 #include "nsGlobalWindow.h"
11 #include "nsSandboxFlags.h"
12 #include "nsScreen.h"
13 
14 #include "mozilla/DOMEventTargetHelper.h"
15 #include "mozilla/Hal.h"
16 #include "mozilla/Preferences.h"
17 
18 #include "mozilla/dom/ContentChild.h"
19 #include "mozilla/dom/Event.h"
20 #include "mozilla/dom/Promise.h"
21 #include "mozilla/StaticPrefs_browser.h"
22 #include "nsContentUtils.h"
23 
24 using namespace mozilla;
25 using namespace mozilla::dom;
26 
27 NS_IMPL_CYCLE_COLLECTION_INHERITED(ScreenOrientation, DOMEventTargetHelper,
28                                    mScreen);
29 
30 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(ScreenOrientation)
NS_INTERFACE_MAP_END_INHERITING(DOMEventTargetHelper)31 NS_INTERFACE_MAP_END_INHERITING(DOMEventTargetHelper)
32 
33 NS_IMPL_ADDREF_INHERITED(ScreenOrientation, DOMEventTargetHelper)
34 NS_IMPL_RELEASE_INHERITED(ScreenOrientation, DOMEventTargetHelper)
35 
36 static OrientationType InternalOrientationToType(
37     hal::ScreenOrientation aOrientation) {
38   switch (aOrientation) {
39     case hal::ScreenOrientation::PortraitPrimary:
40       return OrientationType::Portrait_primary;
41     case hal::ScreenOrientation::PortraitSecondary:
42       return OrientationType::Portrait_secondary;
43     case hal::ScreenOrientation::LandscapePrimary:
44       return OrientationType::Landscape_primary;
45     case hal::ScreenOrientation::LandscapeSecondary:
46       return OrientationType::Landscape_secondary;
47     default:
48       MOZ_CRASH("Bad aOrientation value");
49   }
50 }
51 
OrientationTypeToInternal(OrientationType aOrientation)52 static hal::ScreenOrientation OrientationTypeToInternal(
53     OrientationType aOrientation) {
54   switch (aOrientation) {
55     case OrientationType::Portrait_primary:
56       return hal::ScreenOrientation::PortraitPrimary;
57     case OrientationType::Portrait_secondary:
58       return hal::ScreenOrientation::PortraitSecondary;
59     case OrientationType::Landscape_primary:
60       return hal::ScreenOrientation::LandscapePrimary;
61     case OrientationType::Landscape_secondary:
62       return hal::ScreenOrientation::LandscapeSecondary;
63     default:
64       MOZ_CRASH("Bad aOrientation value");
65   }
66 }
67 
ScreenOrientation(nsPIDOMWindowInner * aWindow,nsScreen * aScreen)68 ScreenOrientation::ScreenOrientation(nsPIDOMWindowInner* aWindow,
69                                      nsScreen* aScreen)
70     : DOMEventTargetHelper(aWindow), mScreen(aScreen) {
71   MOZ_ASSERT(aWindow);
72   MOZ_ASSERT(aScreen);
73 
74   mAngle = aScreen->GetOrientationAngle();
75   mType = InternalOrientationToType(aScreen->GetOrientationType());
76 
77   Document* doc = GetResponsibleDocument();
78   BrowsingContext* bc = doc ? doc->GetBrowsingContext() : nullptr;
79   if (bc && !bc->IsDiscarded() && !bc->InRDMPane()) {
80     MOZ_ALWAYS_SUCCEEDS(bc->SetCurrentOrientation(mType, mAngle));
81   }
82 }
83 
~ScreenOrientation()84 ScreenOrientation::~ScreenOrientation() {
85   if (mTriedToLockDeviceOrientation) {
86     UnlockDeviceOrientation();
87   } else {
88     CleanupFullscreenListener();
89   }
90 
91   MOZ_ASSERT(!mFullscreenListener);
92 }
93 
94 class ScreenOrientation::FullscreenEventListener final
95     : public nsIDOMEventListener {
96   ~FullscreenEventListener() = default;
97 
98  public:
99   FullscreenEventListener() = default;
100 
101   NS_DECL_ISUPPORTS
102   NS_DECL_NSIDOMEVENTLISTENER
103 };
104 
105 class ScreenOrientation::VisibleEventListener final
106     : public nsIDOMEventListener {
107   ~VisibleEventListener() = default;
108 
109  public:
110   VisibleEventListener() = default;
111 
112   NS_DECL_ISUPPORTS
113   NS_DECL_NSIDOMEVENTLISTENER
114 };
115 
116 class ScreenOrientation::LockOrientationTask final : public nsIRunnable {
117   ~LockOrientationTask();
118 
119  public:
120   NS_DECL_ISUPPORTS
121   NS_DECL_NSIRUNNABLE
122 
123   LockOrientationTask(ScreenOrientation* aScreenOrientation, Promise* aPromise,
124                       hal::ScreenOrientation aOrientationLock,
125                       Document* aDocument, bool aIsFullscreen);
126 
127  protected:
128   bool OrientationLockContains(OrientationType aOrientationType);
129 
130   RefPtr<ScreenOrientation> mScreenOrientation;
131   RefPtr<Promise> mPromise;
132   hal::ScreenOrientation mOrientationLock;
133   nsCOMPtr<Document> mDocument;
134   bool mIsFullscreen;
135 };
136 
NS_IMPL_ISUPPORTS(ScreenOrientation::LockOrientationTask,nsIRunnable)137 NS_IMPL_ISUPPORTS(ScreenOrientation::LockOrientationTask, nsIRunnable)
138 
139 ScreenOrientation::LockOrientationTask::LockOrientationTask(
140     ScreenOrientation* aScreenOrientation, Promise* aPromise,
141     hal::ScreenOrientation aOrientationLock, Document* aDocument,
142     bool aIsFullscreen)
143     : mScreenOrientation(aScreenOrientation),
144       mPromise(aPromise),
145       mOrientationLock(aOrientationLock),
146       mDocument(aDocument),
147       mIsFullscreen(aIsFullscreen) {
148   MOZ_ASSERT(aScreenOrientation);
149   MOZ_ASSERT(aPromise);
150   MOZ_ASSERT(aDocument);
151 }
152 
153 ScreenOrientation::LockOrientationTask::~LockOrientationTask() = default;
154 
OrientationLockContains(OrientationType aOrientationType)155 bool ScreenOrientation::LockOrientationTask::OrientationLockContains(
156     OrientationType aOrientationType) {
157   return bool(mOrientationLock & OrientationTypeToInternal(aOrientationType));
158 }
159 
160 NS_IMETHODIMP
Run()161 ScreenOrientation::LockOrientationTask::Run() {
162   if (!mPromise) {
163     return NS_OK;
164   }
165 
166   // Step to lock the orientation as defined in the spec.
167   if (mDocument->GetOrientationPendingPromise() != mPromise) {
168     // The document's pending promise is not associated with this task
169     // to lock orientation. There has since been another request to
170     // lock orientation, thus we don't need to do anything. Old promise
171     // should be been rejected.
172     return NS_OK;
173   }
174 
175   if (mDocument->Hidden()) {
176     // Active orientation lock is not the document's orientation lock.
177     mPromise->MaybeResolveWithUndefined();
178     mDocument->ClearOrientationPendingPromise();
179     return NS_OK;
180   }
181 
182   if (mOrientationLock == hal::ScreenOrientation::None) {
183     mScreenOrientation->UnlockDeviceOrientation();
184     mPromise->MaybeResolveWithUndefined();
185     mDocument->ClearOrientationPendingPromise();
186     return NS_OK;
187   }
188 
189   BrowsingContext* bc = mDocument->GetBrowsingContext();
190   if (!bc) {
191     mPromise->MaybeResolveWithUndefined();
192     mDocument->ClearOrientationPendingPromise();
193     return NS_OK;
194   }
195 
196   OrientationType previousOrientationType = bc->GetCurrentOrientationType();
197   mScreenOrientation->LockDeviceOrientation(mOrientationLock, mIsFullscreen)
198       ->Then(
199           GetCurrentSerialEventTarget(), __func__,
200           [self = RefPtr{this}, previousOrientationType](
201               const GenericNonExclusivePromise::ResolveOrRejectValue& aValue) {
202             if (self->mPromise->State() != Promise::PromiseState::Pending) {
203               // mPromise is already resolved or rejected by
204               // DispatchChangeEventAndResolvePromise() or
205               // AbortInProcessOrientationPromises().
206               return;
207             }
208 
209             if (self->mDocument->GetOrientationPendingPromise() !=
210                 self->mPromise) {
211               // mPromise is old promise now and document has new promise by
212               // later `orientation.lock` call. Old promise is already rejected
213               // by AbortInProcessOrientationPromises()
214               return;
215             }
216             if (aValue.IsResolve()) {
217               // LockDeviceOrientation won't change orientation, so change
218               // event isn't fired.
219               if (BrowsingContext* bc = self->mDocument->GetBrowsingContext()) {
220                 OrientationType currentOrientationType =
221                     bc->GetCurrentOrientationType();
222                 if ((previousOrientationType == currentOrientationType &&
223                      self->OrientationLockContains(currentOrientationType)) ||
224                     (self->mOrientationLock ==
225                          hal::ScreenOrientation::Default &&
226                      bc->GetCurrentOrientationAngle() == 0)) {
227                   // Orientation lock will not cause an orientation change, so
228                   // we need to manually resolve the promise here.
229                   self->mPromise->MaybeResolveWithUndefined();
230                   self->mDocument->ClearOrientationPendingPromise();
231                 }
232               }
233               return;
234             }
235             self->mPromise->MaybeReject(aValue.RejectValue());
236             self->mDocument->ClearOrientationPendingPromise();
237           });
238 
239   return NS_OK;
240 }
241 
Lock(OrientationLockType aOrientation,ErrorResult & aRv)242 already_AddRefed<Promise> ScreenOrientation::Lock(
243     OrientationLockType aOrientation, ErrorResult& aRv) {
244   hal::ScreenOrientation orientation = hal::ScreenOrientation::None;
245 
246   switch (aOrientation) {
247     case OrientationLockType::Any:
248       orientation = hal::ScreenOrientation::PortraitPrimary |
249                     hal::ScreenOrientation::PortraitSecondary |
250                     hal::ScreenOrientation::LandscapePrimary |
251                     hal::ScreenOrientation::LandscapeSecondary;
252       break;
253     case OrientationLockType::Natural:
254       orientation |= hal::ScreenOrientation::Default;
255       break;
256     case OrientationLockType::Landscape:
257       orientation = hal::ScreenOrientation::LandscapePrimary |
258                     hal::ScreenOrientation::LandscapeSecondary;
259       break;
260     case OrientationLockType::Portrait:
261       orientation = hal::ScreenOrientation::PortraitPrimary |
262                     hal::ScreenOrientation::PortraitSecondary;
263       break;
264     case OrientationLockType::Portrait_primary:
265       orientation = hal::ScreenOrientation::PortraitPrimary;
266       break;
267     case OrientationLockType::Portrait_secondary:
268       orientation = hal::ScreenOrientation::PortraitSecondary;
269       break;
270     case OrientationLockType::Landscape_primary:
271       orientation = hal::ScreenOrientation::LandscapePrimary;
272       break;
273     case OrientationLockType::Landscape_secondary:
274       orientation = hal::ScreenOrientation::LandscapeSecondary;
275       break;
276     default:
277       NS_WARNING("Unexpected orientation type");
278       aRv.Throw(NS_ERROR_UNEXPECTED);
279       return nullptr;
280   }
281 
282   return LockInternal(orientation, aRv);
283 }
284 
AbortInProcessOrientationPromises(BrowsingContext * aBrowsingContext)285 void ScreenOrientation::AbortInProcessOrientationPromises(
286     BrowsingContext* aBrowsingContext) {
287   MOZ_ASSERT(aBrowsingContext);
288 
289   aBrowsingContext = aBrowsingContext->Top();
290   aBrowsingContext->PreOrderWalk([](BrowsingContext* aContext) {
291     nsIDocShell* docShell = aContext->GetDocShell();
292     if (docShell) {
293       Document* doc = docShell->GetDocument();
294       if (doc) {
295         Promise* promise = doc->GetOrientationPendingPromise();
296         if (promise) {
297           promise->MaybeReject(NS_ERROR_DOM_ABORT_ERR);
298           doc->ClearOrientationPendingPromise();
299         }
300       }
301     }
302   });
303 }
304 
LockInternal(hal::ScreenOrientation aOrientation,ErrorResult & aRv)305 already_AddRefed<Promise> ScreenOrientation::LockInternal(
306     hal::ScreenOrientation aOrientation, ErrorResult& aRv) {
307   // Steps to apply an orientation lock as defined in spec.
308 
309   Document* doc = GetResponsibleDocument();
310   if (NS_WARN_IF(!doc)) {
311     aRv.Throw(NS_ERROR_UNEXPECTED);
312     return nullptr;
313   }
314 
315   nsCOMPtr<nsPIDOMWindowInner> owner = GetOwner();
316   if (NS_WARN_IF(!owner)) {
317     aRv.Throw(NS_ERROR_UNEXPECTED);
318     return nullptr;
319   }
320 
321   nsCOMPtr<nsIDocShell> docShell = owner->GetDocShell();
322   if (NS_WARN_IF(!docShell)) {
323     aRv.Throw(NS_ERROR_UNEXPECTED);
324     return nullptr;
325   }
326 
327   nsCOMPtr<nsIGlobalObject> go = do_QueryInterface(owner);
328   MOZ_ASSERT(go);
329   RefPtr<Promise> p = Promise::Create(go, aRv);
330   if (NS_WARN_IF(aRv.Failed())) {
331     return nullptr;
332   }
333 
334 #if !defined(MOZ_WIDGET_ANDROID)
335   // User agent does not support locking the screen orientation.
336   p->MaybeReject(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
337   return p.forget();
338 #else
339   // Bypass locking screen orientation if preference is false
340   if (!StaticPrefs::dom_screenorientation_allow_lock()) {
341     p->MaybeReject(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
342     return p.forget();
343   }
344 
345   LockPermission perm = GetLockOrientationPermission(true);
346   if (perm == LOCK_DENIED) {
347     p->MaybeReject(NS_ERROR_DOM_SECURITY_ERR);
348     return p.forget();
349   }
350 
351   RefPtr<BrowsingContext> bc = docShell->GetBrowsingContext();
352   bc = bc ? bc->Top() : nullptr;
353   if (!bc) {
354     aRv.Throw(NS_ERROR_UNEXPECTED);
355     return nullptr;
356   }
357 
358   bc->SetOrientationLock(aOrientation, aRv);
359   if (aRv.Failed()) {
360     return nullptr;
361   }
362 
363   AbortInProcessOrientationPromises(bc);
364   dom::ContentChild::GetSingleton()->SendAbortOtherOrientationPendingPromises(
365       bc);
366 
367   if (!doc->SetOrientationPendingPromise(p)) {
368     p->MaybeReject(NS_ERROR_DOM_SECURITY_ERR);
369     return p.forget();
370   }
371 
372   nsCOMPtr<nsIRunnable> lockOrientationTask = new LockOrientationTask(
373       this, p, aOrientation, doc, perm == FULLSCREEN_LOCK_ALLOWED);
374   aRv = NS_DispatchToMainThread(lockOrientationTask);
375   if (NS_WARN_IF(aRv.Failed())) {
376     return nullptr;
377   }
378 
379   return p.forget();
380 #endif
381 }
382 
LockDeviceOrientation(hal::ScreenOrientation aOrientation,bool aIsFullscreen)383 RefPtr<GenericNonExclusivePromise> ScreenOrientation::LockDeviceOrientation(
384     hal::ScreenOrientation aOrientation, bool aIsFullscreen) {
385   if (!GetOwner()) {
386     return GenericNonExclusivePromise::CreateAndReject(NS_ERROR_DOM_ABORT_ERR,
387                                                        __func__);
388   }
389 
390   nsCOMPtr<EventTarget> target = GetOwner()->GetDoc();
391   // We need to register a listener so we learn when we leave fullscreen
392   // and when we will have to unlock the screen.
393   // This needs to be done before LockScreenOrientation call to make sure
394   // the locking can be unlocked.
395   if (aIsFullscreen && !target) {
396     return GenericNonExclusivePromise::CreateAndReject(NS_ERROR_DOM_ABORT_ERR,
397                                                        __func__);
398   }
399 
400   // We are fullscreen and lock has been accepted.
401   if (aIsFullscreen) {
402     if (!mFullscreenListener) {
403       mFullscreenListener = new FullscreenEventListener();
404     }
405 
406     nsresult rv = target->AddSystemEventListener(u"fullscreenchange"_ns,
407                                                  mFullscreenListener,
408                                                  /* aUseCapture = */ true);
409     if (NS_WARN_IF(NS_FAILED(rv))) {
410       return GenericNonExclusivePromise::CreateAndReject(NS_ERROR_DOM_ABORT_ERR,
411                                                          __func__);
412     }
413   }
414 
415   mTriedToLockDeviceOrientation = true;
416   return hal::LockScreenOrientation(aOrientation);
417 }
418 
Unlock(ErrorResult & aRv)419 void ScreenOrientation::Unlock(ErrorResult& aRv) {
420   RefPtr<Promise> p = LockInternal(hal::ScreenOrientation::None, aRv);
421 }
422 
UnlockDeviceOrientation()423 void ScreenOrientation::UnlockDeviceOrientation() {
424   hal::UnlockScreenOrientation();
425   CleanupFullscreenListener();
426 }
427 
CleanupFullscreenListener()428 void ScreenOrientation::CleanupFullscreenListener() {
429   if (!mFullscreenListener || !GetOwner()) {
430     mFullscreenListener = nullptr;
431     return;
432   }
433 
434   // Remove event listener in case of fullscreen lock.
435   if (nsCOMPtr<EventTarget> target = GetOwner()->GetDoc()) {
436     target->RemoveSystemEventListener(u"fullscreenchange"_ns,
437                                       mFullscreenListener,
438                                       /* useCapture */ true);
439   }
440 
441   mFullscreenListener = nullptr;
442 }
443 
DeviceType(CallerType aCallerType) const444 OrientationType ScreenOrientation::DeviceType(CallerType aCallerType) const {
445   return nsContentUtils::ResistFingerprinting(aCallerType)
446              ? OrientationType::Landscape_primary
447              : mType;
448 }
449 
DeviceAngle(CallerType aCallerType) const450 uint16_t ScreenOrientation::DeviceAngle(CallerType aCallerType) const {
451   return nsContentUtils::ResistFingerprinting(aCallerType) ? 0 : mAngle;
452 }
453 
GetType(CallerType aCallerType,ErrorResult & aRv) const454 OrientationType ScreenOrientation::GetType(CallerType aCallerType,
455                                            ErrorResult& aRv) const {
456   if (nsContentUtils::ResistFingerprinting(aCallerType)) {
457     return OrientationType::Landscape_primary;
458   }
459 
460   Document* doc = GetResponsibleDocument();
461   BrowsingContext* bc = doc ? doc->GetBrowsingContext() : nullptr;
462   if (!bc) {
463     aRv.Throw(NS_ERROR_UNEXPECTED);
464     return OrientationType::Portrait_primary;
465   }
466 
467   return bc->GetCurrentOrientationType();
468 }
469 
GetAngle(CallerType aCallerType,ErrorResult & aRv) const470 uint16_t ScreenOrientation::GetAngle(CallerType aCallerType,
471                                      ErrorResult& aRv) const {
472   if (nsContentUtils::ResistFingerprinting(aCallerType)) {
473     return 0;
474   }
475 
476   Document* doc = GetResponsibleDocument();
477   BrowsingContext* bc = doc ? doc->GetBrowsingContext() : nullptr;
478   if (!bc) {
479     aRv.Throw(NS_ERROR_UNEXPECTED);
480     return 0;
481   }
482 
483   return bc->GetCurrentOrientationAngle();
484 }
485 
486 ScreenOrientation::LockPermission
GetLockOrientationPermission(bool aCheckSandbox) const487 ScreenOrientation::GetLockOrientationPermission(bool aCheckSandbox) const {
488   nsCOMPtr<nsPIDOMWindowInner> owner = GetOwner();
489   if (!owner) {
490     return LOCK_DENIED;
491   }
492 
493   // Chrome can always lock the screen orientation.
494   if (owner->GetBrowsingContext()->IsChrome()) {
495     return LOCK_ALLOWED;
496   }
497 
498   nsCOMPtr<Document> doc = owner->GetDoc();
499   if (!doc || doc->Hidden()) {
500     return LOCK_DENIED;
501   }
502 
503   // Sandboxed without "allow-orientation-lock"
504   if (aCheckSandbox && doc->GetSandboxFlags() & SANDBOXED_ORIENTATION_LOCK) {
505     return LOCK_DENIED;
506   }
507 
508   if (Preferences::GetBool(
509           "dom.screenorientation.testing.non_fullscreen_lock_allow", false)) {
510     return LOCK_ALLOWED;
511   }
512 
513   // Other content must be fullscreen in order to lock orientation.
514   return doc->Fullscreen() ? FULLSCREEN_LOCK_ALLOWED : LOCK_DENIED;
515 }
516 
GetResponsibleDocument() const517 Document* ScreenOrientation::GetResponsibleDocument() const {
518   nsCOMPtr<nsPIDOMWindowInner> owner = GetOwner();
519   if (!owner) {
520     return nullptr;
521   }
522 
523   return owner->GetDoc();
524 }
525 
MaybeChanged()526 void ScreenOrientation::MaybeChanged() {
527   if (ShouldResistFingerprinting()) {
528     return;
529   }
530 
531   Document* doc = GetResponsibleDocument();
532   BrowsingContext* bc = doc ? doc->GetBrowsingContext() : nullptr;
533   if (!bc) {
534     return;
535   }
536 
537   hal::ScreenOrientation orientation = mScreen->GetOrientationType();
538   if (orientation != hal::ScreenOrientation::PortraitPrimary &&
539       orientation != hal::ScreenOrientation::PortraitSecondary &&
540       orientation != hal::ScreenOrientation::LandscapePrimary &&
541       orientation != hal::ScreenOrientation::LandscapeSecondary) {
542     // The platform may notify of some other values from
543     // an orientation lock, but we only care about real
544     // changes to screen orientation which result in one of
545     // the values we care about.
546     return;
547   }
548 
549   OrientationType previousOrientation = mType;
550   mAngle = mScreen->GetOrientationAngle();
551   mType = InternalOrientationToType(orientation);
552 
553   DebugOnly<nsresult> rv;
554   if (mScreen && mType != previousOrientation) {
555     // Use of mozorientationchange is deprecated.
556     rv = mScreen->DispatchTrustedEvent(u"mozorientationchange"_ns);
557     NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "DispatchTrustedEvent failed");
558   }
559 
560   if (doc->Hidden() && !mVisibleListener) {
561     mVisibleListener = new VisibleEventListener();
562     rv = doc->AddSystemEventListener(u"visibilitychange"_ns, mVisibleListener,
563                                      /* aUseCapture = */ true);
564     NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "AddSystemEventListener failed");
565     return;
566   }
567 
568   if (mType != bc->GetCurrentOrientationType()) {
569     rv = bc->SetCurrentOrientation(mType, mAngle);
570     NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "SetCurrentOrientation failed");
571 
572     nsCOMPtr<nsIRunnable> runnable = DispatchChangeEventAndResolvePromise();
573     rv = NS_DispatchToMainThread(runnable);
574     NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "NS_DispatchToMainThread failed");
575   }
576 }
577 
UpdateActiveOrientationLock(hal::ScreenOrientation aOrientation)578 void ScreenOrientation::UpdateActiveOrientationLock(
579     hal::ScreenOrientation aOrientation) {
580   if (aOrientation == hal::ScreenOrientation::None) {
581     hal::UnlockScreenOrientation();
582   } else {
583     hal::LockScreenOrientation(aOrientation)
584         ->Then(
585             GetMainThreadSerialEventTarget(), __func__,
586             [](const GenericNonExclusivePromise::ResolveOrRejectValue& aValue) {
587               NS_WARNING_ASSERTION(aValue.IsResolve(),
588                                    "hal::LockScreenOrientation failed");
589             });
590   }
591 }
592 
593 nsCOMPtr<nsIRunnable>
DispatchChangeEventAndResolvePromise()594 ScreenOrientation::DispatchChangeEventAndResolvePromise() {
595   RefPtr<Document> doc = GetResponsibleDocument();
596   RefPtr<ScreenOrientation> self = this;
597   return NS_NewRunnableFunction(
598       "dom::ScreenOrientation::DispatchChangeEvent", [self, doc]() {
599         DebugOnly<nsresult> rv = self->DispatchTrustedEvent(u"change"_ns);
600         NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "DispatchTrustedEvent failed");
601         if (doc) {
602           Promise* pendingPromise = doc->GetOrientationPendingPromise();
603           if (pendingPromise) {
604             pendingPromise->MaybeResolveWithUndefined();
605             doc->ClearOrientationPendingPromise();
606           }
607         }
608       });
609 }
610 
WrapObject(JSContext * aCx,JS::Handle<JSObject * > aGivenProto)611 JSObject* ScreenOrientation::WrapObject(JSContext* aCx,
612                                         JS::Handle<JSObject*> aGivenProto) {
613   return ScreenOrientation_Binding::Wrap(aCx, this, aGivenProto);
614 }
615 
ShouldResistFingerprinting() const616 bool ScreenOrientation::ShouldResistFingerprinting() const {
617   if (nsContentUtils::ShouldResistFingerprinting(
618           "Legacy RFP function called to avoid observed hangs in the code "
619           "below if we can avoid it.")) {
620     bool resist = false;
621     if (nsCOMPtr<nsPIDOMWindowInner> owner = GetOwner()) {
622       resist = nsContentUtils::ShouldResistFingerprinting(owner->GetDocShell());
623     }
624     return resist;
625   }
626   return false;
627 }
628 
NS_IMPL_ISUPPORTS(ScreenOrientation::VisibleEventListener,nsIDOMEventListener)629 NS_IMPL_ISUPPORTS(ScreenOrientation::VisibleEventListener, nsIDOMEventListener)
630 
631 NS_IMETHODIMP
632 ScreenOrientation::VisibleEventListener::HandleEvent(Event* aEvent) {
633   // Document may have become visible, if the page is visible, run the steps
634   // following the "now visible algorithm" as specified.
635   MOZ_ASSERT(aEvent->GetCurrentTarget());
636   nsCOMPtr<nsINode> eventTargetNode =
637       nsINode::FromEventTarget(aEvent->GetCurrentTarget());
638   if (!eventTargetNode || !eventTargetNode->IsDocument() ||
639       eventTargetNode->AsDocument()->Hidden()) {
640     return NS_OK;
641   }
642 
643   RefPtr<Document> doc = eventTargetNode->AsDocument();
644   auto* win = nsGlobalWindowInner::Cast(doc->GetInnerWindow());
645   if (!win) {
646     return NS_OK;
647   }
648 
649   ErrorResult rv;
650   nsScreen* screen = win->GetScreen(rv);
651   if (NS_WARN_IF(rv.Failed())) {
652     return rv.StealNSResult();
653   }
654 
655   MOZ_ASSERT(screen);
656   ScreenOrientation* orientation = screen->Orientation();
657   MOZ_ASSERT(orientation);
658 
659   doc->RemoveSystemEventListener(u"visibilitychange"_ns, this, true);
660 
661   BrowsingContext* bc = doc->GetBrowsingContext();
662   if (bc && bc->GetCurrentOrientationType() !=
663                 orientation->DeviceType(CallerType::System)) {
664     nsresult result =
665         bc->SetCurrentOrientation(orientation->DeviceType(CallerType::System),
666                                   orientation->DeviceAngle(CallerType::System));
667     NS_ENSURE_SUCCESS(result, result);
668 
669     nsCOMPtr<nsIRunnable> runnable =
670         orientation->DispatchChangeEventAndResolvePromise();
671     rv = NS_DispatchToMainThread(runnable);
672     if (NS_WARN_IF(rv.Failed())) {
673       return rv.StealNSResult();
674     }
675   }
676 
677   return NS_OK;
678 }
679 
NS_IMPL_ISUPPORTS(ScreenOrientation::FullscreenEventListener,nsIDOMEventListener)680 NS_IMPL_ISUPPORTS(ScreenOrientation::FullscreenEventListener,
681                   nsIDOMEventListener)
682 
683 NS_IMETHODIMP
684 ScreenOrientation::FullscreenEventListener::HandleEvent(Event* aEvent) {
685 #ifdef DEBUG
686   nsAutoString eventType;
687   aEvent->GetType(eventType);
688 
689   MOZ_ASSERT(eventType.EqualsLiteral("fullscreenchange"));
690 #endif
691 
692   EventTarget* target = aEvent->GetCurrentTarget();
693   MOZ_ASSERT(target);
694   MOZ_ASSERT(target->IsNode());
695   RefPtr<Document> doc = nsINode::FromEventTarget(target)->AsDocument();
696   MOZ_ASSERT(doc);
697 
698   // We have to make sure that the event we got is the event sent when
699   // fullscreen is disabled because we could get one when fullscreen
700   // got enabled if the lock call is done at the same moment.
701   if (doc->Fullscreen()) {
702     return NS_OK;
703   }
704 
705   hal::UnlockScreenOrientation();
706 
707   target->RemoveSystemEventListener(u"fullscreenchange"_ns, this, true);
708   return NS_OK;
709 }
710