summaryrefslogtreecommitdiffstats
path: root/dom/base/ScreenOrientation.cpp
blob: bb3ccf5c3346e853f780d80f45fdf1b885691daa (plain)
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
/* 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 "ScreenOrientation.h"
#include "nsIDeviceSensors.h"
#include "nsIDocShell.h"
#include "nsIDocument.h"
#include "nsGlobalWindow.h"
#include "nsSandboxFlags.h"
#include "nsScreen.h"

#include "mozilla/DOMEventTargetHelper.h"
#include "mozilla/Hal.h"
#include "mozilla/Preferences.h"

#include "mozilla/dom/Promise.h"
#include "nsContentUtils.h"

using namespace mozilla;
using namespace mozilla::dom;

NS_IMPL_CYCLE_COLLECTION_INHERITED(ScreenOrientation,
                                   DOMEventTargetHelper,
                                   mScreen);

NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION_INHERITED(ScreenOrientation)
NS_INTERFACE_MAP_END_INHERITING(DOMEventTargetHelper)

NS_IMPL_ADDREF_INHERITED(ScreenOrientation, DOMEventTargetHelper)
NS_IMPL_RELEASE_INHERITED(ScreenOrientation, DOMEventTargetHelper)

static OrientationType
InternalOrientationToType(ScreenOrientationInternal aOrientation)
{
  switch (aOrientation) {
  case eScreenOrientation_PortraitPrimary:
    return OrientationType::Portrait_primary;
  case eScreenOrientation_PortraitSecondary:
    return OrientationType::Portrait_secondary;
  case eScreenOrientation_LandscapePrimary:
    return OrientationType::Landscape_primary;
  case eScreenOrientation_LandscapeSecondary:
    return OrientationType::Landscape_secondary;
  default:
    MOZ_CRASH("Bad aOrientation value");
  }
}

static ScreenOrientationInternal
OrientationTypeToInternal(OrientationType aOrientation)
{
  switch (aOrientation) {
  case OrientationType::Portrait_primary:
    return eScreenOrientation_PortraitPrimary;
  case OrientationType::Portrait_secondary:
    return eScreenOrientation_PortraitSecondary;
  case OrientationType::Landscape_primary:
    return eScreenOrientation_LandscapePrimary;
  case OrientationType::Landscape_secondary:
    return eScreenOrientation_LandscapeSecondary;
  default:
    MOZ_CRASH("Bad aOrientation value");
  }
}

ScreenOrientation::ScreenOrientation(nsPIDOMWindowInner* aWindow, nsScreen* aScreen)
  : DOMEventTargetHelper(aWindow), mScreen(aScreen)
{
  MOZ_ASSERT(aWindow);
  MOZ_ASSERT(aScreen);

  hal::RegisterScreenConfigurationObserver(this);

  hal::ScreenConfiguration config;
  hal::GetCurrentScreenConfiguration(&config);
  mType = InternalOrientationToType(config.orientation());
  mAngle = config.angle();

  nsIDocument* doc = GetResponsibleDocument();
  if (doc) {
    doc->SetCurrentOrientation(mType, mAngle);
  }
}

ScreenOrientation::~ScreenOrientation()
{
  hal::UnregisterScreenConfigurationObserver(this);
  MOZ_ASSERT(!mFullScreenListener);
}

class ScreenOrientation::FullScreenEventListener final : public nsIDOMEventListener
{
  ~FullScreenEventListener() {}
public:
  FullScreenEventListener() {}

  NS_DECL_ISUPPORTS
  NS_DECL_NSIDOMEVENTLISTENER
};

class ScreenOrientation::VisibleEventListener final : public nsIDOMEventListener
{
  ~VisibleEventListener() {}
public:
  VisibleEventListener() {}

  NS_DECL_ISUPPORTS
  NS_DECL_NSIDOMEVENTLISTENER
};

class ScreenOrientation::LockOrientationTask final : public nsIRunnable
{
  ~LockOrientationTask();
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIRUNNABLE

  LockOrientationTask(ScreenOrientation* aScreenOrientation,
                      Promise* aPromise,
                      ScreenOrientationInternal aOrientationLock,
                      nsIDocument* aDocument,
                      bool aIsFullScreen);
protected:
  bool OrientationLockContains(OrientationType aOrientationType);

  RefPtr<ScreenOrientation> mScreenOrientation;
  RefPtr<Promise> mPromise;
  ScreenOrientationInternal mOrientationLock;
  nsCOMPtr<nsIDocument> mDocument;
  bool mIsFullScreen;
};

NS_IMPL_ISUPPORTS(ScreenOrientation::LockOrientationTask, nsIRunnable)

ScreenOrientation::LockOrientationTask::LockOrientationTask(
  ScreenOrientation* aScreenOrientation, Promise* aPromise,
  ScreenOrientationInternal aOrientationLock,
  nsIDocument* aDocument, bool aIsFullScreen)
  : mScreenOrientation(aScreenOrientation), mPromise(aPromise),
    mOrientationLock(aOrientationLock), mDocument(aDocument),
    mIsFullScreen(aIsFullScreen)
{
  MOZ_ASSERT(aScreenOrientation);
  MOZ_ASSERT(aPromise);
  MOZ_ASSERT(aDocument);
}

ScreenOrientation::LockOrientationTask::~LockOrientationTask()
{
}

bool
ScreenOrientation::LockOrientationTask::OrientationLockContains(
  OrientationType aOrientationType)
{
  return mOrientationLock & OrientationTypeToInternal(aOrientationType);
}

NS_IMETHODIMP
ScreenOrientation::LockOrientationTask::Run()
{
  // Step to lock the orientation as defined in the spec.

  if (mDocument->GetOrientationPendingPromise() != mPromise) {
    // The document's pending promise is not associated with this task
    // to lock orientation. There has since been another request to
    // lock orientation, thus we don't need to do anything. Old promise
    // should be been rejected.
    return NS_OK;
  }

  if (mDocument->Hidden()) {
    // Active orientation lock is not the document's orientation lock.
    mPromise->MaybeResolveWithUndefined();
    mDocument->SetOrientationPendingPromise(nullptr);
    return NS_OK;
  }

  if (mOrientationLock == eScreenOrientation_None) {
    mScreenOrientation->UnlockDeviceOrientation();
    mPromise->MaybeResolveWithUndefined();
    mDocument->SetOrientationPendingPromise(nullptr);
    return NS_OK;
  }

  ErrorResult rv;
  bool result = mScreenOrientation->LockDeviceOrientation(mOrientationLock,
                                                          mIsFullScreen, rv);
  if (NS_WARN_IF(rv.Failed())) {
    return rv.StealNSResult();
  }

  if (NS_WARN_IF(!result)) {
    mPromise->MaybeReject(NS_ERROR_UNEXPECTED);
    mDocument->SetOrientationPendingPromise(nullptr);
    return NS_OK;
  }

  if (OrientationLockContains(mDocument->CurrentOrientationType()) ||
      (mOrientationLock == eScreenOrientation_Default &&
       mDocument->CurrentOrientationAngle() == 0)) {
    // Orientation lock will not cause an orientation change.
    mPromise->MaybeResolveWithUndefined();
    mDocument->SetOrientationPendingPromise(nullptr);
  }

  return NS_OK;
}

already_AddRefed<Promise>
ScreenOrientation::Lock(OrientationLockType aOrientation, ErrorResult& aRv)
{
  ScreenOrientationInternal orientation = eScreenOrientation_None;

  switch (aOrientation) {
  case OrientationLockType::Any:
    orientation = eScreenOrientation_PortraitPrimary |
                  eScreenOrientation_PortraitSecondary |
                  eScreenOrientation_LandscapePrimary |
                  eScreenOrientation_LandscapeSecondary;
    break;
  case OrientationLockType::Natural:
    orientation |= eScreenOrientation_Default;
    break;
  case OrientationLockType::Landscape:
    orientation = eScreenOrientation_LandscapePrimary |
                  eScreenOrientation_LandscapeSecondary;
    break;
  case OrientationLockType::Portrait:
    orientation = eScreenOrientation_PortraitPrimary |
                  eScreenOrientation_PortraitSecondary;
    break;
  case OrientationLockType::Portrait_primary:
    orientation = eScreenOrientation_PortraitPrimary;
    break;
  case OrientationLockType::Portrait_secondary:
    orientation = eScreenOrientation_PortraitSecondary;
    break;
  case OrientationLockType::Landscape_primary:
    orientation = eScreenOrientation_LandscapePrimary;
    break;
  case OrientationLockType::Landscape_secondary:
    orientation = eScreenOrientation_LandscapeSecondary;
    break;
  default:
    NS_WARNING("Unexpected orientation type");
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return nullptr;
  }

  return LockInternal(orientation, aRv);
}

static inline void
AbortOrientationPromises(nsIDocShell* aDocShell)
{
  MOZ_ASSERT(aDocShell);

  nsIDocument* doc = aDocShell->GetDocument();
  if (doc) {
    Promise* promise = doc->GetOrientationPendingPromise();
    if (promise) {
      promise->MaybeReject(NS_ERROR_DOM_ABORT_ERR);
      doc->SetOrientationPendingPromise(nullptr);
    }
  }

  int32_t childCount;
  aDocShell->GetChildCount(&childCount);
  for (int32_t i = 0; i < childCount; i++) {
    nsCOMPtr<nsIDocShellTreeItem> child;
    if (NS_SUCCEEDED(aDocShell->GetChildAt(i, getter_AddRefs(child)))) {
      nsCOMPtr<nsIDocShell> childShell(do_QueryInterface(child));
      if (childShell) {
        AbortOrientationPromises(childShell);
      }
    }
  }
}

already_AddRefed<Promise>
ScreenOrientation::LockInternal(ScreenOrientationInternal aOrientation, ErrorResult& aRv)
{
  // Steps to apply an orientation lock as defined in spec.

  nsIDocument* doc = GetResponsibleDocument();
  if (NS_WARN_IF(!doc)) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return nullptr;
  }

  nsCOMPtr<nsPIDOMWindowInner> owner = GetOwner();
  if (NS_WARN_IF(!owner)) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return nullptr;
  }

  nsCOMPtr<nsIDocShell> docShell = owner->GetDocShell();
  if (NS_WARN_IF(!docShell)) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return nullptr;
  }

  nsCOMPtr<nsIGlobalObject> go = do_QueryInterface(owner);
  MOZ_ASSERT(go);
  RefPtr<Promise> p = Promise::Create(go, aRv);
  if (NS_WARN_IF(aRv.Failed())) {
    return nullptr;
  }

#if !defined(MOZ_WIDGET_ANDROID) && !defined(MOZ_WIDGET_GONK)
  // User agent does not support locking the screen orientation.
  p->MaybeReject(NS_ERROR_DOM_NOT_SUPPORTED_ERR);
  return p.forget();
#else
  LockPermission perm = GetLockOrientationPermission(true);
  if (perm == LOCK_DENIED) {
    p->MaybeReject(NS_ERROR_DOM_SECURITY_ERR);
    return p.forget();
  }

  nsCOMPtr<nsIDocShellTreeItem> root;
  docShell->GetSameTypeRootTreeItem(getter_AddRefs(root));
  nsCOMPtr<nsIDocShell> rootShell(do_QueryInterface(root));
  if (!rootShell) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return nullptr;
  }

  rootShell->SetOrientationLock(aOrientation);
  AbortOrientationPromises(rootShell);

  doc->SetOrientationPendingPromise(p);

  nsCOMPtr<nsIRunnable> lockOrientationTask =
    new LockOrientationTask(this, p, aOrientation, doc,
                            perm == FULLSCREEN_LOCK_ALLOWED);
  aRv = NS_DispatchToMainThread(lockOrientationTask);
  if (NS_WARN_IF(aRv.Failed())) {
    return nullptr;
  }

  return p.forget();
#endif
}

bool
ScreenOrientation::LockDeviceOrientation(ScreenOrientationInternal aOrientation,
                                         bool aIsFullScreen, ErrorResult& aRv)
{
  if (!GetOwner()) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return false;
  }

  nsCOMPtr<EventTarget> target = do_QueryInterface(GetOwner()->GetDoc());
  // We need to register a listener so we learn when we leave full-screen
  // and when we will have to unlock the screen.
  // This needs to be done before LockScreenOrientation call to make sure
  // the locking can be unlocked.
  if (aIsFullScreen && !target) {
    return false;
  }

  if (NS_WARN_IF(!hal::LockScreenOrientation(aOrientation))) {
    return false;
  }

  // We are fullscreen and lock has been accepted.
  if (aIsFullScreen && !mFullScreenListener) {
    mFullScreenListener = new FullScreenEventListener();
    aRv = target->AddSystemEventListener(NS_LITERAL_STRING("fullscreenchange"),
                                         mFullScreenListener, /* useCapture = */ true);
    if (NS_WARN_IF(aRv.Failed())) {
      return false;
    }
  }

  return true;
}

