File: Fullscreen.cpp

package info (click to toggle)
chromium-browser 57.0.2987.98-1~deb8u1
  • links: PTS, VCS
  • area: main
  • in suites: jessie
  • size: 2,637,852 kB
  • ctags: 2,544,394
  • sloc: cpp: 12,815,961; ansic: 3,676,222; python: 1,147,112; asm: 526,608; java: 523,212; xml: 286,794; perl: 92,654; sh: 86,408; objc: 73,271; makefile: 27,698; cs: 18,487; yacc: 13,031; tcl: 12,957; pascal: 4,875; ml: 4,716; lex: 3,904; sql: 3,862; ruby: 1,982; lisp: 1,508; php: 1,368; exp: 404; awk: 325; csh: 117; jsp: 39; sed: 37
file content (872 lines) | stat: -rw-r--r-- 33,121 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
/*
 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
 *           (C) 1999 Antti Koivisto (koivisto@kde.org)
 *           (C) 2001 Dirk Mueller (mueller@kde.org)
 *           (C) 2006 Alexey Proskuryakov (ap@webkit.org)
 * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2012 Apple Inc. All
 * rights reserved.
 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved.
 * (http://www.torchmobile.com/)
 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
 * Copyright (C) 2013 Google Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 *
 */

#include "core/dom/Fullscreen.h"

#include "bindings/core/v8/ConditionalFeatures.h"
#include "core/dom/Document.h"
#include "core/dom/ElementTraversal.h"
#include "core/dom/StyleEngine.h"
#include "core/dom/TaskRunnerHelper.h"
#include "core/events/Event.h"
#include "core/frame/FrameView.h"
#include "core/frame/HostsUsingFeatures.h"
#include "core/frame/LocalFrame.h"
#include "core/frame/Settings.h"
#include "core/frame/UseCounter.h"
#include "core/html/HTMLIFrameElement.h"
#include "core/input/EventHandler.h"
#include "core/inspector/ConsoleMessage.h"
#include "core/layout/LayoutBlockFlow.h"
#include "core/layout/LayoutFullScreen.h"
#include "core/layout/api/LayoutFullScreenItem.h"
#include "core/page/ChromeClient.h"
#include "core/svg/SVGSVGElement.h"
#include "platform/ScopedOrientationChangeIndicator.h"
#include "platform/UserGestureIndicator.h"

