File: WebFullScreenManager.cpp

package info (click to toggle)
webkit2gtk 2.48.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 429,764 kB
  • sloc: cpp: 3,697,587; javascript: 194,444; ansic: 169,997; python: 46,499; asm: 19,295; ruby: 18,528; perl: 16,602; xml: 4,650; yacc: 2,360; sh: 2,098; java: 1,993; lex: 1,327; pascal: 366; makefile: 298
file content (756 lines) | stat: -rw-r--r-- 25,970 bytes parent folder | download | duplicates (7)
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
/*
 * Copyright (C) 2011 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "WebFullScreenManager.h"

#if ENABLE(FULLSCREEN_API)

#include "Connection.h"
#include "FullScreenMediaDetails.h"
#include "Logging.h"
#include "MessageSenderInlines.h"
#include "WebFrame.h"
#include "WebFullScreenManagerProxyMessages.h"
#include "WebPage.h"
#include <WebCore/AddEventListenerOptions.h>
#include <WebCore/Color.h>
#include <WebCore/EventNames.h>
#include <WebCore/FullscreenManager.h>
#include <WebCore/HTMLVideoElement.h>
#include <WebCore/JSDOMPromiseDeferred.h>
#include <WebCore/LocalFrame.h>
#include <WebCore/LocalFrameView.h>
#include <WebCore/MIMETypeRegistry.h>
#include <WebCore/Quirks.h>
#include <WebCore/RenderImage.h>
#include <WebCore/RenderLayerBacking.h>
#include <WebCore/RenderView.h>
#include <WebCore/Settings.h>
#include <WebCore/TypedElementDescendantIteratorInlines.h>
#include <WebCore/UserGestureIndicator.h>
#include <wtf/LoggerHelper.h>

#if PLATFORM(IOS_FAMILY) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE))
#include "PlaybackSessionManager.h"
#include "VideoPresentationManager.h"
#endif

namespace WebKit {
using namespace WebCore;

using WebCore::FloatSize;

static WebCore::IntRect screenRectOfContents(WebCore::Element* element)
{
    ASSERT(element);
    if (!element)
        return { };

    if (element->renderer() && element->renderer()->hasLayer() && element->renderer()->enclosingLayer()->isComposited()) {
        WebCore::FloatQuad contentsBox = static_cast<WebCore::FloatRect>(element->renderer()->enclosingLayer()->backing()->compositedBounds());
        contentsBox = element->renderer()->localToAbsoluteQuad(contentsBox);
        return element->renderer()->view().frameView().contentsToScreen(contentsBox.enclosingBoundingBox());
    }

    return element->screenRect();
}

Ref<WebFullScreenManager> WebFullScreenManager::create(WebPage& page)
{
    return adoptRef(*new WebFullScreenManager(page));
}

WebFullScreenManager::WebFullScreenManager(WebPage& page)
    : WebCore::EventListener(WebCore::EventListener::CPPEventListenerType)
    , m_page(page)
#if ENABLE(VIDEO) && ENABLE(IMAGE_ANALYSIS)
    , m_mainVideoElementTextRecognitionTimer(RunLoop::main(), this, &WebFullScreenManager::mainVideoElementTextRecognitionTimerFired)
#endif
#if !RELEASE_LOG_DISABLED
    , m_logger(page.logger())
    , m_logIdentifier(page.logIdentifier())
#endif
{
}
    
WebFullScreenManager::~WebFullScreenManager()
{
    invalidate();
}

void WebFullScreenManager::invalidate()
{
    ALWAYS_LOG(LOGIDENTIFIER);
    clearElement();
#if ENABLE(VIDEO)
    setMainVideoElement(nullptr);
#if ENABLE(IMAGE_ANALYSIS)
    m_mainVideoElementTextRecognitionTimer.stop();
#endif
#endif
}

WebCore::Element* WebFullScreenManager::element()
{ 
    return m_element.get(); 
}

void WebFullScreenManager::videoControlsManagerDidChange()
{
#if PLATFORM(IOS_FAMILY) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE))
    ALWAYS_LOG(LOGIDENTIFIER);

    if (!m_element) {
        setPIPStandbyElement(nullptr);
        return;
    }

    RefPtr currentPlaybackControlsElement = dynamicDowncast<WebCore::HTMLVideoElement>(m_page->playbackSessionManager().currentPlaybackControlsElement());
    if (!currentPlaybackControlsElement) {
        setPIPStandbyElement(nullptr);
        return;
    }

    setPIPStandbyElement(currentPlaybackControlsElement.get());
#endif
}

void WebFullScreenManager::setPIPStandbyElement(WebCore::HTMLVideoElement* pipStandbyElement)
{
#if ENABLE(VIDEO)
    if (pipStandbyElement == m_pipStandbyElement)
        return;

#if !RELEASE_LOG_DISABLED
    auto logIdentifierForElement = [] (auto* element) { return element ? element->logIdentifier() : 0; };
#endif
    ALWAYS_LOG(LOGIDENTIFIER, "old element ", logIdentifierForElement(m_pipStandbyElement.get()), ", new element ", logIdentifierForElement(pipStandbyElement));

    if (m_pipStandbyElement)
        m_pipStandbyElement->setVideoFullscreenStandby(false);

    m_pipStandbyElement = pipStandbyElement;

    if (m_pipStandbyElement)
        m_pipStandbyElement->setVideoFullscreenStandby(true);
#endif
}

bool WebFullScreenManager::supportsFullScreenForElement(const WebCore::Element& element, bool withKeyboard)
{
    if (!m_page->corePage()->isFullscreenManagerEnabled())
        return false;

#if PLATFORM(IOS_FAMILY)
    return !withKeyboard;
#else
    return true;
#endif
}

static auto& eventsToObserve()
{
    static NeverDestroyed eventsToObserve = std::array {
        WebCore::eventNames().playEvent,
        WebCore::eventNames().pauseEvent,
        WebCore::eventNames().loadedmetadataEvent,
    };
    return eventsToObserve.get();
}

void WebFullScreenManager::setElement(WebCore::Element& element)
{
    if (m_element == &element)
        return;

    clearElement();

    m_element = &element;
    m_elementToRestore = element;

    for (auto& eventName : eventsToObserve())
        m_element->addEventListener(eventName, *this, { true });
}

void WebFullScreenManager::clearElement()
{
    if (!m_element)
        return;
    for (auto& eventName : eventsToObserve())
        m_element->removeEventListener(eventName, *this, { true });
    m_element = nullptr;
}

#if ENABLE(QUICKLOOK_FULLSCREEN)
FullScreenMediaDetails WebFullScreenManager::getImageMediaDetails(CheckedPtr<RenderImage> renderImage, IsUpdating updating)
{
    if (!renderImage)
        return { };

    auto* cachedImage = renderImage->cachedImage();
    if (!cachedImage || cachedImage->errorOccurred())
        return { };

    RefPtr image = cachedImage->image();
    if (!image)
        return { };
    if (!(image->shouldUseQuickLookForFullscreen() || updating == IsUpdating::Yes))
        return { };

    auto* buffer = cachedImage->resourceBuffer();
    if (!buffer)
        return { };

    auto imageSize = image->size();

    auto mimeType = image->mimeType();
    if (!MIMETypeRegistry::isSupportedImageMIMEType(mimeType))
        mimeType = MIMETypeRegistry::mimeTypeForExtension(image->filenameExtension());
    if (!MIMETypeRegistry::isSupportedImageMIMEType(mimeType))
        mimeType = MIMETypeRegistry::mimeTypeForPath(cachedImage->url().string());
    if (!MIMETypeRegistry::isSupportedImageMIMEType(mimeType))
        return { };

    auto sharedMemoryBuffer = SharedMemory::copyBuffer(*buffer);
    if (!sharedMemoryBuffer)
        return { };

    auto imageResourceHandle = sharedMemoryBuffer->createHandle(SharedMemory::Protection::ReadOnly);

    m_willUseQuickLookForFullscreen = true;

    return {
        FullScreenMediaDetails::Type::Image,
        imageSize,
        mimeType,
        imageResourceHandle
    };
}
#endif // ENABLE(QUICKLOOK_FULLSCREEN)

void WebFullScreenManager::enterFullScreenForElement(Element& element, HTMLMediaElementEnums::VideoFullscreenMode mode, CompletionHandler<void(ExceptionOr<void>)>&& willEnterFullScreenCallback, CompletionHandler<bool(bool)>&& didEnterFullScreenCallback)
{
    ALWAYS_LOG(LOGIDENTIFIER, "<", element.tagName(), " id=\"", element.getIdAttribute(), "\">");

    setElement(element);

    auto frameID = element.document().frame()->frameID();

    FullScreenMediaDetails mediaDetails;
#if PLATFORM(IOS_FAMILY) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE))
    if (m_page->videoPresentationManager().videoElementInPictureInPicture() && m_element->document().quirks().blocksEnteringStandardFullscreenFromPictureInPictureQuirk()) {
        willEnterFullScreenCallback(Exception { ExceptionCode::NotAllowedError });
        didEnterFullScreenCallback(false);
        return;
    }

    if (auto* currentPlaybackControlsElement = m_page->playbackSessionManager().currentPlaybackControlsElement())
        currentPlaybackControlsElement->prepareForVideoFullscreenStandby();
#endif

#if PLATFORM(VISION) && ENABLE(QUICKLOOK_FULLSCREEN)
    if (CheckedPtr renderImage = dynamicDowncast<RenderImage>(element.renderer()))
        mediaDetails = getImageMediaDetails(renderImage, IsUpdating::No);

    if (m_willUseQuickLookForFullscreen)
        m_page->freezeLayerTree(WebPage::LayerTreeFreezeReason::OutOfProcessFullscreen);
#endif

    m_initialFrame = screenRectOfContents(m_element.get());

#if ENABLE(VIDEO)
    updateMainVideoElement();

#if ENABLE(VIDEO_USES_ELEMENT_FULLSCREEN)
    if (m_mainVideoElement) {
        bool fullscreenElementIsVideoElement = is<HTMLVideoElement>(element);

        auto mainVideoElementSize = [&]() -> FloatSize {
#if PLATFORM(VISION)
            if (!fullscreenElementIsVideoElement && element.document().quirks().shouldDisableFullscreenVideoAspectRatioAdaptiveSizing())
                return { };
#endif
            return FloatSize(m_mainVideoElement->videoWidth(), m_mainVideoElement->videoHeight());
        }();

        mediaDetails = {
            fullscreenElementIsVideoElement ? FullScreenMediaDetails::Type::Video : FullScreenMediaDetails::Type::ElementWithVideo,
            mainVideoElementSize
        };
    }
#endif

    m_page->prepareToEnterElementFullScreen();

    if (mode == HTMLMediaElementEnums::VideoFullscreenModeInWindow) {
        willEnterFullScreen(WTFMove(willEnterFullScreenCallback), WTFMove(didEnterFullScreenCallback), mode);
        m_inWindowFullScreenMode = true;
    } else {
        m_page->sendWithAsyncReply(Messages::WebFullScreenManagerProxy::EnterFullScreen(frameID, m_element->document().quirks().blocksReturnToFullscreenFromPictureInPictureQuirk(), WTFMove(mediaDetails)), [
            this,
            protectedThis = Ref { *this },
            willEnterFullScreenCallback = WTFMove(willEnterFullScreenCallback),
            didEnterFullScreenCallback = WTFMove(didEnterFullScreenCallback)
        ] (bool success) mutable {
            if (success) {
                m_scrollPosition = m_page->corePage()->mainFrame().virtualView()->scrollPosition();
                willEnterFullScreen(WTFMove(willEnterFullScreenCallback), WTFMove(didEnterFullScreenCallback));
                return;
            }
            willEnterFullScreenCallback(Exception { ExceptionCode::InvalidStateError });
            didEnterFullScreenCallback(false);
        });
    }
#endif
}

#if ENABLE(QUICKLOOK_FULLSCREEN)
void WebFullScreenManager::updateImageSource(WebCore::Element& element)
{
    FullScreenMediaDetails mediaDetails;
    CheckedPtr renderImage = dynamicDowncast<RenderImage>(element.renderer());
    if (renderImage && m_willUseQuickLookForFullscreen) {
        mediaDetails = getImageMediaDetails(renderImage, IsUpdating::Yes);
        m_page->send(Messages::WebFullScreenManagerProxy::UpdateImageSource(WTFMove(mediaDetails)));
    }
}
#endif // ENABLE(QUICKLOOK_FULLSCREEN)

void WebFullScreenManager::exitFullScreenForElement(WebCore::Element* element, CompletionHandler<void()>&& completionHandler)
{
    if (element)
        ALWAYS_LOG(LOGIDENTIFIER, "<", element->tagName(), " id=\"", element->getIdAttribute(), "\">");
    else
        ALWAYS_LOG(LOGIDENTIFIER, "null");

    m_page->prepareToExitElementFullScreen();

    if (m_inWindowFullScreenMode) {
        willExitFullScreen([this, protectedThis = Ref { *this }, completionHandler = WTFMove(completionHandler)] mutable {
            didExitFullScreen(WTFMove(completionHandler));
            m_inWindowFullScreenMode = false;
        });
    } else {
        m_page->sendWithAsyncReply(Messages::WebFullScreenManagerProxy::ExitFullScreen(), [this, protectedThis = Ref { *this }, completionHandler = WTFMove(completionHandler)] mutable {
            willExitFullScreen(WTFMove(completionHandler));
        });
    }
#if ENABLE(VIDEO)
    setMainVideoElement(nullptr);
#endif
}

void WebFullScreenManager::willEnterFullScreen(CompletionHandler<void(ExceptionOr<void>)>&& willEnterFullscreenCallback, CompletionHandler<bool(bool)>&& didEnterFullscreenCallback, WebCore::HTMLMediaElementEnums::VideoFullscreenMode mode)
{
    if (!m_element) {
        willEnterFullscreenCallback(Exception { ExceptionCode::InvalidStateError });
        didEnterFullscreenCallback(false);
        return;
    }

    ALWAYS_LOG(LOGIDENTIFIER, "<", m_element->tagName(), " id=\"", m_element->getIdAttribute(), "\">");

    m_page->isInFullscreenChanged(WebPage::IsInFullscreenMode::Yes);

    auto result = m_element->document().fullscreenManager().willEnterFullscreen(*m_element, mode);
    if (result.hasException())
        close();
    willEnterFullscreenCallback(result);

    if (!m_element) {
        close();
        didEnterFullscreenCallback(false);
        return;
    }

#if !PLATFORM(IOS_FAMILY)
    m_page->hidePageBanners();
#endif
    m_element->protectedDocument()->updateLayout();
    m_finalFrame = screenRectOfContents(m_element.get());
    m_page->sendWithAsyncReply(Messages::WebFullScreenManagerProxy::BeganEnterFullScreen(m_initialFrame, m_finalFrame), [this, protectedThis = Ref { *this }, completionHandler = WTFMove(didEnterFullscreenCallback)] (bool success) mutable {
        if (!success) {
            completionHandler(false);
            return;
        }
        didEnterFullScreen(WTFMove(completionHandler));
    });
}

void WebFullScreenManager::didEnterFullScreen(CompletionHandler<bool(bool)>&& completionHandler)
{
    if (!m_element) {
        completionHandler(false);
        return;
    }

    ALWAYS_LOG(LOGIDENTIFIER, "<", m_element->tagName(), " id=\"", m_element->getIdAttribute(), "\">");

    if (!completionHandler(true)) {
        close();
        return;
    }

#if ENABLE(QUICKLOOK_FULLSCREEN)
    static constexpr auto maxViewportSize = FloatSize { 10000, 10000 };
    if (m_willUseQuickLookForFullscreen) {
        m_oldSize = m_page->viewportConfiguration().viewLayoutSize();
        m_scaleFactor = m_page->viewportConfiguration().layoutSizeScaleFactor();
        m_minEffectiveWidth = m_page->viewportConfiguration().minimumEffectiveDeviceWidth();
        m_page->setViewportConfigurationViewLayoutSize(maxViewportSize, m_scaleFactor, m_minEffectiveWidth);
    }
#endif

#if PLATFORM(IOS_FAMILY) || (PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE))
    auto* currentPlaybackControlsElement = m_page->playbackSessionManager().currentPlaybackControlsElement();
    setPIPStandbyElement(dynamicDowncast<WebCore::HTMLVideoElement>(currentPlaybackControlsElement));
#endif

#if ENABLE(VIDEO)
    updateMainVideoElement();
#endif
}

#if ENABLE(VIDEO)

void WebFullScreenManager::updateMainVideoElement()
{
    setMainVideoElement([&]() -> RefPtr<WebCore::HTMLVideoElement> {
        if (!m_element)
            return nullptr;

        if (auto video = dynamicDowncast<WebCore::HTMLVideoElement>(*m_element))
            return video;

        RefPtr<WebCore::HTMLVideoElement> mainVideo;
        WebCore::FloatRect mainVideoBounds;
        for (auto& video : WebCore::descendantsOfType<WebCore::HTMLVideoElement>(*m_element)) {
            auto rendererAndBounds = video.boundingAbsoluteRectWithoutLayout();
            if (!rendererAndBounds)
                continue;

            auto& [renderer, bounds] = *rendererAndBounds;
            if (!renderer || bounds.isEmpty())
                continue;

            if (bounds.area() <= mainVideoBounds.area())
                continue;

            mainVideoBounds = bounds;
            mainVideo = &video;
        }
        return mainVideo;
    }());
}

#endif // ENABLE(VIDEO)

void WebFullScreenManager::willExitFullScreen(CompletionHandler<void()>&& completionHandler)
{
    if (!m_element || !m_element->document().frame())
        return completionHandler();
    ALWAYS_LOG(LOGIDENTIFIER, "<", m_element->tagName(), " id=\"", m_element->getIdAttribute(), "\">");

#if ENABLE(VIDEO)
    setPIPStandbyElement(nullptr);
#endif

    m_finalFrame = screenRectOfContents(m_element.get());
    if (!m_element->document().fullscreenManager().willExitFullscreen()) {
        close();
        return completionHandler();
    }
#if !PLATFORM(IOS_FAMILY)
    m_page->showPageBanners();
#endif
    // FIXME: The order of these frames is switched, but that is kept for historical reasons.
    // It should probably be fixed to be consistent at some point.
    m_page->sendWithAsyncReply(Messages::WebFullScreenManagerProxy::BeganExitFullScreen(m_element->document().frame()->frameID(), m_finalFrame, m_initialFrame), [this, protectedThis = Ref { *this }, completionHandler = WTFMove(completionHandler)] mutable {
        didExitFullScreen(WTFMove(completionHandler));
    });
}

static Vector<Ref<Element>> collectFullscreenElementsFromElement(Element* element)
{
    Vector<Ref<Element>> fullscreenElements;

    while (element && element->document().fullscreenManager().fullscreenElement() == element) {
        fullscreenElements.append(*element);
        auto parentDocument = element->document().parentDocument();
        element = parentDocument ? parentDocument->fullscreenManager().fullscreenElement() : nullptr;
    }

    return fullscreenElements;
}

void WebFullScreenManager::didExitFullScreen(CompletionHandler<void()>&& completionHandler)
{
#if PLATFORM(VISION) && ENABLE(QUICKLOOK_FULLSCREEN)
    if (std::exchange(m_willUseQuickLookForFullscreen, false)) {
        m_page->setViewportConfigurationViewLayoutSize(m_oldSize, m_scaleFactor, m_minEffectiveWidth);
        m_page->unfreezeLayerTree(WebPage::LayerTreeFreezeReason::OutOfProcessFullscreen);
    }
#endif

    m_page->isInFullscreenChanged(WebPage::IsInFullscreenMode::No);

    if (!m_element)
        return completionHandler();

    ALWAYS_LOG(LOGIDENTIFIER, "<", m_element->tagName(), " id=\"", m_element->getIdAttribute(), "\">");

    setFullscreenInsets(WebCore::FloatBoxExtent());
    setFullscreenAutoHideDuration(0_s);

    auto fullscreenElements = collectFullscreenElementsFromElement(m_element.get());

    completionHandler();

    // Ensure the element (and all its parent fullscreen elements) that just exited fullscreen are still in view:
    while (!fullscreenElements.isEmpty()) {
        auto element = fullscreenElements.takeLast();
        element->scrollIntoViewIfNotVisible(true);
    }

    clearElement();

    if (RefPtr localMainFrame = m_page->corePage()->localMainFrame()) {
        // Make sure overflow: hidden is unapplied from the root element before restoring.
        localMainFrame->view()->forceLayout();
        localMainFrame->view()->setScrollPosition(m_scrollPosition);
    }
}

void WebFullScreenManager::setAnimatingFullScreen(bool animating)
{
    if (!m_element)
        return;
    m_element->document().fullscreenManager().setAnimatingFullscreen(animating);
}

void WebFullScreenManager::requestRestoreFullScreen(CompletionHandler<void(bool)>&& completionHandler)
{
    ASSERT(!m_element);
    if (m_element)
        return completionHandler(false);

    auto element = RefPtr { m_elementToRestore.get() };
    if (!element) {
        ALWAYS_LOG(LOGIDENTIFIER, "no element to restore");
        return completionHandler(false);
    }

    ALWAYS_LOG(LOGIDENTIFIER, "<", element->tagName(), " id=\"", element->getIdAttribute(), "\">");
    WebCore::UserGestureIndicator gestureIndicator(WebCore::IsProcessingUserGesture::Yes, &element->document());
    element->document().fullscreenManager().requestFullscreenForElement(*element, WebCore::FullscreenManager::ExemptIFrameAllowFullscreenRequirement, [completionHandler = WTFMove(completionHandler)] (auto result) mutable {
        completionHandler(!result.hasException());
    });
}

void WebFullScreenManager::requestExitFullScreen()
{
    if (!m_element) {
        ALWAYS_LOG(LOGIDENTIFIER, "no element, closing");
        close();
        return;
    }

    RefPtr localMainFrame = m_page->localMainFrame();
    RefPtr topDocument = localMainFrame ? localMainFrame->document() : nullptr;
    if (!topDocument || !topDocument->fullscreenManager().fullscreenElement()) {
        ALWAYS_LOG(LOGIDENTIFIER, "top document not in fullscreen, closing");
        close();
        return;
    }

    ALWAYS_LOG(LOGIDENTIFIER);
    m_element->document().fullscreenManager().fullyExitFullscreen();
}

void WebFullScreenManager::close()
{
    if (m_closing)
        return;
    m_closing = true;
    ALWAYS_LOG(LOGIDENTIFIER);
    m_page->closeFullScreen();
    invalidate();
    m_closing = false;
}

void WebFullScreenManager::setFullscreenInsets(const WebCore::FloatBoxExtent& insets)
{
    m_page->corePage()->setFullscreenInsets(insets);
}

void WebFullScreenManager::setFullscreenAutoHideDuration(Seconds duration)
{
    m_page->corePage()->setFullscreenAutoHideDuration(duration);
}

void WebFullScreenManager::handleEvent(WebCore::ScriptExecutionContext& context, WebCore::Event& event)
{
#if ENABLE(VIDEO)
    RefPtr targetElement = dynamicDowncast<WebCore::Element>(event.currentTarget());
    if (!m_element || !targetElement)
        return;

    Ref document = m_element->document();
    if (&context != document.ptr() || !document->fullscreenManager().isFullscreen())
        return;

    if (targetElement == m_element) {
        updateMainVideoElement();
        return;
    }

#if ENABLE(IMAGE_ANALYSIS)
    if (targetElement == m_mainVideoElement.get()) {
        auto& targetVideoElement = downcast<WebCore::HTMLVideoElement>(*targetElement);
        if (targetVideoElement.paused() && !targetVideoElement.seeking())
            scheduleTextRecognitionForMainVideo();
        else
            endTextRecognitionForMainVideoIfNeeded();
    }
#endif
#else
    UNUSED_PARAM(event);
    UNUSED_PARAM(context);
#endif
}

#if ENABLE(VIDEO)

#if ENABLE(IMAGE_ANALYSIS)
void WebFullScreenManager::mainVideoElementTextRecognitionTimerFired()
{
    if (!m_element || !m_element->document().fullscreenManager().isFullscreen())
        return;

    updateMainVideoElement();

    if (!m_mainVideoElement)
        return;

    if (m_isPerformingTextRecognitionInMainVideo)
        m_page->cancelTextRecognitionForVideoInElementFullScreen();

    m_isPerformingTextRecognitionInMainVideo = true;
    m_page->beginTextRecognitionForVideoInElementFullScreen(*m_mainVideoElement);
}

void WebFullScreenManager::scheduleTextRecognitionForMainVideo()
{
    m_mainVideoElementTextRecognitionTimer.startOneShot(250_ms);
}

void WebFullScreenManager::endTextRecognitionForMainVideoIfNeeded()
{
    m_mainVideoElementTextRecognitionTimer.stop();

    if (m_isPerformingTextRecognitionInMainVideo) {
        m_page->cancelTextRecognitionForVideoInElementFullScreen();
        m_isPerformingTextRecognitionInMainVideo = false;
    }
}
#endif // ENABLE(IMAGE_ANALYSIS)

void WebFullScreenManager::setMainVideoElement(RefPtr<WebCore::HTMLVideoElement>&& element)
{
    if (element == m_mainVideoElement.get())
        return;

    static NeverDestroyed eventsToObserve = std::array {
        WebCore::eventNames().seekingEvent,
        WebCore::eventNames().seekedEvent,
        WebCore::eventNames().playingEvent,
        WebCore::eventNames().pauseEvent,
    };

    if (m_mainVideoElement) {
        for (auto& eventName : eventsToObserve.get())
            m_mainVideoElement->removeEventListener(eventName, *this, { });

#if ENABLE(IMAGE_ANALYSIS)
        endTextRecognitionForMainVideoIfNeeded();
#endif
    }

    m_mainVideoElement = WTFMove(element);

    if (m_mainVideoElement) {
        for (auto& eventName : eventsToObserve.get())
            m_mainVideoElement->addEventListener(eventName, *this, { });

#if ENABLE(IMAGE_ANALYSIS)
        if (m_mainVideoElement->paused())
            scheduleTextRecognitionForMainVideo();
#endif
    }
}

#endif // ENABLE(VIDEO)

#if !RELEASE_LOG_DISABLED
WTFLogChannel& WebFullScreenManager::logChannel() const
{
    return WebKit2LogFullscreen;
}
#endif

void WebFullScreenManager::enterFullScreenForOwnerElements(WebCore::FrameIdentifier frameID, CompletionHandler<void()>&& completionHandler)
{
    RefPtr webFrame = WebFrame::webFrame(frameID);
    if (!webFrame)
        return completionHandler();
    RefPtr coreFrame = webFrame->coreFrame();
    if (!coreFrame)
        return completionHandler();

    Vector<Ref<Element>> elements;
    for (RefPtr frame = coreFrame; frame; frame = frame->tree().parent()) {
        if (RefPtr element = frame->ownerElement())
            elements.append(element.releaseNonNull());
    }
    for (auto element : makeReversedRange(elements))
        FullscreenManager::elementEnterFullscreen(element);

    completionHandler();
}

void WebFullScreenManager::exitFullScreenInMainFrame(CompletionHandler<void()>&& completionHandler)
{
    RefPtr mainFrame = m_page->mainFrame();
    if (!mainFrame)
        return completionHandler();

    FullscreenManager::finishExitFullscreen(*mainFrame, FullscreenManager::ExitMode::Resize);
    completionHandler();
}

} // namespace WebKit

#endif // ENABLE(FULLSCREEN_API)