void
ScreenOrientation::Unlock(ErrorResult& aRv)
{
  RefPtr<Promise> p = LockInternal(eScreenOrientation_None, aRv);
}

void
ScreenOrientation::UnlockDeviceOrientation()
{
  hal::UnlockScreenOrientation();

  if (!mFullScreenListener || !GetOwner()) {
    mFullScreenListener = nullptr;
    return;
  }

  // Remove event listener in case of fullscreen lock.
  nsCOMPtr<EventTarget> target = do_QueryInterface(GetOwner()->GetDoc());
  if (target) {
    DebugOnly<nsresult> rv =
      target->RemoveSystemEventListener(NS_LITERAL_STRING("fullscreenchange"),
                                        mFullScreenListener,
                                        /* useCapture */ true);
    NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "RemoveSystemEventListener failed");
  }

  mFullScreenListener = nullptr;
}

OrientationType
ScreenOrientation::DeviceType() const
{
  return ShouldResistFingerprinting() ? OrientationType::Landscape_primary
                                      : mType;
}

uint16_t
ScreenOrientation::DeviceAngle() const
{
  return ShouldResistFingerprinting() ? 0 : mAngle;
}

OrientationType
ScreenOrientation::GetType(ErrorResult& aRv) const
{
  if (ShouldResistFingerprinting()) {
    return OrientationType::Landscape_primary;
  }

  nsIDocument* doc = GetResponsibleDocument();
  if (!doc) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return OrientationType::Portrait_primary;
  }

  return doc->CurrentOrientationType();
}