namespace blink {

namespace {

// https://html.spec.whatwg.org/multipage/embedded-content.html#allowed-to-use
bool allowedToUseFullscreen(const Frame* frame) {
  // To determine whether a Document object |document| is allowed to use the
  // feature indicated by attribute name |allowattribute|, run these steps:

  // 1. If |document| has no browsing context, then return false.
  if (!frame)
    return false;

  if (!RuntimeEnabledFeatures::featurePolicyEnabled()) {
    // 2. If |document|'s browsing context is a top-level browsing context, then
    // return true.
    if (frame->isMainFrame())
      return true;

    // 3. If |document|'s browsing context has a browsing context container that
    // is an iframe element with an |allowattribute| attribute specified, and
    // whose node document is allowed to use the feature indicated by
    // |allowattribute|, then return true.
    if (frame->owner() && frame->owner()->allowFullscreen())
      return allowedToUseFullscreen(frame->tree().parent());

    // 4. Return false.
    return false;
  }

  // If Feature Policy is enabled, then we need this hack to support it, until
  // we have proper support for <iframe allowfullscreen> in FP:

  // 1. If FP, by itself, enables fullscreen in this document, then fullscreen
  // is allowed.
  if (frame->securityContext()->getFeaturePolicy()->isFeatureEnabled(
          kFullscreenFeature)) {
    return true;
  }

  // 2. Otherwise, if the embedding frame's document is allowed to use
  // fullscreen (either through FP or otherwise), and either:
  //   a) this is a same-origin embedded document, or
  //   b) this document's iframe has the allowfullscreen attribute set,
  // then fullscreen is allowed.
  if (!frame->isMainFrame()) {
    if (allowedToUseFullscreen(frame->tree().parent())) {
      return (frame->owner() && frame->owner()->allowFullscreen()) ||
             frame->tree()
                 .parent()
                 ->securityContext()
                 ->getSecurityOrigin()
                 ->isSameSchemeHostPortAndSuborigin(
                     frame->securityContext()->getSecurityOrigin());
    }
  }

  // Otherwise, fullscreen is not allowed. (If we reach here and this is the
  // main frame, then fullscreen must have been disabled by FP.)
  return false;
}

bool allowedToRequestFullscreen(Document& document) {
  // An algorithm is allowed to request fullscreen if one of the following is
  // true:

  //  The algorithm is triggered by a user activation.
  if (UserGestureIndicator::utilizeUserGesture())
    return true;

  //  The algorithm is triggered by a user generated orientation change.
  if (ScopedOrientationChangeIndicator::processingOrientationChange()) {
    UseCounter::count(document,
                      UseCounter::FullscreenAllowedByOrientationChange);
    return true;
  }

  String message = ExceptionMessages::failedToExecute(
      "requestFullscreen", "Element",
      "API can only be initiated by a user gesture.");
  document.addConsoleMessage(
      ConsoleMessage::create(JSMessageSource, WarningMessageLevel, message));

  return false;
}

// https://fullscreen.spec.whatwg.org/#fullscreen-is-supported
bool fullscreenIsSupported(const Document& document) {
  LocalFrame* frame = document.frame();
  if (!frame)
    return false;

  // Fullscreen is supported if there is no previously-established user
  // preference, security risk, or platform limitation.
  return !document.settings() || document.settings()->getFullscreenSupported();
}

// https://fullscreen.spec.whatwg.org/#fullscreen-element-ready-check
bool fullscreenElementReady(const Element& element) {
  // A fullscreen element ready check for an element |element| returns true if
  // all of the following are true, and false otherwise:

  // |element| is in a document.
  if (!element.isConnected())
    return false;

  // |element|'s node document is allowed to use the feature indicated by
  // attribute name allowfullscreen.
  if (!allowedToUseFullscreen(element.document().frame()))
    return false;

  // |element|'s node document's fullscreen element stack is either empty or its
  // top element is an inclusive ancestor of |element|.
  if (const Element* topElement =
          Fullscreen::fullscreenElementFrom(element.document())) {
    if (!topElement->contains(&element))
      return false;
  }

  // |element| has no ancestor element whose local name is iframe and namespace
  // is the HTML namespace.
  if (Traversal<HTMLIFrameElement>::firstAncestor(element))
    return false;

  // |element|'s node document's browsing context either has a browsing context
  // container and the fullscreen element ready check returns true for
  // |element|'s node document's browsing context's browsing context container,
  // or it has no browsing context container.
  if (const Element* owner = element.document().localOwner()) {
    if (!fullscreenElementReady(*owner))
      return false;
  }

  return true;
}

bool isPrefixed(const AtomicString& type) {
  return type == EventTypeNames::webkitfullscreenchange ||
         type == EventTypeNames::webkitfullscreenerror;
}

Event* createEvent(const AtomicString& type, EventTarget& target) {
  EventInit initializer;
  initializer.setBubbles(isPrefixed(type));
  Event* event = Event::create(type, initializer);
  event->setTarget(&target);
  return event;
}

// Walks the frame tree and returns the first local ancestor frame, if any.
LocalFrame* nextLocalAncestor(Frame& frame) {
  Frame* parent = frame.tree().parent();
  if (!parent)
    return nullptr;
  if (parent->isLocalFrame())
    return toLocalFrame(parent);
  return nextLocalAncestor(*parent);
}

// Walks the document's frame tree and returns the document of the first local
// ancestor frame, if any.
Document* nextLocalAncestor(Document& document) {
  LocalFrame* frame = document.frame();
  if (!frame)
    return nullptr;
  LocalFrame* next = nextLocalAncestor(*document.frame());
  if (!next)
    return nullptr;
  DCHECK(next->document());
  return next->document();
}

// Helper to walk the ancestor chain and return the Document of the topmost
// local ancestor frame. Note that this is not the same as the topmost frame's
// Document, which might be unavailable in OOPIF scenarios. For example, with
// OOPIFs, when called on the bottom frame's Document in a A-B-C-B hierarchy in
// process B, this will skip remote frame C and return this frame: A-[B]-C-B.
Document& topmostLocalAncestor(Document& document) {
  if (Document* next = nextLocalAncestor(document))
    return topmostLocalAncestor(*next);
  return document;
}

// Helper to find the browsing context container in |doc| that embeds the
// |descendant| Document, possibly through multiple levels of nesting.  This
// works even in OOPIF scenarios like A-B-A, where there may be remote frames
// in between |doc| and |descendant|.
HTMLFrameOwnerElement* findContainerForDescendant(const Document& doc,
                                                  const Document& descendant) {
  Frame* frame = descendant.frame();
  while (frame->tree().parent() != doc.frame())
    frame = frame->tree().parent();
  return toHTMLFrameOwnerElement(frame->owner());
}

// Fullscreen status affects scroll paint properties through
// FrameView::userInputScrollable().
void setNeedsPaintPropertyUpdate(Document* document) {
  if (!RuntimeEnabledFeatures::slimmingPaintInvalidationEnabled() ||
      RuntimeEnabledFeatures::rootLayerScrollingEnabled())
    return;

  if (!document)
    return;

  LocalFrame* frame = document->frame();
  if (!frame)
    return;

  if (FrameView* frameView = frame->view())
    frameView->setNeedsPaintPropertyUpdate();
}

}  // anonymous namespace

const char* Fullscreen::supplementName() {
  return "Fullscreen";
}

Fullscreen& Fullscreen::from(Document& document) {
  Fullscreen* fullscreen = fromIfExists(document);
  if (!fullscreen) {
    fullscreen = new Fullscreen(document);
    Supplement<Document>::provideTo(document, supplementName(), fullscreen);
  }

  return *fullscreen;
}

Fullscreen* Fullscreen::fromIfExistsSlow(Document& document) {
  return static_cast<Fullscreen*>(
      Supplement<Document>::from(document, supplementName()));
}

Element* Fullscreen::fullscreenElementFrom(Document& document) {
  if (Fullscreen* found = fromIfExists(document))
    return found->fullscreenElement();
  return nullptr;
}

Element* Fullscreen::fullscreenElementForBindingFrom(TreeScope& scope) {
  Element* element = fullscreenElementFrom(scope.document());
  if (!element || !RuntimeEnabledFeatures::fullscreenUnprefixedEnabled())
    return element;

  // TODO(kochi): Once V0 code is removed, we can use the same logic for
  // Document and ShadowRoot.
  if (!scope.rootNode().isShadowRoot()) {
    // For Shadow DOM V0 compatibility: We allow returning an element in V0
    // shadow tree, even though it leaks the Shadow DOM.
    if (element->isInV0ShadowTree()) {
      UseCounter::count(scope.document(),
                        UseCounter::DocumentFullscreenElementInV0Shadow);
      return element;
    }
  } else if (!toShadowRoot(scope.rootNode()).isV1()) {
    return nullptr;
  }
  return scope.adjustedElement(*element);
}

Element* Fullscreen::currentFullScreenElementFrom(Document& document) {
  if (Fullscreen* found = fromIfExists(document))
    return found->currentFullScreenElement();
  return nullptr;
}

Element* Fullscreen::currentFullScreenElementForBindingFrom(
    Document& document) {
  Element* element = currentFullScreenElementFrom(document);
  if (!element || !RuntimeEnabledFeatures::fullscreenUnprefixedEnabled())
    return element;

  // For Shadow DOM V0 compatibility: We allow returning an element in V0 shadow
  // tree, even though it leaks the Shadow DOM.
  if (element->isInV0ShadowTree()) {
    UseCounter::count(document,
                      UseCounter::DocumentFullscreenElementInV0Shadow);
    return element;
  }
  return document.adjustedElement(*element);
}

Fullscreen::Fullscreen(Document& document)
    : Supplement<Document>(document),
      ContextLifecycleObserver(&document),
      m_fullScreenLayoutObject(nullptr),
      m_eventQueueTimer(TaskRunnerHelper::get(TaskType::Unthrottled, &document),
                        this,
                        &Fullscreen::eventQueueTimerFired),
      m_forCrossProcessDescendant(false) {
  document.setHasFullscreenSupplement();
}

Fullscreen::~Fullscreen() {}

inline Document* Fullscreen::document() {
  return toDocument(lifecycleContext());
}

void Fullscreen::contextDestroyed(ExecutionContext*) {
  m_eventQueue.clear();

  if (m_fullScreenLayoutObject)
    m_fullScreenLayoutObject->destroy();

  m_currentFullScreenElement = nullptr;
  m_fullscreenElementStack.clear();
}

// https://fullscreen.spec.whatwg.org/#dom-element-requestfullscreen
void Fullscreen::requestFullscreen(Element& element) {
  // TODO(foolip): Make RequestType::Unprefixed the default when the unprefixed
  // API is enabled. https://crbug.com/383813
  requestFullscreen(element, RequestType::Prefixed, false);
}

void Fullscreen::requestFullscreen(Element& element,
                                   RequestType requestType,
                                   bool forCrossProcessDescendant) {
  Document& document = element.document();

  // Use counters only need to be incremented in the process of the actual
  // fullscreen element.
  if (!forCrossProcessDescendant) {
    if (document.isSecureContext()) {
      UseCounter::count(document, UseCounter::FullscreenSecureOrigin);
    } else {
      UseCounter::count(document, UseCounter::FullscreenInsecureOrigin);
      HostsUsingFeatures::countAnyWorld(
          document, HostsUsingFeatures::Feature::FullscreenInsecureHost);
    }
  }

  // Ignore this call if the document is not in a live frame.
  if (!document.isActive() || !document.frame())
    return;

  // If |element| is on top of |doc|'s fullscreen element stack, terminate these
  // substeps.
  if (&element == fullscreenElementFrom(document))
    return;

  do {
    // 1. If any of the following conditions are false, then terminate these
    // steps and queue a task to fire an event named fullscreenerror with its
    // bubbles attribute set to true on the context object's node document:

    // |element|'s namespace is the HTML namespace or |element| is an SVG
    // svg or MathML math element.
    // Note: MathML is not supported.
    if (!element.isHTMLElement() && !isSVGSVGElement(element))
      break;

    // The fullscreen element ready check for |element| returns true.
    if (!fullscreenElementReady(element))
      break;

    // Fullscreen is supported.
    if (!fullscreenIsSupported(document))
      break;

    // This algorithm is allowed to request fullscreen.
    // OOPIF: If |forCrossProcessDescendant| is true, requestFullscreen was
    // already called on a descendant element in another process, and
    // getting here means that it was already allowed to request fullscreen.
    if (!forCrossProcessDescendant && !allowedToRequestFullscreen(document))
      break;

    // 2. Let doc be element's node document. (i.e. "this")

    // 3. Let docs be all doc's ancestor browsing context's documents (if any)
    // and doc.
    //
    // For OOPIF scenarios, |docs| will only contain documents for local
    // ancestors, and remote ancestors will be processed in their
    // respective processes.  This preserves the spec's event firing order
    // for local ancestors, but not for remote ancestors.  However, that
    // difference shouldn't be observable in practice: a fullscreenchange
    // event handler would need to postMessage a frame in another renderer
    // process, where the message should be queued up and processed after
    // the IPC that dispatches fullscreenchange.
    HeapDeque<Member<Document>> docs;
    for (Document* doc = &document; doc; doc = nextLocalAncestor(*doc))
      docs.prepend(doc);

    // 4. For each document in docs, run these substeps:
    HeapDeque<Member<Document>>::iterator current = docs.begin(),
                                          following = docs.begin();

    do {
      ++following;

      // 1. Let following document be the document after document in docs, or
      // null if there is no such document.
      Document* currentDoc = *current;
      Document* followingDoc = following != docs.end() ? *following : nullptr;

      // 2. If following document is null, push context object on document's
      // fullscreen element stack, and queue a task to fire an event named
      // fullscreenchange with its bubbles attribute set to true on the
      // document.
      if (!followingDoc) {
        from(*currentDoc).pushFullscreenElementStack(element, requestType);
        from(document).enqueueChangeEvent(*currentDoc, requestType);
        continue;
      }

      // 3. Otherwise, if document's fullscreen element stack is either empty or
      // its top element is not following document's browsing context container,
      Element* topElement = fullscreenElementFrom(*currentDoc);
      HTMLFrameOwnerElement* followingOwner =
          findContainerForDescendant(*currentDoc, *followingDoc);
      if (!topElement || topElement != followingOwner) {
        // ...push following document's browsing context container on document's
        // fullscreen element stack, and queue a task to fire an event named
        // fullscreenchange with its bubbles attribute set to true on document.
        from(*currentDoc)
            .pushFullscreenElementStack(*followingOwner, requestType);
        from(document).enqueueChangeEvent(*currentDoc, requestType);
        continue;
      }

      // 4. Otherwise, do nothing for this document. It stays the same.
    } while (++current != docs.end());

    from(document).m_forCrossProcessDescendant = forCrossProcessDescendant;

    // 5. Return, and run the remaining steps asynchronously.
    // 6. Optionally, perform some animation.
    from(document).m_pendingFullscreenElement = &element;
    document.frame()->chromeClient().enterFullscreen(*document.frame());

    // 7. Optionally, display a message indicating how the user can exit
    // displaying the context object fullscreen.
    return;
  } while (false);

  from(document).enqueueErrorEvent(element, requestType);
}

// https://fullscreen.spec.whatwg.org/#fully-exit-fullscreen
void Fullscreen::fullyExitFullscreen(Document& document) {
  // To fully exit fullscreen, run these steps:

  // 1. Let |doc| be the top-level browsing context's document.
  //
  // Since the top-level browsing context's document might be unavailable in
  // OOPIF scenarios (i.e., when the top frame is remote), this actually uses
  // the Document of the topmost local ancestor frame.  Without OOPIF, this
  // will be the top frame's document.  With OOPIF, each renderer process for
  // the current page will separately call fullyExitFullscreen to cover all
  // local frames in each process.
  Document& doc = topmostLocalAncestor(document);

  // 2. If |doc|'s fullscreen element stack is empty, terminate these steps.
  if (!fullscreenElementFrom(doc))
    return;

  // 3. Remove elements from |doc|'s fullscreen element stack until only the top
  // element is left.
  size_t stackSize = from(doc).m_fullscreenElementStack.size();
  from(doc).m_fullscreenElementStack.remove(0, stackSize - 1);
  DCHECK_EQ(from(doc).m_fullscreenElementStack.size(), 1u);

  // 4. Act as if the exitFullscreen() method was invoked on |doc|.
  exitFullscreen(doc);
}

// https://fullscreen.spec.whatwg.org/#exit-fullscreen
void Fullscreen::exitFullscreen(Document& document) {
  // The exitFullscreen() method must run these steps:

  // Ignore this call if the document is not in a live frame.
  if (!document.isActive() || !document.frame())
    return;

  // 1. Let doc be the context object. (i.e. "this")
  // 2. If doc's fullscreen element stack is empty, terminate these steps.
  if (!fullscreenElementFrom(document))
    return;

  // 3. Let descendants be all the doc's descendant browsing context's documents
  // with a non-empty fullscreen element stack (if any), ordered so that the
  // child of the doc is last and the document furthest away from the doc is
  // first.
  HeapDeque<Member<Document>> descendants;
  for (Frame* descendant = document.frame()->tree().traverseNext(); descendant;
       descendant = descendant->tree().traverseNext()) {
    if (!descendant->isLocalFrame())
      continue;
    DCHECK(toLocalFrame(descendant)->document());
    if (fullscreenElementFrom(*toLocalFrame(descendant)->document()))
      descendants.prepend(toLocalFrame(descendant)->document());
  }

  // 4. For each descendant in descendants, empty descendant's fullscreen
  // element stack, and queue a task to fire an event named fullscreenchange
  // with its bubbles attribute set to true on descendant.
  for (auto& descendant : descendants) {
    DCHECK(descendant);
    RequestType requestType =
        from(*descendant).m_fullscreenElementStack.back().second;
    from(*descendant).clearFullscreenElementStack();
    from(document).enqueueChangeEvent(*descendant, requestType);
  }

  // 5. While doc is not null, run these substeps:
  Element* newTop = nullptr;
  for (Document* currentDoc = &document; currentDoc;) {
    RequestType requestType =
        from(*currentDoc).m_fullscreenElementStack.back().second;

    // 1. Pop the top element of doc's fullscreen element stack.
    from(*currentDoc).popFullscreenElementStack();

    //    If doc's fullscreen element stack is non-empty and the element now at
    //    the top is either not in a document or its node document is not doc,
    //    repeat this substep.
    newTop = fullscreenElementFrom(*currentDoc);
    if (newTop && (!newTop->isConnected() || newTop->document() != currentDoc))
      continue;

    // 2. Queue a task to fire an event named fullscreenchange with its bubbles
    // attribute set to true on doc.
    from(document).enqueueChangeEvent(*currentDoc, requestType);

    // 3. If doc's fullscreen element stack is empty and doc's browsing context
    // has a browsing context container, set doc to that browsing context
    // container's node document.
    //
    // OOPIF: If browsing context container's document is in another
    // process, keep moving up the ancestor chain and looking for a
    // browsing context container with a local document.
    // TODO(alexmos): Deal with nested fullscreen cases, see
    // https://crbug.com/617369.
    if (!newTop) {
      currentDoc = nextLocalAncestor(*currentDoc);
      continue;
    }

    // 4. Otherwise, set doc to null.
    currentDoc = nullptr;
  }

  // 6. Return, and run the remaining steps asynchronously.
  // 7. Optionally, perform some animation.

  // Only exit fullscreen mode if the fullscreen element stack is empty.
  if (!newTop) {
    document.frame()->chromeClient().exitFullscreen(*document.frame());
    return;
  }

  // Otherwise, enter fullscreen for the fullscreen element stack's top element.
  from(document).m_pendingFullscreenElement = newTop;
  from(document).didEnterFullscreen();
}

// https://fullscreen.spec.whatwg.org/#dom-document-fullscreenenabled
bool Fullscreen::fullscreenEnabled(Document& document) {
  // The fullscreenEnabled attribute's getter must return true if the context
  // object is allowed to use the feature indicated by attribute name
  // allowfullscreen and fullscreen is supported, and false otherwise.
  return allowedToUseFullscreen(document.frame()) &&
         fullscreenIsSupported(document);
}

void Fullscreen::didEnterFullscreen() {
  if (!document()->isActive() || !document()->frame())
    return;

  // Start the timer for events enqueued by |requestFullscreen()|. The hover
  // state update is scheduled first so that it's done when the events fire.
  document()->frame()->eventHandler().scheduleHoverStateUpdate();
  m_eventQueueTimer.startOneShot(0, BLINK_FROM_HERE);

  Element* element = m_pendingFullscreenElement.release();
  if (!element)
    return;

  if (m_currentFullScreenElement == element)
    return;

  if (!element->isConnected() || &element->document() != document()) {
    // The element was removed or has moved to another document since the
    // |requestFullscreen()| call. Exit fullscreen again to recover.
    // TODO(foolip): Fire a fullscreenerror event. This is currently difficult
    // because the fullscreenchange event has already been enqueued and possibly
    // even fired. https://crbug.com/402376
    LocalFrame& frame = *document()->frame();
    frame.chromeClient().exitFullscreen(frame);
    return;
  }

  if (m_fullScreenLayoutObject)
    m_fullScreenLayoutObject->unwrapLayoutObject();

  Element* previousElement = m_currentFullScreenElement;
  m_currentFullScreenElement = element;

  // Create a placeholder block for a the full-screen element, to keep the page
  // from reflowing when the element is removed from the normal flow. Only do
  // this for a LayoutBox, as only a box will have a frameRect. The placeholder
  // will be created in setFullScreenLayoutObject() during layout.
  LayoutObject* layoutObject = m_currentFullScreenElement->layoutObject();
  bool shouldCreatePlaceholder = layoutObject && layoutObject->isBox();
  if (shouldCreatePlaceholder) {
    m_savedPlaceholderFrameRect = toLayoutBox(layoutObject)->frameRect();
    m_savedPlaceholderComputedStyle =
        ComputedStyle::clone(layoutObject->styleRef());
  }

  // TODO(alexmos): When |m_forCrossProcessDescendant| is true, some of
  // this layout work has already been done in another process, so it should
  // not be necessary to repeat it here.
  if (m_currentFullScreenElement != document()->documentElement()) {
    LayoutFullScreen::wrapLayoutObject(
        layoutObject, layoutObject ? layoutObject->parent() : 0, document());
  }

  // When |m_forCrossProcessDescendant| is true, m_currentFullScreenElement
  // corresponds to the HTMLFrameOwnerElement for the out-of-process iframe
  // that contains the actual fullscreen element.   Hence, it must also set
  // the ContainsFullScreenElement flag (so that it gains the
  // -webkit-full-screen-ancestor style).
  if (m_forCrossProcessDescendant) {
    DCHECK(m_currentFullScreenElement->isFrameOwnerElement());
    DCHECK(toHTMLFrameOwnerElement(m_currentFullScreenElement)
               ->contentFrame()
               ->isRemoteFrame());
    m_currentFullScreenElement->setContainsFullScreenElement(true);
  }

  m_currentFullScreenElement
      ->setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(true);

  document()->styleEngine().ensureUAStyleForFullscreen();
  m_currentFullScreenElement->pseudoStateChanged(CSSSelector::PseudoFullScreen);

  // FIXME: This should not call updateStyleAndLayoutTree.
  document()->updateStyleAndLayoutTree();

  document()->frame()->chromeClient().fullscreenElementChanged(previousElement,
                                                               element);
}

void Fullscreen::didExitFullscreen() {
  if (!document()->isActive() || !document()->frame())
    return;

  // Start the timer for events enqueued by |exitFullscreen()|. The hover state
  // update is scheduled first so that it's done when the events fire.
  document()->frame()->eventHandler().scheduleHoverStateUpdate();
  m_eventQueueTimer.startOneShot(0, BLINK_FROM_HERE);

  // If fullscreen was canceled by the browser, e.g. if the user pressed Esc,
  // then |exitFullscreen()| was never called. Let |fullyExitFullscreen()| clear
  // the fullscreen element stack and fire any events as necessary.
  // TODO(foolip): Remove this when state changes and events are synchronized
  // with animation frames. https://crbug.com/402376
  fullyExitFullscreen(*document());

  if (!m_currentFullScreenElement)
    return;

  if (m_forCrossProcessDescendant)
    m_currentFullScreenElement->setContainsFullScreenElement(false);

  m_currentFullScreenElement
      ->setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);