uint16_t
ScreenOrientation::GetAngle(ErrorResult& aRv) const
{
  if (ShouldResistFingerprinting()) {
    return 0;
  }

  nsIDocument* doc = GetResponsibleDocument();
  if (!doc) {
    aRv.Throw(NS_ERROR_UNEXPECTED);
    return 0;
  }

  return doc->CurrentOrientationAngle();
}

ScreenOrientation::LockPermission
ScreenOrientation::GetLockOrientationPermission(bool aCheckSandbox) const
{
  nsCOMPtr<nsPIDOMWindowInner> owner = GetOwner();
  if (!owner) {
    return LOCK_DENIED;
  }

  // Chrome can always lock the screen orientation.
  nsIDocShell* docShell = owner->GetDocShell();
  if (docShell && docShell->ItemType() == nsIDocShellTreeItem::typeChrome) {
    return LOCK_ALLOWED;
  }

  nsCOMPtr<nsIDocument> doc = owner->GetDoc();
  if (!doc || doc->Hidden()) {
    return LOCK_DENIED;
  }

  // Sandboxed without "allow-orientation-lock"
  if (aCheckSandbox && doc->GetSandboxFlags() & SANDBOXED_ORIENTATION_LOCK) {
    return LOCK_DENIED;
  }

  // Apps can always lock the screen orientation.
  if (doc->NodePrincipal()->GetAppStatus() >=
        nsIPrincipal::APP_STATUS_INSTALLED) {
    return LOCK_ALLOWED;
  }

  if (Preferences::GetBool("dom.screenorientation.testing.non_fullscreen_lock_allow",
                           false)) {
    return LOCK_ALLOWED;
  }

  // Other content must be full-screen in order to lock orientation.
  return doc->Fullscreen() ? FULLSCREEN_LOCK_ALLOWED : LOCK_DENIED;
}

nsIDocument*
ScreenOrientation::GetResponsibleDocument() const
{
  nsCOMPtr<nsPIDOMWindowInner> owner = GetOwner();
  if (!owner) {
    return nullptr;
  }

  return owner->GetDoc();
}

void
ScreenOrientation::Notify(const hal::ScreenConfiguration& aConfiguration)
{
  if (ShouldResistFingerprinting()) {
    return;
  }

  nsIDocument* doc = GetResponsibleDocument();
  if (!doc) {
    return;
  }

  ScreenOrientationInternal orientation = aConfiguration.orientation();
  if (orientation != eScreenOrientation_PortraitPrimary &&
      orientation != eScreenOrientation_PortraitSecondary &&
      orientation != eScreenOrientation_LandscapePrimary &&
      orientation != eScreenOrientation_LandscapeSecondary) {
    // The platform may notify of some other values from
    // an orientation lock, but we only care about real
    // changes to screen orientation which result in one of
    // the values we care about.
    return;
  }

  OrientationType previousOrientation = mType;
  mAngle = aConfiguration.angle();
  mType = InternalOrientationToType(orientation);

  DebugOnly<nsresult> rv;
  if (mScreen && mType != previousOrientation) {
    // Use of mozorientationchange is deprecated.
    rv = mScreen->DispatchTrustedEvent(NS_LITERAL_STRING("mozorientationchange"));
    NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "DispatchTrustedEvent failed");
  }

  if (doc->Hidden() && !mVisibleListener) {
    mVisibleListener = new VisibleEventListener();
    rv = doc->AddSystemEventListener(NS_LITERAL_STRING("visibilitychange"),
                                     mVisibleListener, /* useCapture = */ true);
    NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "AddSystemEventListener failed");
    return;
  }

  if (mType != doc->CurrentOrientationType()) {
    doc->SetCurrentOrientation(mType, mAngle);

    Promise* pendingPromise = doc->GetOrientationPendingPromise();
    if (pendingPromise) {
      pendingPromise->MaybeResolveWithUndefined();
      doc->SetOrientationPendingPromise(nullptr);
    }

    nsCOMPtr<nsIRunnable> runnable = NewRunnableMethod(this,
      &ScreenOrientation::DispatchChangeEvent);
    rv = NS_DispatchToMainThread(runnable);
    NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "NS_DispatchToMainThread failed");
  }
}