  if (m_fullScreenLayoutObject)
    LayoutFullScreenItem(m_fullScreenLayoutObject).unwrapLayoutObject();

  document()->styleEngine().ensureUAStyleForFullscreen();
  m_currentFullScreenElement->pseudoStateChanged(CSSSelector::PseudoFullScreen);
  Element* previousElement = m_currentFullScreenElement;
  m_currentFullScreenElement = nullptr;

  m_forCrossProcessDescendant = false;

  document()->frame()->chromeClient().fullscreenElementChanged(previousElement,
                                                               nullptr);
}

void Fullscreen::setFullScreenLayoutObject(LayoutFullScreen* layoutObject) {
  if (layoutObject == m_fullScreenLayoutObject)
    return;

  if (layoutObject && m_savedPlaceholderComputedStyle) {
    layoutObject->createPlaceholder(std::move(m_savedPlaceholderComputedStyle),
                                    m_savedPlaceholderFrameRect);
  } else if (layoutObject && m_fullScreenLayoutObject &&
             m_fullScreenLayoutObject->placeholder()) {
    LayoutBlockFlow* placeholder = m_fullScreenLayoutObject->placeholder();
    layoutObject->createPlaceholder(
        ComputedStyle::clone(placeholder->styleRef()),
        placeholder->frameRect());
  }

  if (m_fullScreenLayoutObject)
    m_fullScreenLayoutObject->unwrapLayoutObject();
  DCHECK(!m_fullScreenLayoutObject);

  m_fullScreenLayoutObject = layoutObject;
}