void
ScreenOrientation::UpdateActiveOrientationLock(ScreenOrientationInternal aOrientation)
{
  if (aOrientation == eScreenOrientation_None) {
    hal::UnlockScreenOrientation();
  } else {
    DebugOnly<bool> ok = hal::LockScreenOrientation(aOrientation);
    NS_WARNING_ASSERTION(ok, "hal::LockScreenOrientation failed");
  }
}

void
ScreenOrientation::DispatchChangeEvent()
{
  DebugOnly<nsresult> rv = DispatchTrustedEvent(NS_LITERAL_STRING("change"));
  NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "DispatchTrustedEvent failed");
}

JSObject*
ScreenOrientation::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aGivenProto)
{
  return ScreenOrientationBinding::Wrap(aCx, this, aGivenProto);
}

bool
ScreenOrientation::ShouldResistFingerprinting() const
{
  bool resist = false;
  if (nsCOMPtr<nsPIDOMWindowInner> owner = GetOwner()) {
    resist = nsContentUtils::ShouldResistFingerprinting(owner->GetDocShell());
  }
  return resist;
}

NS_IMPL_ISUPPORTS(ScreenOrientation::VisibleEventListener, nsIDOMEventListener)

NS_IMETHODIMP
ScreenOrientation::VisibleEventListener::HandleEvent(nsIDOMEvent* aEvent)
{
  // Document may have become visible, if the page is visible, run the steps
  // following the "now visible algorithm" as specified.
  nsCOMPtr<EventTarget> target = aEvent->InternalDOMEvent()->GetCurrentTarget();
  MOZ_ASSERT(target);

  nsCOMPtr<nsIDocument> doc = do_QueryInterface(target);
  if (!doc || doc->Hidden()) {
    return NS_OK;
  }

  auto* win = nsGlobalWindow::Cast(doc->GetInnerWindow());
  if (!win) {
    return NS_OK;
  }

  ErrorResult rv;
  nsScreen* screen = win->GetScreen(rv);
  if (NS_WARN_IF(rv.Failed())) {
    return rv.StealNSResult();
  }

  MOZ_ASSERT(screen);
  ScreenOrientation* orientation = screen->Orientation();
  MOZ_ASSERT(orientation);

  rv = target->RemoveSystemEventListener(NS_LITERAL_STRING("visibilitychange"),
                                         this, true);
  if (NS_WARN_IF(rv.Failed())) {
    return rv.StealNSResult();
  }

  if (doc->CurrentOrientationType() != orientation->DeviceType()) {
    doc->SetCurrentOrientation(orientation->DeviceType(), orientation->DeviceAngle());

    Promise* pendingPromise = doc->GetOrientationPendingPromise();
    if (pendingPromise) {
      pendingPromise->MaybeResolveWithUndefined();
      doc->SetOrientationPendingPromise(nullptr);
    }

    nsCOMPtr<nsIRunnable> runnable = NewRunnableMethod(orientation,
      &ScreenOrientation::DispatchChangeEvent);
    rv = NS_DispatchToMainThread(runnable);
    if (NS_WARN_IF(rv.Failed())) {
      return rv.StealNSResult();
    }
  }

  return NS_OK;
}

NS_IMPL_ISUPPORTS(ScreenOrientation::FullScreenEventListener, nsIDOMEventListener)

NS_IMETHODIMP
ScreenOrientation::FullScreenEventListener::HandleEvent(nsIDOMEvent* aEvent)
{
#ifdef DEBUG
  nsAutoString eventType;
  aEvent->GetType(eventType);

  MOZ_ASSERT(eventType.EqualsLiteral("fullscreenchange"));
#endif

  nsCOMPtr<EventTarget> target = aEvent->InternalDOMEvent()->GetCurrentTarget();
  MOZ_ASSERT(target);

  nsCOMPtr<nsIDocument> doc = do_QueryInterface(target);
  MOZ_ASSERT(doc);

  // We have to make sure that the event we got is the event sent when
  // fullscreen is disabled because we could get one when fullscreen
  // got enabled if the lock call is done at the same moment.
  if (doc->Fullscreen()) {
    return NS_OK;
  }

  hal::UnlockScreenOrientation();

  nsresult rv = target->RemoveSystemEventListener(NS_LITERAL_STRING("fullscreenchange"),
                                                  this, true);
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_OK;
}