void Fullscreen::fullScreenLayoutObjectDestroyed() {
  m_fullScreenLayoutObject = nullptr;
}

void Fullscreen::enqueueChangeEvent(Document& document,
                                    RequestType requestType) {
  Event* event;
  if (requestType == RequestType::Unprefixed) {
    event = createEvent(EventTypeNames::fullscreenchange, document);
  } else {
    DCHECK(document.hasFullscreenSupplement());
    Fullscreen& fullscreen = from(document);
    EventTarget* target = fullscreen.fullscreenElement();
    if (!target)
      target = fullscreen.currentFullScreenElement();
    if (!target)
      target = &document;
    event = createEvent(EventTypeNames::webkitfullscreenchange, *target);
  }
  m_eventQueue.append(event);
  // NOTE: The timer is started in didEnterFullscreen/didExitFullscreen.
}

void Fullscreen::enqueueErrorEvent(Element& element, RequestType requestType) {
  Event* event;
  if (requestType == RequestType::Unprefixed)
    event = createEvent(EventTypeNames::fullscreenerror, element.document());
  else
    event = createEvent(EventTypeNames::webkitfullscreenerror, element);
  m_eventQueue.append(event);
  m_eventQueueTimer.startOneShot(0, BLINK_FROM_HERE);
}

void Fullscreen::eventQueueTimerFired(TimerBase*) {
  HeapDeque<Member<Event>> eventQueue;
  m_eventQueue.swap(eventQueue);

  while (!eventQueue.isEmpty()) {
    Event* event = eventQueue.takeFirst();
    Node* target = event->target()->toNode();

    // If the element was removed from our tree, also message the
    // documentElement.
    if (!target->isConnected() && document()->documentElement()) {
      DCHECK(isPrefixed(event->type()));
      eventQueue.append(
          createEvent(event->type(), *document()->documentElement()));
    }

    target->dispatchEvent(event);
  }
}

void Fullscreen::elementRemoved(Element& oldNode) {
  // Whenever the removing steps run with an |oldNode| and |oldNode| is in its
  // node document's fullscreen element stack, run these steps:

  // 1. If |oldNode| is at the top of its node document's fullscreen element
  // stack, act as if the exitFullscreen() method was invoked on that document.
  if (fullscreenElement() == &oldNode) {
    exitFullscreen(oldNode.document());
    return;
  }

  // 2. Otherwise, remove |oldNode| from its node document's fullscreen element
  // stack.
  for (size_t i = 0; i < m_fullscreenElementStack.size(); ++i) {
    if (m_fullscreenElementStack[i].first.get() == &oldNode) {
      m_fullscreenElementStack.remove(i);
      return;
    }
  }

  // NOTE: |oldNode| was not in the fullscreen element stack.
}

void Fullscreen::clearFullscreenElementStack() {
  if (m_fullscreenElementStack.isEmpty())
    return;

  m_fullscreenElementStack.clear();

  setNeedsPaintPropertyUpdate(document());
}

void Fullscreen::popFullscreenElementStack() {
  if (m_fullscreenElementStack.isEmpty())
    return;

  m_fullscreenElementStack.pop_back();

  setNeedsPaintPropertyUpdate(document());
}

void Fullscreen::pushFullscreenElementStack(Element& element,
                                            RequestType requestType) {
  m_fullscreenElementStack.push_back(std::make_pair(&element, requestType));

  setNeedsPaintPropertyUpdate(document());
}

DEFINE_TRACE(Fullscreen) {
  visitor->trace(m_pendingFullscreenElement);
  visitor->trace(m_fullscreenElementStack);
  visitor->trace(m_currentFullScreenElement);
  visitor->trace(m_eventQueue);
  Supplement<Document>::trace(visitor);
  ContextLifecycleObserver::trace(visitor);
}

}  // namespace blink