[Web Animations] Tests using the new animation engine may crash under WebCore::FrameV...
[WebKit-https.git] / Source / WebCore / testing / Internals.cpp
1 /*
2  * Copyright (C) 2012 Google Inc. All rights reserved.
3  * Copyright (C) 2013-2018 Apple Inc. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1.  Redistributions of source code must retain the above copyright
10  *     notice, this list of conditions and the following disclaimer.
11  * 2.  Redistributions in binary form must reproduce the above copyright
12  *     notice, this list of conditions and the following disclaimer in the
13  *     documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
16  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
19  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
20  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
21  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
22  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include "config.h"
28 #include "Internals.h"
29
30 #include "AXObjectCache.h"
31 #include "ActiveDOMCallbackMicrotask.h"
32 #include "AnimationTimeline.h"
33 #include "ApplicationCacheStorage.h"
34 #include "AudioSession.h"
35 #include "Autofill.h"
36 #include "BackForwardController.h"
37 #include "BitmapImage.h"
38 #include "CSSAnimationController.h"
39 #include "CSSKeyframesRule.h"
40 #include "CSSMediaRule.h"
41 #include "CSSStyleRule.h"
42 #include "CSSSupportsRule.h"
43 #include "CacheStorageConnection.h"
44 #include "CacheStorageProvider.h"
45 #include "CachedImage.h"
46 #include "CachedResourceLoader.h"
47 #include "Chrome.h"
48 #include "ClientOrigin.h"
49 #include "ComposedTreeIterator.h"
50 #include "Cursor.h"
51 #include "DOMRect.h"
52 #include "DOMRectList.h"
53 #include "DOMStringList.h"
54 #include "DOMWindow.h"
55 #include "DeprecatedGlobalSettings.h"
56 #include "DisplayList.h"
57 #include "Document.h"
58 #include "DocumentLoader.h"
59 #include "DocumentMarkerController.h"
60 #include "DocumentTimeline.h"
61 #include "Editor.h"
62 #include "Element.h"
63 #include "EventHandler.h"
64 #include "ExtendableEvent.h"
65 #include "ExtensionStyleSheets.h"
66 #include "FetchResponse.h"
67 #include "File.h"
68 #include "FontCache.h"
69 #include "FormController.h"
70 #include "Frame.h"
71 #include "FrameLoader.h"
72 #include "FrameView.h"
73 #include "GCObservation.h"
74 #include "GridPosition.h"
75 #include "HTMLAnchorElement.h"
76 #include "HTMLCanvasElement.h"
77 #include "HTMLIFrameElement.h"
78 #include "HTMLImageElement.h"
79 #include "HTMLInputElement.h"
80 #include "HTMLLinkElement.h"
81 #include "HTMLNames.h"
82 #include "HTMLPictureElement.h"
83 #include "HTMLPlugInElement.h"
84 #include "HTMLPreloadScanner.h"
85 #include "HTMLSelectElement.h"
86 #include "HTMLTextAreaElement.h"
87 #include "HTMLVideoElement.h"
88 #include "HistoryController.h"
89 #include "HistoryItem.h"
90 #include "HitTestResult.h"
91 #include "InspectorClient.h"
92 #include "InspectorController.h"
93 #include "InspectorFrontendClientLocal.h"
94 #include "InspectorOverlay.h"
95 #include "InstrumentingAgents.h"
96 #include "IntRect.h"
97 #include "InternalSettings.h"
98 #include "JSImageData.h"
99 #include "LibWebRTCProvider.h"
100 #include "MallocStatistics.h"
101 #include "MediaPlayer.h"
102 #include "MediaProducer.h"
103 #include "MediaResourceLoader.h"
104 #include "MediaStreamTrack.h"
105 #include "MemoryCache.h"
106 #include "MemoryInfo.h"
107 #include "MockLibWebRTCPeerConnection.h"
108 #include "MockPageOverlay.h"
109 #include "MockPageOverlayClient.h"
110 #if USE(CG)
111 #include "PDFDocumentImage.h"
112 #endif
113 #include "Page.h"
114 #include "PageCache.h"
115 #include "PageOverlay.h"
116 #include "PathUtilities.h"
117 #include "PlatformMediaSessionManager.h"
118 #include "PrintContext.h"
119 #include "PseudoElement.h"
120 #include "Range.h"
121 #include "ReadableStream.h"
122 #include "RenderEmbeddedObject.h"
123 #include "RenderLayerBacking.h"
124 #include "RenderLayerCompositor.h"
125 #include "RenderMenuList.h"
126 #include "RenderTreeAsText.h"
127 #include "RenderView.h"
128 #include "RenderedDocumentMarker.h"
129 #include "ResourceLoadObserver.h"
130 #include "RuntimeEnabledFeatures.h"
131 #include "SMILTimeContainer.h"
132 #include "SVGDocumentExtensions.h"
133 #include "SVGPathStringBuilder.h"
134 #include "SVGSVGElement.h"
135 #include "SWClientConnection.h"
136 #include "SchemeRegistry.h"
137 #include "ScriptedAnimationController.h"
138 #include "ScrollingCoordinator.h"
139 #include "ScrollingMomentumCalculator.h"
140 #include "SecurityOrigin.h"
141 #include "SerializedScriptValue.h"
142 #include "ServiceWorker.h"
143 #include "ServiceWorkerProvider.h"
144 #include "ServiceWorkerRegistrationData.h"
145 #include "Settings.h"
146 #include "ShadowRoot.h"
147 #include "SourceBuffer.h"
148 #include "SpellChecker.h"
149 #include "StaticNodeList.h"
150 #include "StringCallback.h"
151 #include "StyleRule.h"
152 #include "StyleScope.h"
153 #include "StyleSheetContents.h"
154 #include "TextIterator.h"
155 #include "TreeScope.h"
156 #include "TypeConversions.h"
157 #include "UserGestureIndicator.h"
158 #include "UserMediaController.h"
159 #include "ViewportArguments.h"
160 #include "VoidCallback.h"
161 #include "WebCoreJSClientData.h"
162 #include "WindowProxy.h"
163 #include "WorkerThread.h"
164 #include "WritingDirection.h"
165 #include "XMLHttpRequest.h"
166 #include <JavaScriptCore/CodeBlock.h>
167 #include <JavaScriptCore/InspectorAgentBase.h>
168 #include <JavaScriptCore/InspectorFrontendChannel.h>
169 #include <JavaScriptCore/JSCInlines.h>
170 #include <JavaScriptCore/JSCJSValue.h>
171 #include <wtf/JSONValues.h>
172 #include <wtf/Language.h>
173 #include <wtf/MemoryPressureHandler.h>
174 #include <wtf/MonotonicTime.h>
175 #include <wtf/text/StringBuffer.h>
176 #include <wtf/text/StringBuilder.h>
177 #include <wtf/text/StringView.h>
178
179 #if ENABLE(INPUT_TYPE_COLOR)
180 #include "ColorChooser.h"
181 #endif
182
183 #if ENABLE(MOUSE_CURSOR_SCALE)
184 #include <wtf/dtoa.h>
185 #endif
186
187 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
188 #include "LegacyCDM.h"
189 #include "LegacyMockCDM.h"
190 #endif
191
192 #if ENABLE(ENCRYPTED_MEDIA)
193 #include "MockCDMFactory.h"
194 #endif
195
196 #if ENABLE(VIDEO_TRACK)
197 #include "CaptionUserPreferences.h"
198 #include "PageGroup.h"
199 #endif
200
201 #if ENABLE(VIDEO)
202 #include "HTMLMediaElement.h"
203 #include "TimeRanges.h"
204 #endif
205
206 #if ENABLE(WEBGL)
207 #include "WebGLRenderingContext.h"
208 #endif
209
210 #if ENABLE(SPEECH_SYNTHESIS)
211 #include "DOMWindowSpeechSynthesis.h"
212 #include "PlatformSpeechSynthesizerMock.h"
213 #include "SpeechSynthesis.h"
214 #endif
215
216 #if ENABLE(MEDIA_STREAM)
217 #include "MediaStream.h"
218 #include "MockRealtimeMediaSourceCenter.h"
219 #endif
220
221 #if ENABLE(WEB_RTC)
222 #include "RTCPeerConnection.h"
223 #endif
224
225 #if ENABLE(MEDIA_SOURCE)
226 #include "MockMediaPlayerMediaSource.h"
227 #endif
228
229 #if PLATFORM(MAC)
230 #include "DictionaryLookup.h"
231 #endif
232
233 #if ENABLE(CONTENT_FILTERING)
234 #include "MockContentFilterSettings.h"
235 #endif
236
237 #if ENABLE(WEB_AUDIO)
238 #include "AudioContext.h"
239 #endif
240
241 #if ENABLE(MEDIA_SESSION)
242 #include "MediaSession.h"
243 #include "MediaSessionManager.h"
244 #endif
245
246 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
247 #include "MediaPlaybackTargetContext.h"
248 #endif
249
250 #if ENABLE(POINTER_LOCK)
251 #include "PointerLockController.h"
252 #endif
253
254 #if USE(QUICK_LOOK)
255 #include "MockPreviewLoaderClient.h"
256 #include "PreviewLoader.h"
257 #endif
258
259 #if ENABLE(APPLE_PAY)
260 #include "MockPaymentCoordinator.h"
261 #include "PaymentCoordinator.h"
262 #endif
263
264 #if ENABLE(WEB_AUTHN)
265 #include "AuthenticatorManager.h"
266 #include "MockCredentialsMessenger.h"
267 #endif
268
269 #if USE(SYSTEM_PREVIEW) && USE(APPLE_INTERNAL_SDK)
270 #import <WebKitAdditions/SystemPreviewDetection.cpp>
271 #endif
272
273 using JSC::CallData;
274 using JSC::CallType;
275 using JSC::CodeBlock;
276 using JSC::FunctionExecutable;
277 using JSC::Identifier;
278 using JSC::JSFunction;
279 using JSC::JSGlobalObject;
280 using JSC::JSObject;
281 using JSC::JSValue;
282 using JSC::MarkedArgumentBuffer;
283 using JSC::PropertySlot;
284 using JSC::ScriptExecutable;
285 using JSC::StackVisitor;
286
287
288 namespace WebCore {
289 using namespace Inspector;
290
291 using namespace HTMLNames;
292
293 class InspectorStubFrontend final : public InspectorFrontendClientLocal, public FrontendChannel {
294 public:
295     InspectorStubFrontend(Page& inspectedPage, RefPtr<DOMWindow>&& frontendWindow);
296     virtual ~InspectorStubFrontend();
297
298 private:
299     void attachWindow(DockSide) final { }
300     void detachWindow() final { }
301     void closeWindow() final;
302     void bringToFront() final { }
303     String localizedStringsURL() final { return String(); }
304     void inspectedURLChanged(const String&) final { }
305     void setAttachedWindowHeight(unsigned) final { }
306     void setAttachedWindowWidth(unsigned) final { }
307
308     void sendMessageToFrontend(const String& message) final;
309     ConnectionType connectionType() const final { return ConnectionType::Local; }
310
311     Page* frontendPage() const
312     {
313         if (!m_frontendWindow || !m_frontendWindow->document())
314             return nullptr;
315
316         return m_frontendWindow->document()->page();
317     }
318
319     RefPtr<DOMWindow> m_frontendWindow;
320     InspectorController& m_frontendController;
321 };
322
323 InspectorStubFrontend::InspectorStubFrontend(Page& inspectedPage, RefPtr<DOMWindow>&& frontendWindow)
324     : InspectorFrontendClientLocal(&inspectedPage.inspectorController(), frontendWindow->document()->page(), std::make_unique<InspectorFrontendClientLocal::Settings>())
325     , m_frontendWindow(frontendWindow.copyRef())
326     , m_frontendController(frontendPage()->inspectorController())
327 {
328     ASSERT_ARG(frontendWindow, frontendWindow);
329
330     m_frontendController.setInspectorFrontendClient(this);
331     inspectedPage.inspectorController().connectFrontend(this);
332 }
333
334 InspectorStubFrontend::~InspectorStubFrontend()
335 {
336     closeWindow();
337 }
338
339 void InspectorStubFrontend::closeWindow()
340 {
341     if (!m_frontendWindow)
342         return;
343
344     m_frontendController.setInspectorFrontendClient(nullptr);
345     inspectedPage()->inspectorController().disconnectFrontend(this);
346
347     m_frontendWindow->close();
348     m_frontendWindow = nullptr;
349 }
350
351 void InspectorStubFrontend::sendMessageToFrontend(const String& message)
352 {
353     ASSERT_ARG(message, !message.isEmpty());
354
355     InspectorClient::doDispatchMessageOnFrontendPage(frontendPage(), message);
356 }
357
358 static bool markerTypeFrom(const String& markerType, DocumentMarker::MarkerType& result)
359 {
360     if (equalLettersIgnoringASCIICase(markerType, "spelling"))
361         result = DocumentMarker::Spelling;
362     else if (equalLettersIgnoringASCIICase(markerType, "grammar"))
363         result = DocumentMarker::Grammar;
364     else if (equalLettersIgnoringASCIICase(markerType, "textmatch"))
365         result = DocumentMarker::TextMatch;
366     else if (equalLettersIgnoringASCIICase(markerType, "replacement"))
367         result = DocumentMarker::Replacement;
368     else if (equalLettersIgnoringASCIICase(markerType, "correctionindicator"))
369         result = DocumentMarker::CorrectionIndicator;
370     else if (equalLettersIgnoringASCIICase(markerType, "rejectedcorrection"))
371         result = DocumentMarker::RejectedCorrection;
372     else if (equalLettersIgnoringASCIICase(markerType, "autocorrected"))
373         result = DocumentMarker::Autocorrected;
374     else if (equalLettersIgnoringASCIICase(markerType, "spellcheckingexemption"))
375         result = DocumentMarker::SpellCheckingExemption;
376     else if (equalLettersIgnoringASCIICase(markerType, "deletedautocorrection"))
377         result = DocumentMarker::DeletedAutocorrection;
378     else if (equalLettersIgnoringASCIICase(markerType, "dictationalternatives"))
379         result = DocumentMarker::DictationAlternatives;
380 #if ENABLE(TELEPHONE_NUMBER_DETECTION)
381     else if (equalLettersIgnoringASCIICase(markerType, "telephonenumber"))
382         result = DocumentMarker::TelephoneNumber;
383 #endif
384     else
385         return false;
386
387     return true;
388 }
389
390 static bool markerTypesFrom(const String& markerType, OptionSet<DocumentMarker::MarkerType>& result)
391 {
392     DocumentMarker::MarkerType singularResult;
393
394     if (markerType.isEmpty() || equalLettersIgnoringASCIICase(markerType, "all"))
395         result = DocumentMarker::allMarkers();
396     else if (markerTypeFrom(markerType, singularResult))
397         result = singularResult;
398     else
399         return false;
400
401     return true;
402 }
403
404 static std::unique_ptr<PrintContext>& printContextForTesting()
405 {
406     static NeverDestroyed<std::unique_ptr<PrintContext>> context;
407     return context;
408 }
409
410 const char* Internals::internalsId = "internals";
411
412 Ref<Internals> Internals::create(Document& document)
413 {
414     return adoptRef(*new Internals(document));
415 }
416
417 Internals::~Internals()
418 {
419 #if ENABLE(MEDIA_STREAM)
420     if (m_track)
421         m_track->source().removeObserver(*this);
422 #endif
423 }
424
425 void Internals::resetToConsistentState(Page& page)
426 {
427     page.setPageScaleFactor(1, IntPoint(0, 0));
428     page.setPagination(Pagination());
429     page.setPaginationLineGridEnabled(false);
430
431     page.setDefersLoading(false);
432
433     page.mainFrame().setTextZoomFactor(1.0f);
434
435     FrameView* mainFrameView = page.mainFrame().view();
436     if (mainFrameView) {
437         mainFrameView->setHeaderHeight(0);
438         mainFrameView->setFooterHeight(0);
439         page.setTopContentInset(0);
440         mainFrameView->setUseFixedLayout(false);
441         mainFrameView->setFixedLayoutSize(IntSize());
442 #if USE(COORDINATED_GRAPHICS)
443         mainFrameView->setFixedVisibleContentRect(IntRect());
444 #endif
445         if (auto* backing = mainFrameView->tiledBacking())
446             backing->setTileSizeUpdateDelayDisabledForTesting(false);
447     }
448
449     WebCore::clearDefaultPortForProtocolMapForTesting();
450     overrideUserPreferredLanguages(Vector<String>());
451     WebCore::DeprecatedGlobalSettings::setUsesOverlayScrollbars(false);
452     WebCore::DeprecatedGlobalSettings::setUsesMockScrollAnimator(false);
453 #if ENABLE(VIDEO_TRACK)
454     page.group().captionPreferences().setTestingMode(true);
455     page.group().captionPreferences().setCaptionsStyleSheetOverride(emptyString());
456     page.group().captionPreferences().setTestingMode(false);
457 #endif
458     if (!page.mainFrame().editor().isContinuousSpellCheckingEnabled())
459         page.mainFrame().editor().toggleContinuousSpellChecking();
460     if (page.mainFrame().editor().isOverwriteModeEnabled())
461         page.mainFrame().editor().toggleOverwriteModeEnabled();
462     page.mainFrame().loader().clearTestingOverrides();
463     page.applicationCacheStorage().setDefaultOriginQuota(ApplicationCacheStorage::noQuota());
464 #if ENABLE(VIDEO)
465     PlatformMediaSessionManager::sharedManager().resetRestrictions();
466     PlatformMediaSessionManager::sharedManager().setWillIgnoreSystemInterruptions(true);
467 #endif
468 #if HAVE(ACCESSIBILITY)
469     AXObjectCache::setEnhancedUserInterfaceAccessibility(false);
470     AXObjectCache::disableAccessibility();
471 #endif
472
473     MockPageOverlayClient::singleton().uninstallAllOverlays();
474
475 #if ENABLE(CONTENT_FILTERING)
476     MockContentFilterSettings::reset();
477 #endif
478
479 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
480     page.setMockMediaPlaybackTargetPickerEnabled(true);
481     page.setMockMediaPlaybackTargetPickerState(emptyString(), MediaPlaybackTargetContext::Unknown);
482 #endif
483
484     page.setShowAllPlugins(false);
485     page.setLowPowerModeEnabledOverrideForTesting(std::nullopt);
486
487 #if USE(QUICK_LOOK)
488     MockPreviewLoaderClient::singleton().setPassword("");
489     PreviewLoader::setClientForTesting(nullptr);
490 #endif
491
492     printContextForTesting() = nullptr;
493
494 #if USE(LIBWEBRTC)
495     WebCore::useRealRTCPeerConnectionFactory(page.libWebRTCProvider());
496 #endif
497
498     page.settings().setStorageAccessAPIEnabled(false);
499     page.setFullscreenAutoHideDelay(0);
500     page.setFullscreenInsetTop(0);
501 }
502
503 Internals::Internals(Document& document)
504     : ContextDestructionObserver(&document)
505 #if ENABLE(MEDIA_STREAM)
506     , m_orientationNotifier(0)
507 #endif
508 {
509 #if ENABLE(VIDEO_TRACK)
510     if (document.page())
511         document.page()->group().captionPreferences().setTestingMode(true);
512 #endif
513
514 #if ENABLE(MEDIA_STREAM)
515     setMockMediaCaptureDevicesEnabled(true);
516     WebCore::DeprecatedGlobalSettings::setMediaCaptureRequiresSecureConnection(false);
517 #endif
518
519 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
520     if (document.page())
521         document.page()->setMockMediaPlaybackTargetPickerEnabled(true);
522 #endif
523
524     if (contextDocument() && contextDocument()->frame()) {
525         setAutomaticSpellingCorrectionEnabled(true);
526         setAutomaticQuoteSubstitutionEnabled(false);
527         setAutomaticDashSubstitutionEnabled(false);
528         setAutomaticLinkDetectionEnabled(false);
529         setAutomaticTextReplacementEnabled(true);
530     }
531
532     setConsoleMessageListener(nullptr);
533
534 #if ENABLE(APPLE_PAY)
535     auto* frame = document.frame();
536     if (frame && frame->page()) {
537         m_mockPaymentCoordinator = new MockPaymentCoordinator(*frame->page());
538         frame->page()->setPaymentCoordinator(std::make_unique<PaymentCoordinator>(*m_mockPaymentCoordinator));
539     }
540 #endif
541
542 #if ENABLE(WEB_AUTHN)
543     m_mockCredentialsMessenger = std::make_unique<MockCredentialsMessenger>(*this);
544     AuthenticatorManager::singleton().setMessenger(*m_mockCredentialsMessenger);
545 #endif
546 }
547
548 Document* Internals::contextDocument() const
549 {
550     return downcast<Document>(scriptExecutionContext());
551 }
552
553 Frame* Internals::frame() const
554 {
555     if (!contextDocument())
556         return nullptr;
557     return contextDocument()->frame();
558 }
559
560 InternalSettings* Internals::settings() const
561 {
562     Document* document = contextDocument();
563     if (!document)
564         return nullptr;
565     Page* page = document->page();
566     if (!page)
567         return nullptr;
568     return InternalSettings::from(page);
569 }
570
571 unsigned Internals::workerThreadCount() const
572 {
573     return WorkerThread::workerThreadCount();
574 }
575
576 ExceptionOr<bool> Internals::areSVGAnimationsPaused() const
577 {
578     auto* document = contextDocument();
579     if (!document)
580         return Exception { InvalidAccessError, ASCIILiteral("No context document") };
581
582     if (!document->svgExtensions())
583         return Exception { NotFoundError, ASCIILiteral("No SVG animations") };
584
585     return document->accessSVGExtensions().areAnimationsPaused();
586 }
587
588 ExceptionOr<double> Internals::svgAnimationsInterval(SVGSVGElement& element) const
589 {
590     auto* document = contextDocument();
591     if (!document)
592         return 0;
593
594     if (!document->svgExtensions())
595         return 0;
596
597     if (document->accessSVGExtensions().areAnimationsPaused())
598         return 0;
599
600     return element.timeContainer().animationFrameDelay().value();
601 }
602
603 String Internals::address(Node& node)
604 {
605     return String::format("%p", &node);
606 }
607
608 bool Internals::nodeNeedsStyleRecalc(Node& node)
609 {
610     return node.needsStyleRecalc();
611 }
612
613 static String styleValidityToToString(Style::Validity validity)
614 {
615     switch (validity) {
616     case Style::Validity::Valid:
617         return "NoStyleChange";
618     case Style::Validity::ElementInvalid:
619         return "InlineStyleChange";
620     case Style::Validity::SubtreeInvalid:
621         return "FullStyleChange";
622     case Style::Validity::SubtreeAndRenderersInvalid:
623         return "ReconstructRenderTree";
624     }
625     ASSERT_NOT_REACHED();
626     return "";
627 }
628
629 String Internals::styleChangeType(Node& node)
630 {
631     node.document().styleScope().flushPendingUpdate();
632
633     return styleValidityToToString(node.styleValidity());
634 }
635
636 String Internals::description(JSC::JSValue value)
637 {
638     return toString(value);
639 }
640
641 bool Internals::isPreloaded(const String& url)
642 {
643     Document* document = contextDocument();
644     return document->cachedResourceLoader().isPreloaded(url);
645 }
646
647 bool Internals::isLoadingFromMemoryCache(const String& url)
648 {
649     if (!contextDocument() || !contextDocument()->page())
650         return false;
651
652     ResourceRequest request(contextDocument()->completeURL(url));
653     request.setDomainForCachePartition(contextDocument()->domainForCachePartition());
654
655     CachedResource* resource = MemoryCache::singleton().resourceForRequest(request, contextDocument()->page()->sessionID());
656     return resource && resource->status() == CachedResource::Cached;
657 }
658
659 static String responseSourceToString(const ResourceResponse& response)
660 {
661     if (response.isNull())
662         return "Null response";
663     switch (response.source()) {
664     case ResourceResponse::Source::Unknown:
665         return "Unknown";
666     case ResourceResponse::Source::Network:
667         return "Network";
668     case ResourceResponse::Source::ServiceWorker:
669         return "Service worker";
670     case ResourceResponse::Source::DiskCache:
671         return "Disk cache";
672     case ResourceResponse::Source::DiskCacheAfterValidation:
673         return "Disk cache after validation";
674     case ResourceResponse::Source::MemoryCache:
675         return "Memory cache";
676     case ResourceResponse::Source::MemoryCacheAfterValidation:
677         return "Memory cache after validation";
678     case ResourceResponse::Source::ApplicationCache:
679         return "Application cache";
680     }
681     ASSERT_NOT_REACHED();
682     return "Error";
683 }
684
685 String Internals::xhrResponseSource(XMLHttpRequest& request)
686 {
687     return responseSourceToString(request.resourceResponse());
688 }
689
690 String Internals::fetchResponseSource(FetchResponse& response)
691 {
692     return responseSourceToString(response.resourceResponse());
693 }
694
695 bool Internals::isSharingStyleSheetContents(HTMLLinkElement& a, HTMLLinkElement& b)
696 {
697     if (!a.sheet() || !b.sheet())
698         return false;
699     return &a.sheet()->contents() == &b.sheet()->contents();
700 }
701
702 bool Internals::isStyleSheetLoadingSubresources(HTMLLinkElement& link)
703 {
704     return link.sheet() && link.sheet()->contents().isLoadingSubresources();
705 }
706
707 static ResourceRequestCachePolicy toResourceRequestCachePolicy(Internals::CachePolicy policy)
708 {
709     switch (policy) {
710     case Internals::CachePolicy::UseProtocolCachePolicy:
711         return UseProtocolCachePolicy;
712     case Internals::CachePolicy::ReloadIgnoringCacheData:
713         return ReloadIgnoringCacheData;
714     case Internals::CachePolicy::ReturnCacheDataElseLoad:
715         return ReturnCacheDataElseLoad;
716     case Internals::CachePolicy::ReturnCacheDataDontLoad:
717         return ReturnCacheDataDontLoad;
718     }
719     ASSERT_NOT_REACHED();
720     return UseProtocolCachePolicy;
721 }
722
723 void Internals::setOverrideCachePolicy(CachePolicy policy)
724 {
725     frame()->loader().setOverrideCachePolicyForTesting(toResourceRequestCachePolicy(policy));
726 }
727
728 ExceptionOr<void> Internals::setCanShowModalDialogOverride(bool allow)
729 {
730     if (!contextDocument() || !contextDocument()->domWindow())
731         return Exception { InvalidAccessError };
732
733     contextDocument()->domWindow()->setCanShowModalDialogOverride(allow);
734     return { };
735 }
736
737 static ResourceLoadPriority toResourceLoadPriority(Internals::ResourceLoadPriority priority)
738 {
739     switch (priority) {
740     case Internals::ResourceLoadPriority::ResourceLoadPriorityVeryLow:
741         return ResourceLoadPriority::VeryLow;
742     case Internals::ResourceLoadPriority::ResourceLoadPriorityLow:
743         return ResourceLoadPriority::Low;
744     case Internals::ResourceLoadPriority::ResourceLoadPriorityMedium:
745         return ResourceLoadPriority::Medium;
746     case Internals::ResourceLoadPriority::ResourceLoadPriorityHigh:
747         return ResourceLoadPriority::High;
748     case Internals::ResourceLoadPriority::ResourceLoadPriorityVeryHigh:
749         return ResourceLoadPriority::VeryHigh;
750     }
751     ASSERT_NOT_REACHED();
752     return ResourceLoadPriority::Low;
753 }
754
755 void Internals::setOverrideResourceLoadPriority(ResourceLoadPriority priority)
756 {
757     frame()->loader().setOverrideResourceLoadPriorityForTesting(toResourceLoadPriority(priority));
758 }
759
760 void Internals::setStrictRawResourceValidationPolicyDisabled(bool disabled)
761 {
762     frame()->loader().setStrictRawResourceValidationPolicyDisabledForTesting(disabled);
763 }
764
765 void Internals::clearMemoryCache()
766 {
767     MemoryCache::singleton().evictResources();
768 }
769
770 void Internals::pruneMemoryCacheToSize(unsigned size)
771 {
772     MemoryCache::singleton().pruneDeadResourcesToSize(size);
773     MemoryCache::singleton().pruneLiveResourcesToSize(size, true);
774 }
775     
776 void Internals::destroyDecodedDataForAllImages()
777 {
778     MemoryCache::singleton().destroyDecodedDataForAllImages();
779 }
780
781 unsigned Internals::memoryCacheSize() const
782 {
783     return MemoryCache::singleton().size();
784 }
785
786 static Image* imageFromImageElement(HTMLImageElement& element)
787 {
788     auto* cachedImage = element.cachedImage();
789     return cachedImage ? cachedImage->image() : nullptr;
790 }
791
792 static BitmapImage* bitmapImageFromImageElement(HTMLImageElement& element)
793 {
794     auto* image = imageFromImageElement(element);
795     return image && is<BitmapImage>(image) ? &downcast<BitmapImage>(*image) : nullptr;
796 }
797
798 #if USE(CG)
799 static PDFDocumentImage* pdfDocumentImageFromImageElement(HTMLImageElement& element)
800 {
801     auto* image = imageFromImageElement(element);
802     return image && is<PDFDocumentImage>(image) ? &downcast<PDFDocumentImage>(*image) : nullptr;
803 }
804 #endif
805
806 unsigned Internals::imageFrameIndex(HTMLImageElement& element)
807 {
808     auto* bitmapImage = bitmapImageFromImageElement(element);
809     return bitmapImage ? bitmapImage->currentFrame() : 0;
810 }
811
812 void Internals::setImageFrameDecodingDuration(HTMLImageElement& element, float duration)
813 {
814     if (auto* bitmapImage = bitmapImageFromImageElement(element))
815         bitmapImage->setFrameDecodingDurationForTesting(Seconds { duration });
816 }
817
818 void Internals::resetImageAnimation(HTMLImageElement& element)
819 {
820     if (auto* image = imageFromImageElement(element))
821         image->resetAnimation();
822 }
823
824 bool Internals::isImageAnimating(HTMLImageElement& element)
825 {
826     auto* image = imageFromImageElement(element);
827     return image && (image->isAnimating() || image->animationPending());
828 }
829
830 void Internals::setClearDecoderAfterAsyncFrameRequestForTesting(HTMLImageElement& element, bool enabled)
831 {
832     if (auto* bitmapImage = bitmapImageFromImageElement(element))
833         bitmapImage->setClearDecoderAfterAsyncFrameRequestForTesting(enabled);
834 }
835
836 unsigned Internals::imageDecodeCount(HTMLImageElement& element)
837 {
838     auto* bitmapImage = bitmapImageFromImageElement(element);
839     return bitmapImage ? bitmapImage->decodeCountForTesting() : 0;
840 }
841
842 unsigned Internals::pdfDocumentCachingCount(HTMLImageElement& element)
843 {
844 #if USE(CG)
845     auto* pdfDocumentImage = pdfDocumentImageFromImageElement(element);
846     return pdfDocumentImage ? pdfDocumentImage->cachingCountForTesting() : 0;
847 #else
848     UNUSED_PARAM(element);
849     return 0;
850 #endif
851 }
852
853 void Internals::setLargeImageAsyncDecodingEnabledForTesting(HTMLImageElement& element, bool enabled)
854 {
855     if (auto* bitmapImage = bitmapImageFromImageElement(element))
856         bitmapImage->setLargeImageAsyncDecodingEnabledForTesting(enabled);
857 }
858     
859 void Internals::setForceUpdateImageDataEnabledForTesting(HTMLImageElement& element, bool enabled)
860 {
861     if (auto* cachedImage = element.cachedImage())
862         cachedImage->setForceUpdateImageDataEnabledForTesting(enabled);
863 }
864
865 void Internals::setGridMaxTracksLimit(unsigned maxTrackLimit)
866 {
867     GridPosition::setMaxPositionForTesting(maxTrackLimit);
868 }
869
870 void Internals::clearPageCache()
871 {
872     PageCache::singleton().pruneToSizeNow(0, PruningReason::None);
873 }
874
875 unsigned Internals::pageCacheSize() const
876 {
877     return PageCache::singleton().pageCount();
878 }
879
880 void Internals::disableTileSizeUpdateDelay()
881 {
882     Document* document = contextDocument();
883     if (!document || !document->frame())
884         return;
885
886     auto* view = document->frame()->view();
887     if (!view)
888         return;
889
890     if (auto* backing = view->tiledBacking())
891         backing->setTileSizeUpdateDelayDisabledForTesting(true);
892 }
893
894 void Internals::setSpeculativeTilingDelayDisabledForTesting(bool disabled)
895 {
896     Document* document = contextDocument();
897     if (!document || !document->frame())
898         return;
899
900     if (auto* frameView = document->frame()->view())
901         frameView->setSpeculativeTilingDelayDisabledForTesting(disabled);
902 }
903
904
905 Node* Internals::treeScopeRootNode(Node& node)
906 {
907     return &node.treeScope().rootNode();
908 }
909
910 Node* Internals::parentTreeScope(Node& node)
911 {
912     const TreeScope* parentTreeScope = node.treeScope().parentTreeScope();
913     return parentTreeScope ? &parentTreeScope->rootNode() : nullptr;
914 }
915
916 ExceptionOr<unsigned> Internals::lastSpatialNavigationCandidateCount() const
917 {
918     if (!contextDocument() || !contextDocument()->page())
919         return Exception { InvalidAccessError };
920
921     return contextDocument()->page()->lastSpatialNavigationCandidateCount();
922 }
923
924 unsigned Internals::numberOfActiveAnimations() const
925 {
926     if (RuntimeEnabledFeatures::sharedFeatures().cssAnimationsAndCSSTransitionsBackedByWebAnimationsEnabled())
927         return frame()->document()->timeline().numberOfActiveAnimationsForTesting();
928     return frame()->animation().numberOfActiveAnimations(frame()->document());
929 }
930
931 ExceptionOr<bool> Internals::animationsAreSuspended() const
932 {
933     Document* document = contextDocument();
934     if (!document || !document->frame())
935         return Exception { InvalidAccessError };
936
937     if (RuntimeEnabledFeatures::sharedFeatures().cssAnimationsAndCSSTransitionsBackedByWebAnimationsEnabled())
938         return document->timeline().animationsAreSuspended();
939     return document->frame()->animation().animationsAreSuspendedForDocument(document);
940 }
941
942 double Internals::animationsInterval() const
943 {
944     Document* document = contextDocument();
945     if (!document)
946         return INFINITY;
947
948     if (RuntimeEnabledFeatures::sharedFeatures().cssAnimationsAndCSSTransitionsBackedByWebAnimationsEnabled()) {
949         if (auto timeline = document->existingTimeline())
950             return timeline->animationInterval().seconds();
951         return INFINITY;
952     }
953
954     if (!document->frame())
955         return INFINITY;
956     return document->frame()->animation().animationInterval().value();
957 }
958
959 ExceptionOr<void> Internals::suspendAnimations() const
960 {
961     Document* document = contextDocument();
962     if (!document || !document->frame())
963         return Exception { InvalidAccessError };
964
965     if (RuntimeEnabledFeatures::sharedFeatures().cssAnimationsAndCSSTransitionsBackedByWebAnimationsEnabled()) {
966         document->timeline().suspendAnimations();
967         for (Frame* frame = document->frame(); frame; frame = frame->tree().traverseNext()) {
968             if (Document* document = frame->document())
969                 document->timeline().suspendAnimations();
970         }
971     } else {
972         document->frame()->animation().suspendAnimationsForDocument(document);
973
974         for (Frame* frame = document->frame(); frame; frame = frame->tree().traverseNext()) {
975             if (Document* document = frame->document())
976                 frame->animation().suspendAnimationsForDocument(document);
977         }
978     }
979
980     return { };
981 }
982
983 ExceptionOr<void> Internals::resumeAnimations() const
984 {
985     Document* document = contextDocument();
986     if (!document || !document->frame())
987         return Exception { InvalidAccessError };
988
989     if (RuntimeEnabledFeatures::sharedFeatures().cssAnimationsAndCSSTransitionsBackedByWebAnimationsEnabled()) {
990         document->timeline().resumeAnimations();
991         for (Frame* frame = document->frame(); frame; frame = frame->tree().traverseNext()) {
992             if (Document* document = frame->document())
993                 document->timeline().resumeAnimations();
994         }
995     } else {
996         document->frame()->animation().resumeAnimationsForDocument(document);
997
998         for (Frame* frame = document->frame(); frame; frame = frame->tree().traverseNext()) {
999             if (Document* document = frame->document())
1000                 frame->animation().resumeAnimationsForDocument(document);
1001         }
1002     }
1003
1004     return { };
1005 }
1006
1007 ExceptionOr<bool> Internals::pauseAnimationAtTimeOnElement(const String& animationName, double pauseTime, Element& element)
1008 {
1009     if (pauseTime < 0)
1010         return Exception { InvalidAccessError };
1011     return frame()->animation().pauseAnimationAtTime(element, AtomicString(animationName), pauseTime);
1012 }
1013
1014 ExceptionOr<bool> Internals::pauseAnimationAtTimeOnPseudoElement(const String& animationName, double pauseTime, Element& element, const String& pseudoId)
1015 {
1016     if (pauseTime < 0)
1017         return Exception { InvalidAccessError };
1018
1019     if (pseudoId != "before" && pseudoId != "after")
1020         return Exception { InvalidAccessError };
1021
1022     PseudoElement* pseudoElement = pseudoId == "before" ? element.beforePseudoElement() : element.afterPseudoElement();
1023     if (!pseudoElement)
1024         return Exception { InvalidAccessError };
1025
1026     return frame()->animation().pauseAnimationAtTime(*pseudoElement, AtomicString(animationName), pauseTime);
1027 }
1028
1029 ExceptionOr<bool> Internals::pauseTransitionAtTimeOnElement(const String& propertyName, double pauseTime, Element& element)
1030 {
1031     if (pauseTime < 0)
1032         return Exception { InvalidAccessError };
1033     return frame()->animation().pauseTransitionAtTime(element, propertyName, pauseTime);
1034 }
1035
1036 ExceptionOr<bool> Internals::pauseTransitionAtTimeOnPseudoElement(const String& property, double pauseTime, Element& element, const String& pseudoId)
1037 {
1038     if (pauseTime < 0)
1039         return Exception { InvalidAccessError };
1040
1041     if (pseudoId != "before" && pseudoId != "after")
1042         return Exception { InvalidAccessError };
1043
1044     PseudoElement* pseudoElement = pseudoId == "before" ? element.beforePseudoElement() : element.afterPseudoElement();
1045     if (!pseudoElement)
1046         return Exception { InvalidAccessError };
1047
1048     return frame()->animation().pauseTransitionAtTime(*pseudoElement, property, pauseTime);
1049 }
1050
1051 ExceptionOr<RefPtr<Element>> Internals::pseudoElement(Element& element, const String& pseudoId)
1052 {
1053     if (pseudoId != "before" && pseudoId != "after")
1054         return Exception { InvalidAccessError };
1055
1056     return pseudoId == "before" ? element.beforePseudoElement() : element.afterPseudoElement();
1057 }
1058
1059 ExceptionOr<String> Internals::elementRenderTreeAsText(Element& element)
1060 {
1061     element.document().updateStyleIfNeeded();
1062
1063     String representation = externalRepresentation(&element);
1064     if (representation.isEmpty())
1065         return Exception { InvalidAccessError };
1066
1067     return WTFMove(representation);
1068 }
1069
1070 bool Internals::hasPausedImageAnimations(Element& element)
1071 {
1072     return element.renderer() && element.renderer()->hasPausedImageAnimations();
1073 }
1074     
1075 bool Internals::isPaintingFrequently(Element& element)
1076 {
1077     return element.renderer() && element.renderer()->enclosingLayer() && element.renderer()->enclosingLayer()->paintingFrequently();
1078 }
1079
1080 void Internals::incrementFrequentPaintCounter(Element& element)
1081 {
1082     if (element.renderer() && element.renderer()->enclosingLayer())
1083         element.renderer()->enclosingLayer()->simulateFrequentPaint();
1084 }
1085
1086 Ref<CSSComputedStyleDeclaration> Internals::computedStyleIncludingVisitedInfo(Element& element) const
1087 {
1088     bool allowVisitedStyle = true;
1089     return CSSComputedStyleDeclaration::create(element, allowVisitedStyle);
1090 }
1091
1092 Node* Internals::ensureUserAgentShadowRoot(Element& host)
1093 {
1094     return &host.ensureUserAgentShadowRoot();
1095 }
1096
1097 Node* Internals::shadowRoot(Element& host)
1098 {
1099     return host.shadowRoot();
1100 }
1101
1102 ExceptionOr<String> Internals::shadowRootType(const Node& root) const
1103 {
1104     if (!is<ShadowRoot>(root))
1105         return Exception { InvalidAccessError };
1106
1107     switch (downcast<ShadowRoot>(root).mode()) {
1108     case ShadowRootMode::UserAgent:
1109         return String("UserAgentShadowRoot");
1110     case ShadowRootMode::Closed:
1111         return String("ClosedShadowRoot");
1112     case ShadowRootMode::Open:
1113         return String("OpenShadowRoot");
1114     default:
1115         ASSERT_NOT_REACHED();
1116         return String("Unknown");
1117     }
1118 }
1119
1120 String Internals::shadowPseudoId(Element& element)
1121 {
1122     return element.shadowPseudoId().string();
1123 }
1124
1125 void Internals::setShadowPseudoId(Element& element, const String& id)
1126 {
1127     return element.setPseudo(id);
1128 }
1129
1130 static unsigned deferredStyleRulesCountForList(const Vector<RefPtr<StyleRuleBase>>& childRules)
1131 {
1132     unsigned count = 0;
1133     for (auto rule : childRules) {
1134         if (is<StyleRule>(rule)) {
1135             auto* cssRule = downcast<StyleRule>(rule.get());
1136             if (!cssRule->propertiesWithoutDeferredParsing())
1137                 count++;
1138             continue;
1139         }
1140
1141         StyleRuleGroup* groupRule = nullptr;
1142         if (is<StyleRuleMedia>(rule))
1143             groupRule = downcast<StyleRuleMedia>(rule.get());
1144         else if (is<StyleRuleSupports>(rule))
1145             groupRule = downcast<StyleRuleSupports>(rule.get());
1146         if (!groupRule)
1147             continue;
1148
1149         auto* groupChildRules = groupRule->childRulesWithoutDeferredParsing();
1150         if (!groupChildRules)
1151             continue;
1152
1153         count += deferredStyleRulesCountForList(*groupChildRules);
1154     }
1155
1156     return count;
1157 }
1158
1159 unsigned Internals::deferredStyleRulesCount(StyleSheet& styleSheet)
1160 {
1161     return deferredStyleRulesCountForList(downcast<CSSStyleSheet>(styleSheet).contents().childRules());
1162 }
1163
1164 static unsigned deferredGroupRulesCountForList(const Vector<RefPtr<StyleRuleBase>>& childRules)
1165 {
1166     unsigned count = 0;
1167     for (auto rule : childRules) {
1168         StyleRuleGroup* groupRule = nullptr;
1169         if (is<StyleRuleMedia>(rule))
1170             groupRule = downcast<StyleRuleMedia>(rule.get());
1171         else if (is<StyleRuleSupports>(rule))
1172             groupRule = downcast<StyleRuleSupports>(rule.get());
1173         if (!groupRule)
1174             continue;
1175
1176         auto* groupChildRules = groupRule->childRulesWithoutDeferredParsing();
1177         if (!groupChildRules)
1178             count++;
1179         else
1180             count += deferredGroupRulesCountForList(*groupChildRules);
1181     }
1182     return count;
1183 }
1184
1185 unsigned Internals::deferredGroupRulesCount(StyleSheet& styleSheet)
1186 {
1187     return deferredGroupRulesCountForList(downcast<CSSStyleSheet>(styleSheet).contents().childRules());
1188 }
1189
1190 static unsigned deferredKeyframesRulesCountForList(const Vector<RefPtr<StyleRuleBase>>& childRules)
1191 {
1192     unsigned count = 0;
1193     for (auto rule : childRules) {
1194         if (is<StyleRuleKeyframes>(rule)) {
1195             auto* cssRule = downcast<StyleRuleKeyframes>(rule.get());
1196             if (!cssRule->keyframesWithoutDeferredParsing())
1197                 count++;
1198             continue;
1199         }
1200
1201         StyleRuleGroup* groupRule = nullptr;
1202         if (is<StyleRuleMedia>(rule))
1203             groupRule = downcast<StyleRuleMedia>(rule.get());
1204         else if (is<StyleRuleSupports>(rule))
1205             groupRule = downcast<StyleRuleSupports>(rule.get());
1206         if (!groupRule)
1207             continue;
1208
1209         auto* groupChildRules = groupRule->childRulesWithoutDeferredParsing();
1210         if (!groupChildRules)
1211             continue;
1212
1213         count += deferredKeyframesRulesCountForList(*groupChildRules);
1214     }
1215
1216     return count;
1217 }
1218
1219 unsigned Internals::deferredKeyframesRulesCount(StyleSheet& styleSheet)
1220 {
1221     StyleSheetContents& contents = downcast<CSSStyleSheet>(styleSheet).contents();
1222     return deferredKeyframesRulesCountForList(contents.childRules());
1223 }
1224
1225 ExceptionOr<bool> Internals::isTimerThrottled(int timeoutId)
1226 {
1227     auto* timer = scriptExecutionContext()->findTimeout(timeoutId);
1228     if (!timer)
1229         return Exception { NotFoundError };
1230
1231     if (timer->intervalClampedToMinimum() > timer->m_originalInterval)
1232         return true;
1233
1234     return !!timer->alignedFireTime(MonotonicTime { });
1235 }
1236
1237 bool Internals::isRequestAnimationFrameThrottled() const
1238 {
1239     auto* scriptedAnimationController = contextDocument()->scriptedAnimationController();
1240     if (!scriptedAnimationController)
1241         return false;
1242     return scriptedAnimationController->isThrottled();
1243 }
1244
1245 double Internals::requestAnimationFrameInterval() const
1246 {
1247     auto* scriptedAnimationController = contextDocument()->scriptedAnimationController();
1248     if (!scriptedAnimationController)
1249         return INFINITY;
1250     return scriptedAnimationController->interval().value();
1251 }
1252
1253 bool Internals::scriptedAnimationsAreSuspended() const
1254 {
1255     Document* document = contextDocument();
1256     if (!document || !document->page())
1257         return true;
1258
1259     return document->page()->scriptedAnimationsSuspended();
1260 }
1261
1262 bool Internals::areTimersThrottled() const
1263 {
1264     return contextDocument()->isTimerThrottlingEnabled();
1265 }
1266
1267 void Internals::setEventThrottlingBehaviorOverride(std::optional<EventThrottlingBehavior> value)
1268 {
1269     Document* document = contextDocument();
1270     if (!document || !document->page())
1271         return;
1272
1273     if (!value) {
1274         document->page()->setEventThrottlingBehaviorOverride(std::nullopt);
1275         return;
1276     }
1277
1278     switch (value.value()) {
1279     case Internals::EventThrottlingBehavior::Responsive:
1280         document->page()->setEventThrottlingBehaviorOverride(WebCore::EventThrottlingBehavior::Responsive);
1281         break;
1282     case Internals::EventThrottlingBehavior::Unresponsive:
1283         document->page()->setEventThrottlingBehaviorOverride(WebCore::EventThrottlingBehavior::Unresponsive);
1284         break;
1285     }
1286 }
1287
1288 std::optional<Internals::EventThrottlingBehavior> Internals::eventThrottlingBehaviorOverride() const
1289 {
1290     Document* document = contextDocument();
1291     if (!document || !document->page())
1292         return std::nullopt;
1293
1294     auto behavior = document->page()->eventThrottlingBehaviorOverride();
1295     if (!behavior)
1296         return std::nullopt;
1297
1298     switch (behavior.value()) {
1299     case WebCore::EventThrottlingBehavior::Responsive:
1300         return Internals::EventThrottlingBehavior::Responsive;
1301     case WebCore::EventThrottlingBehavior::Unresponsive:
1302         return Internals::EventThrottlingBehavior::Unresponsive;
1303     }
1304
1305     return std::nullopt;
1306 }
1307
1308 String Internals::visiblePlaceholder(Element& element)
1309 {
1310     if (is<HTMLTextFormControlElement>(element)) {
1311         const HTMLTextFormControlElement& textFormControlElement = downcast<HTMLTextFormControlElement>(element);
1312         if (!textFormControlElement.isPlaceholderVisible())
1313             return String();
1314         if (HTMLElement* placeholderElement = textFormControlElement.placeholderElement())
1315             return placeholderElement->textContent();
1316     }
1317
1318     return String();
1319 }
1320
1321 void Internals::selectColorInColorChooser(HTMLInputElement& element, const String& colorValue)
1322 {
1323     element.selectColor(colorValue);
1324 }
1325
1326 ExceptionOr<Vector<String>> Internals::formControlStateOfPreviousHistoryItem()
1327 {
1328     HistoryItem* mainItem = frame()->loader().history().previousItem();
1329     if (!mainItem)
1330         return Exception { InvalidAccessError };
1331     String uniqueName = frame()->tree().uniqueName();
1332     if (mainItem->target() != uniqueName && !mainItem->childItemWithTarget(uniqueName))
1333         return Exception { InvalidAccessError };
1334     return Vector<String> { mainItem->target() == uniqueName ? mainItem->documentState() : mainItem->childItemWithTarget(uniqueName)->documentState() };
1335 }
1336
1337 ExceptionOr<void> Internals::setFormControlStateOfPreviousHistoryItem(const Vector<String>& state)
1338 {
1339     HistoryItem* mainItem = frame()->loader().history().previousItem();
1340     if (!mainItem)
1341         return Exception { InvalidAccessError };
1342     String uniqueName = frame()->tree().uniqueName();
1343     if (mainItem->target() == uniqueName)
1344         mainItem->setDocumentState(state);
1345     else if (HistoryItem* subItem = mainItem->childItemWithTarget(uniqueName))
1346         subItem->setDocumentState(state);
1347     else
1348         return Exception { InvalidAccessError };
1349     return { };
1350 }
1351
1352 #if ENABLE(SPEECH_SYNTHESIS)
1353
1354 void Internals::enableMockSpeechSynthesizer()
1355 {
1356     Document* document = contextDocument();
1357     if (!document || !document->domWindow())
1358         return;
1359     SpeechSynthesis* synthesis = DOMWindowSpeechSynthesis::speechSynthesis(*document->domWindow());
1360     if (!synthesis)
1361         return;
1362
1363     synthesis->setPlatformSynthesizer(std::make_unique<PlatformSpeechSynthesizerMock>(synthesis));
1364 }
1365
1366 #endif
1367
1368 #if ENABLE(WEB_RTC)
1369
1370 void Internals::emulateRTCPeerConnectionPlatformEvent(RTCPeerConnection& connection, const String& action)
1371 {
1372     if (!LibWebRTCProvider::webRTCAvailable())
1373         return;
1374
1375     connection.emulatePlatformEvent(action);
1376 }
1377
1378 void Internals::useMockRTCPeerConnectionFactory(const String& testCase)
1379 {
1380     if (!LibWebRTCProvider::webRTCAvailable())
1381         return;
1382
1383 #if USE(LIBWEBRTC)
1384     Document* document = contextDocument();
1385     LibWebRTCProvider* provider = (document && document->page()) ? &document->page()->libWebRTCProvider() : nullptr;
1386     WebCore::useMockRTCPeerConnectionFactory(provider, testCase);
1387 #else
1388     UNUSED_PARAM(testCase);
1389 #endif
1390 }
1391
1392 void Internals::setICECandidateFiltering(bool enabled)
1393 {
1394     auto* page = contextDocument()->page();
1395     if (!page)
1396         return;
1397
1398     auto& rtcController = page->rtcController();
1399     if (enabled)
1400         rtcController.enableICECandidateFiltering();
1401     else
1402         rtcController.disableICECandidateFilteringForAllOrigins();
1403 }
1404
1405 void Internals::setEnumeratingAllNetworkInterfacesEnabled(bool enabled)
1406 {
1407 #if USE(LIBWEBRTC)
1408     Document* document = contextDocument();
1409     auto* page = document->page();
1410     if (!page)
1411         return;
1412     auto& rtcProvider = page->libWebRTCProvider();
1413     if (enabled)
1414         rtcProvider.enableEnumeratingAllNetworkInterfaces();
1415     else
1416         rtcProvider.disableEnumeratingAllNetworkInterfaces();
1417 #else
1418     UNUSED_PARAM(enabled);
1419 #endif
1420 }
1421
1422 void Internals::stopPeerConnection(RTCPeerConnection& connection)
1423 {
1424     ActiveDOMObject& object = connection;
1425     object.stop();
1426 }
1427
1428 void Internals::applyRotationForOutgoingVideoSources(RTCPeerConnection& connection)
1429 {
1430     connection.applyRotationForOutgoingVideoSources();
1431 }
1432 #endif
1433
1434 #if ENABLE(MEDIA_STREAM)
1435
1436 void Internals::setMockMediaCaptureDevicesEnabled(bool enabled)
1437 {
1438     WebCore::DeprecatedGlobalSettings::setMockCaptureDevicesEnabled(enabled);
1439 }
1440
1441 #endif
1442
1443 ExceptionOr<Ref<DOMRect>> Internals::absoluteCaretBounds()
1444 {
1445     Document* document = contextDocument();
1446     if (!document || !document->frame())
1447         return Exception { InvalidAccessError };
1448
1449     return DOMRect::create(document->frame()->selection().absoluteCaretBounds());
1450 }
1451
1452 Ref<DOMRect> Internals::boundingBox(Element& element)
1453 {
1454     element.document().updateLayoutIgnorePendingStylesheets();
1455     auto renderer = element.renderer();
1456     if (!renderer)
1457         return DOMRect::create();
1458     return DOMRect::create(renderer->absoluteBoundingBoxRectIgnoringTransforms());
1459 }
1460
1461 ExceptionOr<Ref<DOMRectList>> Internals::inspectorHighlightRects()
1462 {
1463     Document* document = contextDocument();
1464     if (!document || !document->page())
1465         return Exception { InvalidAccessError };
1466
1467     Highlight highlight;
1468     document->page()->inspectorController().getHighlight(highlight, InspectorOverlay::CoordinateSystem::View);
1469     return DOMRectList::create(highlight.quads);
1470 }
1471
1472 ExceptionOr<String> Internals::inspectorHighlightObject()
1473 {
1474     Document* document = contextDocument();
1475     if (!document || !document->page())
1476         return Exception { InvalidAccessError };
1477
1478     return document->page()->inspectorController().buildObjectForHighlightedNodes()->toJSONString();
1479 }
1480
1481 ExceptionOr<unsigned> Internals::markerCountForNode(Node& node, const String& markerType)
1482 {
1483     OptionSet<DocumentMarker::MarkerType> markerTypes;
1484     if (!markerTypesFrom(markerType, markerTypes))
1485         return Exception { SyntaxError };
1486
1487     node.document().frame()->editor().updateEditorUINowIfScheduled();
1488     return node.document().markers().markersFor(&node, markerTypes).size();
1489 }
1490
1491 ExceptionOr<RenderedDocumentMarker*> Internals::markerAt(Node& node, const String& markerType, unsigned index)
1492 {
1493     node.document().updateLayoutIgnorePendingStylesheets();
1494
1495     OptionSet<DocumentMarker::MarkerType> markerTypes;
1496     if (!markerTypesFrom(markerType, markerTypes))
1497         return Exception { SyntaxError };
1498
1499     node.document().frame()->editor().updateEditorUINowIfScheduled();
1500
1501     Vector<RenderedDocumentMarker*> markers = node.document().markers().markersFor(&node, markerTypes);
1502     if (markers.size() <= index)
1503         return nullptr;
1504     return markers[index];
1505 }
1506
1507 ExceptionOr<RefPtr<Range>> Internals::markerRangeForNode(Node& node, const String& markerType, unsigned index)
1508 {
1509     auto result = markerAt(node, markerType, index);
1510     if (result.hasException())
1511         return result.releaseException();
1512     auto marker = result.releaseReturnValue();
1513     if (!marker)
1514         return nullptr;
1515     return RefPtr<Range> { Range::create(node.document(), &node, marker->startOffset(), &node, marker->endOffset()) };
1516 }
1517
1518 ExceptionOr<String> Internals::markerDescriptionForNode(Node& node, const String& markerType, unsigned index)
1519 {
1520     auto result = markerAt(node, markerType, index);
1521     if (result.hasException())
1522         return result.releaseException();
1523     auto marker = result.releaseReturnValue();
1524     if (!marker)
1525         return String();
1526     return String { marker->description() };
1527 }
1528
1529 ExceptionOr<String> Internals::dumpMarkerRects(const String& markerTypeString)
1530 {
1531     DocumentMarker::MarkerType markerType;
1532     if (!markerTypeFrom(markerTypeString, markerType))
1533         return Exception { SyntaxError };
1534
1535     contextDocument()->markers().updateRectsForInvalidatedMarkersOfType(markerType);
1536     auto rects = contextDocument()->markers().renderedRectsForMarkers(markerType);
1537
1538     StringBuilder rectString;
1539     rectString.appendLiteral("marker rects: ");
1540     for (const auto& rect : rects) {
1541         rectString.append('(');
1542         rectString.appendNumber(rect.x());
1543         rectString.appendLiteral(", ");
1544         rectString.appendNumber(rect.y());
1545         rectString.appendLiteral(", ");
1546         rectString.appendNumber(rect.width());
1547         rectString.appendLiteral(", ");
1548         rectString.appendNumber(rect.height());
1549         rectString.appendLiteral(") ");
1550     }
1551     return rectString.toString();
1552 }
1553
1554 void Internals::addTextMatchMarker(const Range& range, bool isActive)
1555 {
1556     range.ownerDocument().updateLayoutIgnorePendingStylesheets();
1557     range.ownerDocument().markers().addTextMatchMarker(&range, isActive);
1558 }
1559
1560 ExceptionOr<void> Internals::setMarkedTextMatchesAreHighlighted(bool flag)
1561 {
1562     Document* document = contextDocument();
1563     if (!document || !document->frame())
1564         return Exception { InvalidAccessError };
1565     document->frame()->editor().setMarkedTextMatchesAreHighlighted(flag);
1566     return { };
1567 }
1568
1569 void Internals::invalidateFontCache()
1570 {
1571     FontCache::singleton().invalidate();
1572 }
1573
1574 void Internals::setFontSmoothingEnabled(bool enabled)
1575 {
1576     WebCore::FontCascade::setShouldUseSmoothing(enabled);
1577 }
1578
1579 ExceptionOr<void> Internals::setLowPowerModeEnabled(bool isEnabled)
1580 {
1581     auto* document = contextDocument();
1582     if (!document)
1583         return Exception { InvalidAccessError };
1584     auto* page = document->page();
1585     if (!page)
1586         return Exception { InvalidAccessError };
1587
1588     page->setLowPowerModeEnabledOverrideForTesting(isEnabled);
1589     return { };
1590 }
1591
1592 ExceptionOr<void> Internals::setScrollViewPosition(int x, int y)
1593 {
1594     Document* document = contextDocument();
1595     if (!document || !document->view())
1596         return Exception { InvalidAccessError };
1597
1598     auto& frameView = *document->view();
1599     bool constrainsScrollingToContentEdgeOldValue = frameView.constrainsScrollingToContentEdge();
1600     bool scrollbarsSuppressedOldValue = frameView.scrollbarsSuppressed();
1601
1602     frameView.setConstrainsScrollingToContentEdge(false);
1603     frameView.setScrollbarsSuppressed(false);
1604     frameView.setScrollOffsetFromInternals({ x, y });
1605     frameView.setScrollbarsSuppressed(scrollbarsSuppressedOldValue);
1606     frameView.setConstrainsScrollingToContentEdge(constrainsScrollingToContentEdgeOldValue);
1607
1608     return { };
1609 }
1610
1611 ExceptionOr<void> Internals::unconstrainedScrollTo(Element& element, double x, double y)
1612 {
1613     Document* document = contextDocument();
1614     if (!document || !document->view())
1615         return Exception { InvalidAccessError };
1616
1617     element.scrollTo({ x, y }, ScrollClamping::Unclamped);
1618     return { };
1619 }
1620
1621 ExceptionOr<Ref<DOMRect>> Internals::layoutViewportRect()
1622 {
1623     Document* document = contextDocument();
1624     if (!document || !document->frame())
1625         return Exception { InvalidAccessError };
1626
1627     document->updateLayoutIgnorePendingStylesheets();
1628
1629     auto& frameView = *document->view();
1630     return DOMRect::create(frameView.layoutViewportRect());
1631 }
1632
1633 ExceptionOr<Ref<DOMRect>> Internals::visualViewportRect()
1634 {
1635     Document* document = contextDocument();
1636     if (!document || !document->frame())
1637         return Exception { InvalidAccessError };
1638
1639     document->updateLayoutIgnorePendingStylesheets();
1640
1641     auto& frameView = *document->view();
1642     return DOMRect::create(frameView.visualViewportRect());
1643 }
1644
1645 ExceptionOr<void> Internals::setViewBaseBackgroundColor(const String& colorValue)
1646 {
1647     Document* document = contextDocument();
1648     if (!document || !document->view())
1649         return Exception { InvalidAccessError };
1650
1651     if (colorValue == "transparent") {
1652         document->view()->setBaseBackgroundColor(Color::transparent);
1653         return { };
1654     }
1655     if (colorValue == "white") {
1656         document->view()->setBaseBackgroundColor(Color::white);
1657         return { };
1658     }
1659     return Exception { SyntaxError };
1660 }
1661
1662 ExceptionOr<void> Internals::setPagination(const String& mode, int gap, int pageLength)
1663 {
1664     Document* document = contextDocument();
1665     if (!document || !document->page())
1666         return Exception { InvalidAccessError };
1667
1668     Pagination pagination;
1669     if (mode == "Unpaginated")
1670         pagination.mode = Pagination::Unpaginated;
1671     else if (mode == "LeftToRightPaginated")
1672         pagination.mode = Pagination::LeftToRightPaginated;
1673     else if (mode == "RightToLeftPaginated")
1674         pagination.mode = Pagination::RightToLeftPaginated;
1675     else if (mode == "TopToBottomPaginated")
1676         pagination.mode = Pagination::TopToBottomPaginated;
1677     else if (mode == "BottomToTopPaginated")
1678         pagination.mode = Pagination::BottomToTopPaginated;
1679     else
1680         return Exception { SyntaxError };
1681
1682     pagination.gap = gap;
1683     pagination.pageLength = pageLength;
1684     document->page()->setPagination(pagination);
1685
1686     return { };
1687 }
1688
1689 ExceptionOr<void> Internals::setPaginationLineGridEnabled(bool enabled)
1690 {
1691     Document* document = contextDocument();
1692     if (!document || !document->page())
1693         return Exception { InvalidAccessError };
1694     document->page()->setPaginationLineGridEnabled(enabled);
1695     return { };
1696 }
1697
1698 ExceptionOr<String> Internals::configurationForViewport(float devicePixelRatio, int deviceWidth, int deviceHeight, int availableWidth, int availableHeight)
1699 {
1700     Document* document = contextDocument();
1701     if (!document || !document->page())
1702         return Exception { InvalidAccessError };
1703
1704     const int defaultLayoutWidthForNonMobilePages = 980;
1705
1706     ViewportArguments arguments = document->page()->viewportArguments();
1707     ViewportAttributes attributes = computeViewportAttributes(arguments, defaultLayoutWidthForNonMobilePages, deviceWidth, deviceHeight, devicePixelRatio, IntSize(availableWidth, availableHeight));
1708     restrictMinimumScaleFactorToViewportSize(attributes, IntSize(availableWidth, availableHeight), devicePixelRatio);
1709     restrictScaleFactorToInitialScaleIfNotUserScalable(attributes);
1710
1711     return String { "viewport size " + String::number(attributes.layoutSize.width()) + "x" + String::number(attributes.layoutSize.height()) + " scale " + String::number(attributes.initialScale) + " with limits [" + String::number(attributes.minimumScale) + ", " + String::number(attributes.maximumScale) + "] and userScalable " + (attributes.userScalable ? "true" : "false") };
1712 }
1713
1714 ExceptionOr<bool> Internals::wasLastChangeUserEdit(Element& textField)
1715 {
1716     if (is<HTMLInputElement>(textField))
1717         return downcast<HTMLInputElement>(textField).lastChangeWasUserEdit();
1718
1719     if (is<HTMLTextAreaElement>(textField))
1720         return downcast<HTMLTextAreaElement>(textField).lastChangeWasUserEdit();
1721
1722     return Exception { InvalidNodeTypeError };
1723 }
1724
1725 bool Internals::elementShouldAutoComplete(HTMLInputElement& element)
1726 {
1727     return element.shouldAutocomplete();
1728 }
1729
1730 void Internals::setEditingValue(HTMLInputElement& element, const String& value)
1731 {
1732     element.setEditingValue(value);
1733 }
1734
1735 void Internals::setAutofilled(HTMLInputElement& element, bool enabled)
1736 {
1737     element.setAutoFilled(enabled);
1738 }
1739
1740 static AutoFillButtonType toAutoFillButtonType(Internals::AutoFillButtonType type)
1741 {
1742     switch (type) {
1743     case Internals::AutoFillButtonType::None:
1744         return AutoFillButtonType::None;
1745     case Internals::AutoFillButtonType::Credentials:
1746         return AutoFillButtonType::Credentials;
1747     case Internals::AutoFillButtonType::Contacts:
1748         return AutoFillButtonType::Contacts;
1749     case Internals::AutoFillButtonType::StrongConfirmationPassword:
1750         return AutoFillButtonType::StrongConfirmationPassword;
1751     case Internals::AutoFillButtonType::StrongPassword:
1752         return AutoFillButtonType::StrongPassword;
1753     }
1754     ASSERT_NOT_REACHED();
1755     return AutoFillButtonType::None;
1756 }
1757
1758 static Internals::AutoFillButtonType toInternalsAutoFillButtonType(AutoFillButtonType type)
1759 {
1760     switch (type) {
1761     case AutoFillButtonType::None:
1762         return Internals::AutoFillButtonType::None;
1763     case AutoFillButtonType::Credentials:
1764         return Internals::AutoFillButtonType::Credentials;
1765     case AutoFillButtonType::Contacts:
1766         return Internals::AutoFillButtonType::Contacts;
1767     case AutoFillButtonType::StrongConfirmationPassword:
1768         return Internals::AutoFillButtonType::StrongConfirmationPassword;
1769    case AutoFillButtonType::StrongPassword:
1770         return Internals::AutoFillButtonType::StrongPassword;
1771     }
1772     ASSERT_NOT_REACHED();
1773     return Internals::AutoFillButtonType::None;
1774 }
1775
1776 void Internals::setShowAutoFillButton(HTMLInputElement& element, AutoFillButtonType type)
1777 {
1778     element.setShowAutoFillButton(toAutoFillButtonType(type));
1779 }
1780
1781 auto Internals::autoFillButtonType(const HTMLInputElement& element) -> AutoFillButtonType
1782 {
1783     return toInternalsAutoFillButtonType(element.autoFillButtonType());
1784 }
1785
1786 auto Internals::lastAutoFillButtonType(const HTMLInputElement& element) -> AutoFillButtonType
1787 {
1788     return toInternalsAutoFillButtonType(element.lastAutoFillButtonType());
1789 }
1790
1791 ExceptionOr<void> Internals::scrollElementToRect(Element& element, int x, int y, int w, int h)
1792 {
1793     FrameView* frameView = element.document().view();
1794     if (!frameView)
1795         return Exception { InvalidAccessError };
1796     frameView->scrollElementToRect(element, { x, y, w, h });
1797     return { };
1798 }
1799
1800 ExceptionOr<String> Internals::autofillFieldName(Element& element)
1801 {
1802     if (!is<HTMLFormControlElement>(element))
1803         return Exception { InvalidNodeTypeError };
1804
1805     return String { downcast<HTMLFormControlElement>(element).autofillData().fieldName };
1806 }
1807
1808 ExceptionOr<void> Internals::paintControlTints()
1809 {
1810     Document* document = contextDocument();
1811     if (!document || !document->view())
1812         return Exception { InvalidAccessError };
1813
1814     document->view()->paintControlTints();
1815     return { };
1816 }
1817
1818 RefPtr<Range> Internals::rangeFromLocationAndLength(Element& scope, int rangeLocation, int rangeLength)
1819 {
1820     return TextIterator::rangeFromLocationAndLength(&scope, rangeLocation, rangeLength);
1821 }
1822
1823 unsigned Internals::locationFromRange(Element& scope, const Range& range)
1824 {
1825     size_t location = 0;
1826     size_t unusedLength = 0;
1827     TextIterator::getLocationAndLengthFromRange(&scope, &range, location, unusedLength);
1828     return location;
1829 }
1830
1831 unsigned Internals::lengthFromRange(Element& scope, const Range& range)
1832 {
1833     size_t unusedLocation = 0;
1834     size_t length = 0;
1835     TextIterator::getLocationAndLengthFromRange(&scope, &range, unusedLocation, length);
1836     return length;
1837 }
1838
1839 String Internals::rangeAsText(const Range& range)
1840 {
1841     return range.text();
1842 }
1843
1844 Ref<Range> Internals::subrange(Range& range, int rangeLocation, int rangeLength)
1845 {
1846     return TextIterator::subrange(range, rangeLocation, rangeLength);
1847 }
1848
1849 RefPtr<Range> Internals::rangeOfStringNearLocation(const Range& searchRange, const String& text, unsigned targetOffset)
1850 {
1851     return findClosestPlainText(searchRange, text, { }, targetOffset);
1852 }
1853
1854 ExceptionOr<RefPtr<Range>> Internals::rangeForDictionaryLookupAtLocation(int x, int y)
1855 {
1856 #if PLATFORM(MAC)
1857     auto* document = contextDocument();
1858     if (!document || !document->frame())
1859         return Exception { InvalidAccessError };
1860
1861     document->updateLayoutIgnorePendingStylesheets();
1862
1863     HitTestResult result = document->frame()->mainFrame().eventHandler().hitTestResultAtPoint(IntPoint(x, y));
1864     return DictionaryLookup::rangeAtHitTestResult(result, nullptr);
1865 #else
1866     UNUSED_PARAM(x);
1867     UNUSED_PARAM(y);
1868     return Exception { InvalidAccessError };
1869 #endif
1870 }
1871
1872 ExceptionOr<void> Internals::setDelegatesScrolling(bool enabled)
1873 {
1874     Document* document = contextDocument();
1875     // Delegate scrolling is valid only on mainframe's view.
1876     if (!document || !document->view() || !document->page() || &document->page()->mainFrame() != document->frame())
1877         return Exception { InvalidAccessError };
1878
1879     document->view()->setDelegatesScrolling(enabled);
1880     return { };
1881 }
1882
1883 ExceptionOr<int> Internals::lastSpellCheckRequestSequence()
1884 {
1885     Document* document = contextDocument();
1886     if (!document || !document->frame())
1887         return Exception { InvalidAccessError };
1888
1889     return document->frame()->editor().spellChecker().lastRequestSequence();
1890 }
1891
1892 ExceptionOr<int> Internals::lastSpellCheckProcessedSequence()
1893 {
1894     Document* document = contextDocument();
1895     if (!document || !document->frame())
1896         return Exception { InvalidAccessError };
1897
1898     return document->frame()->editor().spellChecker().lastProcessedSequence();
1899 }
1900
1901 Vector<String> Internals::userPreferredLanguages() const
1902 {
1903     return WTF::userPreferredLanguages();
1904 }
1905
1906 void Internals::setUserPreferredLanguages(const Vector<String>& languages)
1907 {
1908     overrideUserPreferredLanguages(languages);
1909 }
1910
1911 Vector<String> Internals::userPreferredAudioCharacteristics() const
1912 {
1913     Document* document = contextDocument();
1914     if (!document || !document->page())
1915         return Vector<String>();
1916 #if ENABLE(VIDEO_TRACK)
1917     return document->page()->group().captionPreferences().preferredAudioCharacteristics();
1918 #else
1919     return Vector<String>();
1920 #endif
1921 }
1922
1923 void Internals::setUserPreferredAudioCharacteristic(const String& characteristic)
1924 {
1925     Document* document = contextDocument();
1926     if (!document || !document->page())
1927         return;
1928 #if ENABLE(VIDEO_TRACK)
1929     document->page()->group().captionPreferences().setPreferredAudioCharacteristic(characteristic);
1930 #else
1931     UNUSED_PARAM(characteristic);
1932 #endif
1933 }
1934
1935 ExceptionOr<unsigned> Internals::wheelEventHandlerCount()
1936 {
1937     Document* document = contextDocument();
1938     if (!document)
1939         return Exception { InvalidAccessError };
1940
1941     return document->wheelEventHandlerCount();
1942 }
1943
1944 ExceptionOr<unsigned> Internals::touchEventHandlerCount()
1945 {
1946     Document* document = contextDocument();
1947     if (!document)
1948         return Exception { InvalidAccessError };
1949
1950     return document->touchEventHandlerCount();
1951 }
1952
1953 ExceptionOr<Ref<DOMRectList>> Internals::touchEventRectsForEvent(const String& eventName)
1954 {
1955     Document* document = contextDocument();
1956     if (!document || !document->page())
1957         return Exception { InvalidAccessError };
1958
1959     return document->page()->touchEventRectsForEvent(eventName);
1960 }
1961
1962 ExceptionOr<Ref<DOMRectList>> Internals::passiveTouchEventListenerRects()
1963 {
1964     Document* document = contextDocument();
1965     if (!document || !document->page())
1966         return Exception { InvalidAccessError };
1967
1968     return document->page()->passiveTouchEventListenerRects();
1969 }
1970
1971 // FIXME: Remove the document argument. It is almost always the same as
1972 // contextDocument(), with the exception of a few tests that pass a
1973 // different document, and could just make the call through another Internals
1974 // instance instead.
1975 ExceptionOr<RefPtr<NodeList>> Internals::nodesFromRect(Document& document, int centerX, int centerY, unsigned topPadding, unsigned rightPadding, unsigned bottomPadding, unsigned leftPadding, bool ignoreClipping, bool allowUserAgentShadowContent, bool allowChildFrameContent) const
1976 {
1977     if (!document.frame() || !document.frame()->view())
1978         return Exception { InvalidAccessError };
1979
1980     Frame* frame = document.frame();
1981     FrameView* frameView = document.view();
1982     RenderView* renderView = document.renderView();
1983     if (!renderView)
1984         return nullptr;
1985
1986     document.updateLayoutIgnorePendingStylesheets();
1987
1988     float zoomFactor = frame->pageZoomFactor();
1989     LayoutPoint point(centerX * zoomFactor + frameView->scrollX(), centerY * zoomFactor + frameView->scrollY());
1990
1991     HitTestRequest::HitTestRequestType hitType = HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::CollectMultipleElements;
1992     if (ignoreClipping)
1993         hitType |= HitTestRequest::IgnoreClipping;
1994     if (!allowUserAgentShadowContent)
1995         hitType |= HitTestRequest::DisallowUserAgentShadowContent;
1996     if (allowChildFrameContent)
1997         hitType |= HitTestRequest::AllowChildFrameContent;
1998
1999     HitTestRequest request(hitType);
2000
2001     // When ignoreClipping is false, this method returns null for coordinates outside of the viewport.
2002     if (!request.ignoreClipping() && !frameView->visibleContentRect().intersects(HitTestLocation::rectForPoint(point, topPadding, rightPadding, bottomPadding, leftPadding)))
2003         return nullptr;
2004
2005     HitTestResult result(point, topPadding, rightPadding, bottomPadding, leftPadding);
2006     renderView->hitTest(request, result);
2007     const HitTestResult::NodeSet& nodeSet = result.listBasedTestResult();
2008     Vector<Ref<Node>> matches;
2009     matches.reserveInitialCapacity(nodeSet.size());
2010     for (auto& node : nodeSet)
2011         matches.uncheckedAppend(*node);
2012
2013     return RefPtr<NodeList> { StaticNodeList::create(WTFMove(matches)) };
2014 }
2015
2016 class GetCallerCodeBlockFunctor {
2017 public:
2018     GetCallerCodeBlockFunctor()
2019         : m_iterations(0)
2020         , m_codeBlock(0)
2021     {
2022     }
2023
2024     StackVisitor::Status operator()(StackVisitor& visitor) const
2025     {
2026         ++m_iterations;
2027         if (m_iterations < 2)
2028             return StackVisitor::Continue;
2029
2030         m_codeBlock = visitor->codeBlock();
2031         return StackVisitor::Done;
2032     }
2033
2034     CodeBlock* codeBlock() const { return m_codeBlock; }
2035
2036 private:
2037     mutable int m_iterations;
2038     mutable CodeBlock* m_codeBlock;
2039 };
2040
2041 String Internals::parserMetaData(JSC::JSValue code)
2042 {
2043     JSC::VM& vm = contextDocument()->vm();
2044     JSC::ExecState* exec = vm.topCallFrame;
2045     ScriptExecutable* executable;
2046
2047     if (!code || code.isNull() || code.isUndefined()) {
2048         GetCallerCodeBlockFunctor iter;
2049         exec->iterate(iter);
2050         CodeBlock* codeBlock = iter.codeBlock();
2051         executable = codeBlock->ownerScriptExecutable();
2052     } else if (code.isFunction()) {
2053         JSFunction* funcObj = JSC::jsCast<JSFunction*>(code.toObject(exec));
2054         executable = funcObj->jsExecutable();
2055     } else
2056         return String();
2057
2058     unsigned startLine = executable->firstLine();
2059     unsigned startColumn = executable->startColumn();
2060     unsigned endLine = executable->lastLine();
2061     unsigned endColumn = executable->endColumn();
2062
2063     StringBuilder result;
2064
2065     if (executable->isFunctionExecutable()) {
2066         FunctionExecutable* funcExecutable = reinterpret_cast<FunctionExecutable*>(executable);
2067         String inferredName = funcExecutable->inferredName().string();
2068         result.appendLiteral("function \"");
2069         result.append(inferredName);
2070         result.append('"');
2071     } else if (executable->isEvalExecutable())
2072         result.appendLiteral("eval");
2073     else if (executable->isModuleProgramExecutable())
2074         result.appendLiteral("module");
2075     else if (executable->isProgramExecutable())
2076         result.appendLiteral("program");
2077     else
2078         ASSERT_NOT_REACHED();
2079
2080     result.appendLiteral(" { ");
2081     result.appendNumber(startLine);
2082     result.append(':');
2083     result.appendNumber(startColumn);
2084     result.appendLiteral(" - ");
2085     result.appendNumber(endLine);
2086     result.append(':');
2087     result.appendNumber(endColumn);
2088     result.appendLiteral(" }");
2089
2090     return result.toString();
2091 }
2092
2093 void Internals::updateEditorUINowIfScheduled()
2094 {
2095     if (Document* document = contextDocument()) {
2096         if (Frame* frame = document->frame())
2097             frame->editor().updateEditorUINowIfScheduled();
2098     }
2099 }
2100
2101 bool Internals::hasSpellingMarker(int from, int length)
2102 {
2103     Document* document = contextDocument();
2104     if (!document || !document->frame())
2105         return false;
2106
2107     updateEditorUINowIfScheduled();
2108
2109     return document->frame()->editor().selectionStartHasMarkerFor(DocumentMarker::Spelling, from, length);
2110 }
2111
2112 bool Internals::hasAutocorrectedMarker(int from, int length)
2113 {
2114     Document* document = contextDocument();
2115     if (!document || !document->frame())
2116         return false;
2117
2118     updateEditorUINowIfScheduled();
2119
2120     return document->frame()->editor().selectionStartHasMarkerFor(DocumentMarker::Autocorrected, from, length);
2121 }
2122
2123 void Internals::setContinuousSpellCheckingEnabled(bool enabled)
2124 {
2125     if (!contextDocument() || !contextDocument()->frame())
2126         return;
2127
2128     if (enabled != contextDocument()->frame()->editor().isContinuousSpellCheckingEnabled())
2129         contextDocument()->frame()->editor().toggleContinuousSpellChecking();
2130 }
2131
2132 void Internals::setAutomaticQuoteSubstitutionEnabled(bool enabled)
2133 {
2134     if (!contextDocument() || !contextDocument()->frame())
2135         return;
2136
2137 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
2138     if (enabled != contextDocument()->frame()->editor().isAutomaticQuoteSubstitutionEnabled())
2139         contextDocument()->frame()->editor().toggleAutomaticQuoteSubstitution();
2140 #else
2141     UNUSED_PARAM(enabled);
2142 #endif
2143 }
2144
2145 void Internals::setAutomaticLinkDetectionEnabled(bool enabled)
2146 {
2147     if (!contextDocument() || !contextDocument()->frame())
2148         return;
2149
2150 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
2151     if (enabled != contextDocument()->frame()->editor().isAutomaticLinkDetectionEnabled())
2152         contextDocument()->frame()->editor().toggleAutomaticLinkDetection();
2153 #else
2154     UNUSED_PARAM(enabled);
2155 #endif
2156 }
2157
2158 void Internals::setAutomaticDashSubstitutionEnabled(bool enabled)
2159 {
2160     if (!contextDocument() || !contextDocument()->frame())
2161         return;
2162
2163 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
2164     if (enabled != contextDocument()->frame()->editor().isAutomaticDashSubstitutionEnabled())
2165         contextDocument()->frame()->editor().toggleAutomaticDashSubstitution();
2166 #else
2167     UNUSED_PARAM(enabled);
2168 #endif
2169 }
2170
2171 void Internals::setAutomaticTextReplacementEnabled(bool enabled)
2172 {
2173     if (!contextDocument() || !contextDocument()->frame())
2174         return;
2175
2176 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
2177     if (enabled != contextDocument()->frame()->editor().isAutomaticTextReplacementEnabled())
2178         contextDocument()->frame()->editor().toggleAutomaticTextReplacement();
2179 #else
2180     UNUSED_PARAM(enabled);
2181 #endif
2182 }
2183
2184 void Internals::setAutomaticSpellingCorrectionEnabled(bool enabled)
2185 {
2186     if (!contextDocument() || !contextDocument()->frame())
2187         return;
2188
2189 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
2190     if (enabled != contextDocument()->frame()->editor().isAutomaticSpellingCorrectionEnabled())
2191         contextDocument()->frame()->editor().toggleAutomaticSpellingCorrection();
2192 #else
2193     UNUSED_PARAM(enabled);
2194 #endif
2195 }
2196
2197 void Internals::handleAcceptedCandidate(const String& candidate, unsigned location, unsigned length)
2198 {
2199     if (!contextDocument() || !contextDocument()->frame())
2200         return;
2201
2202     TextCheckingResult result;
2203     result.type = TextCheckingTypeNone;
2204     result.location = location;
2205     result.length = length;
2206     result.replacement = candidate;
2207     contextDocument()->frame()->editor().handleAcceptedCandidate(result);
2208 }
2209
2210 bool Internals::isOverwriteModeEnabled()
2211 {
2212     Document* document = contextDocument();
2213     if (!document || !document->frame())
2214         return false;
2215
2216     return document->frame()->editor().isOverwriteModeEnabled();
2217 }
2218
2219 void Internals::toggleOverwriteModeEnabled()
2220 {
2221     Document* document = contextDocument();
2222     if (!document || !document->frame())
2223         return;
2224
2225     document->frame()->editor().toggleOverwriteModeEnabled();
2226 }
2227
2228 static ExceptionOr<FindOptions> parseFindOptions(const Vector<String>& optionList)
2229 {
2230     const struct {
2231         const char* name;
2232         FindOptionFlag value;
2233     } flagList[] = {
2234         {"CaseInsensitive", CaseInsensitive},
2235         {"AtWordStarts", AtWordStarts},
2236         {"TreatMedialCapitalAsWordStart", TreatMedialCapitalAsWordStart},
2237         {"Backwards", Backwards},
2238         {"WrapAround", WrapAround},
2239         {"StartInSelection", StartInSelection},
2240         {"DoNotRevealSelection", DoNotRevealSelection},
2241         {"AtWordEnds", AtWordEnds},
2242         {"DoNotTraverseFlatTree", DoNotTraverseFlatTree},
2243     };
2244     FindOptions result;
2245     for (auto& option : optionList) {
2246         bool found = false;
2247         for (auto& flag : flagList) {
2248             if (flag.name == option) {
2249                 result |= flag.value;
2250                 found = true;
2251                 break;
2252             }
2253         }
2254         if (!found)
2255             return Exception { SyntaxError };
2256     }
2257     return WTFMove(result);
2258 }
2259
2260 ExceptionOr<RefPtr<Range>> Internals::rangeOfString(const String& text, RefPtr<Range>&& referenceRange, const Vector<String>& findOptions)
2261 {
2262     Document* document = contextDocument();
2263     if (!document || !document->frame())
2264         return Exception { InvalidAccessError };
2265
2266     auto parsedOptions = parseFindOptions(findOptions);
2267     if (parsedOptions.hasException())
2268         return parsedOptions.releaseException();
2269
2270     return document->frame()->editor().rangeOfString(text, referenceRange.get(), parsedOptions.releaseReturnValue());
2271 }
2272
2273 ExceptionOr<unsigned> Internals::countMatchesForText(const String& text, const Vector<String>& findOptions, const String& markMatches)
2274 {
2275     Document* document = contextDocument();
2276     if (!document || !document->frame())
2277         return Exception { InvalidAccessError };
2278
2279     auto parsedOptions = parseFindOptions(findOptions);
2280     if (parsedOptions.hasException())
2281         return parsedOptions.releaseException();
2282
2283     bool mark = markMatches == "mark";
2284     return document->frame()->editor().countMatchesForText(text, nullptr, parsedOptions.releaseReturnValue(), 1000, mark, nullptr);
2285 }
2286
2287 ExceptionOr<unsigned> Internals::countFindMatches(const String& text, const Vector<String>& findOptions)
2288 {
2289     Document* document = contextDocument();
2290     if (!document || !document->page())
2291         return Exception { InvalidAccessError };
2292
2293     auto parsedOptions = parseFindOptions(findOptions);
2294     if (parsedOptions.hasException())
2295         return parsedOptions.releaseException();
2296
2297     return document->page()->countFindMatches(text, parsedOptions.releaseReturnValue(), 1000);
2298 }
2299
2300 unsigned Internals::numberOfLiveNodes() const
2301 {
2302     unsigned nodeCount = 0;
2303     for (auto* document : Document::allDocuments())
2304         nodeCount += document->referencingNodeCount();
2305     return nodeCount;
2306 }
2307
2308 unsigned Internals::numberOfLiveDocuments() const
2309 {
2310     return Document::allDocuments().size();
2311 }
2312
2313 unsigned Internals::referencingNodeCount(const Document& document) const
2314 {
2315     return document.referencingNodeCount();
2316 }
2317
2318 RefPtr<WindowProxy> Internals::openDummyInspectorFrontend(const String& url)
2319 {
2320     auto* inspectedPage = contextDocument()->frame()->page();
2321     auto* window = inspectedPage->mainFrame().document()->domWindow();
2322     auto frontendWindowProxy = window->open(*window, *window, url, "", "");
2323     m_inspectorFrontend = std::make_unique<InspectorStubFrontend>(*inspectedPage, downcast<DOMWindow>(frontendWindowProxy->window()));
2324     return frontendWindowProxy;
2325 }
2326
2327 void Internals::closeDummyInspectorFrontend()
2328 {
2329     m_inspectorFrontend = nullptr;
2330 }
2331
2332 ExceptionOr<void> Internals::setInspectorIsUnderTest(bool isUnderTest)
2333 {
2334     Page* page = contextDocument()->frame()->page();
2335     if (!page)
2336         return Exception { InvalidAccessError };
2337
2338     page->inspectorController().setIsUnderTest(isUnderTest);
2339     return { };
2340 }
2341
2342 bool Internals::hasGrammarMarker(int from, int length)
2343 {
2344     Document* document = contextDocument();
2345     if (!document || !document->frame())
2346         return false;
2347
2348     return document->frame()->editor().selectionStartHasMarkerFor(DocumentMarker::Grammar, from, length);
2349 }
2350
2351 unsigned Internals::numberOfScrollableAreas()
2352 {
2353     Document* document = contextDocument();
2354     if (!document || !document->frame())
2355         return 0;
2356
2357     unsigned count = 0;
2358     Frame* frame = document->frame();
2359     if (frame->view()->scrollableAreas())
2360         count += frame->view()->scrollableAreas()->size();
2361
2362     for (Frame* child = frame->tree().firstChild(); child; child = child->tree().nextSibling()) {
2363         if (child->view() && child->view()->scrollableAreas())
2364             count += child->view()->scrollableAreas()->size();
2365     }
2366
2367     return count;
2368 }
2369
2370 ExceptionOr<bool> Internals::isPageBoxVisible(int pageNumber)
2371 {
2372     Document* document = contextDocument();
2373     if (!document)
2374         return Exception { InvalidAccessError };
2375
2376     return document->isPageBoxVisible(pageNumber);
2377 }
2378
2379 static LayerTreeFlags toLayerTreeFlags(unsigned short flags)
2380 {
2381     LayerTreeFlags layerTreeFlags = 0;
2382     if (flags & Internals::LAYER_TREE_INCLUDES_VISIBLE_RECTS)
2383         layerTreeFlags |= LayerTreeFlagsIncludeVisibleRects;
2384     if (flags & Internals::LAYER_TREE_INCLUDES_TILE_CACHES)
2385         layerTreeFlags |= LayerTreeFlagsIncludeTileCaches;
2386     if (flags & Internals::LAYER_TREE_INCLUDES_REPAINT_RECTS)
2387         layerTreeFlags |= LayerTreeFlagsIncludeRepaintRects;
2388     if (flags & Internals::LAYER_TREE_INCLUDES_PAINTING_PHASES)
2389         layerTreeFlags |= LayerTreeFlagsIncludePaintingPhases;
2390     if (flags & Internals::LAYER_TREE_INCLUDES_CONTENT_LAYERS)
2391         layerTreeFlags |= LayerTreeFlagsIncludeContentLayers;
2392     if (flags & Internals::LAYER_TREE_INCLUDES_ACCELERATES_DRAWING)
2393         layerTreeFlags |= LayerTreeFlagsIncludeAcceleratesDrawing;
2394     if (flags & Internals::LAYER_TREE_INCLUDES_BACKING_STORE_ATTACHED)
2395         layerTreeFlags |= LayerTreeFlagsIncludeBackingStoreAttached;
2396
2397     return layerTreeFlags;
2398 }
2399
2400 // FIXME: Remove the document argument. It is almost always the same as
2401 // contextDocument(), with the exception of a few tests that pass a
2402 // different document, and could just make the call through another Internals
2403 // instance instead.
2404 ExceptionOr<String> Internals::layerTreeAsText(Document& document, unsigned short flags) const
2405 {
2406     if (!document.frame())
2407         return Exception { InvalidAccessError };
2408
2409     document.updateLayoutIgnorePendingStylesheets();
2410     return document.frame()->layerTreeAsText(toLayerTreeFlags(flags));
2411 }
2412
2413 ExceptionOr<uint64_t> Internals::layerIDForElement(Element& element)
2414 {
2415     Document* document = contextDocument();
2416     if (!document || !document->frame())
2417         return Exception { InvalidAccessError };
2418
2419     element.document().updateLayoutIgnorePendingStylesheets();
2420
2421     if (!element.renderer() || !element.renderer()->hasLayer())
2422         return Exception { NotFoundError };
2423
2424     auto& layerModelObject = downcast<RenderLayerModelObject>(*element.renderer());
2425     if (!layerModelObject.layer()->isComposited())
2426         return Exception { NotFoundError };
2427
2428     auto* backing = layerModelObject.layer()->backing();
2429     return backing->graphicsLayer()->primaryLayerID();
2430 }
2431
2432 ExceptionOr<String> Internals::repaintRectsAsText() const
2433 {
2434     Document* document = contextDocument();
2435     if (!document || !document->frame())
2436         return Exception { InvalidAccessError };
2437
2438     return document->frame()->trackedRepaintRectsAsText();
2439 }
2440
2441 ExceptionOr<String> Internals::scrollingStateTreeAsText() const
2442 {
2443     Document* document = contextDocument();
2444     if (!document || !document->frame())
2445         return Exception { InvalidAccessError };
2446
2447     Page* page = document->page();
2448     if (!page)
2449         return String();
2450
2451     return page->scrollingStateTreeAsText();
2452 }
2453
2454 ExceptionOr<String> Internals::mainThreadScrollingReasons() const
2455 {
2456     Document* document = contextDocument();
2457     if (!document || !document->frame())
2458         return Exception { InvalidAccessError };
2459
2460     Page* page = document->page();
2461     if (!page)
2462         return String();
2463
2464     return page->synchronousScrollingReasonsAsText();
2465 }
2466
2467 ExceptionOr<Ref<DOMRectList>> Internals::nonFastScrollableRects() const
2468 {
2469     Document* document = contextDocument();
2470     if (!document || !document->frame())
2471         return Exception { InvalidAccessError };
2472
2473     Page* page = document->page();
2474     if (!page)
2475         return DOMRectList::create();
2476
2477     return page->nonFastScrollableRects();
2478 }
2479
2480 ExceptionOr<void> Internals::setElementUsesDisplayListDrawing(Element& element, bool usesDisplayListDrawing)
2481 {
2482     Document* document = contextDocument();
2483     if (!document || !document->renderView())
2484         return Exception { InvalidAccessError };
2485
2486     element.document().updateLayoutIgnorePendingStylesheets();
2487
2488     if (!element.renderer())
2489         return Exception { InvalidAccessError };
2490
2491     if (is<HTMLCanvasElement>(element)) {
2492         downcast<HTMLCanvasElement>(element).setUsesDisplayListDrawing(usesDisplayListDrawing);
2493         return { };
2494     }
2495
2496     if (!element.renderer()->hasLayer())
2497         return Exception { InvalidAccessError };
2498
2499     RenderLayer* layer = downcast<RenderLayerModelObject>(element.renderer())->layer();
2500     if (!layer->isComposited())
2501         return Exception { InvalidAccessError };
2502
2503     layer->backing()->setUsesDisplayListDrawing(usesDisplayListDrawing);
2504     return { };
2505 }
2506
2507 ExceptionOr<void> Internals::setElementTracksDisplayListReplay(Element& element, bool isTrackingReplay)
2508 {
2509     Document* document = contextDocument();
2510     if (!document || !document->renderView())
2511         return Exception { InvalidAccessError };
2512
2513     element.document().updateLayoutIgnorePendingStylesheets();
2514
2515     if (!element.renderer())
2516         return Exception { InvalidAccessError };
2517
2518     if (is<HTMLCanvasElement>(element)) {
2519         downcast<HTMLCanvasElement>(element).setTracksDisplayListReplay(isTrackingReplay);
2520         return { };
2521     }
2522
2523     if (!element.renderer()->hasLayer())
2524         return Exception { InvalidAccessError };
2525
2526     RenderLayer* layer = downcast<RenderLayerModelObject>(element.renderer())->layer();
2527     if (!layer->isComposited())
2528         return Exception { InvalidAccessError };
2529
2530     layer->backing()->setIsTrackingDisplayListReplay(isTrackingReplay);
2531     return { };
2532 }
2533
2534 ExceptionOr<String> Internals::displayListForElement(Element& element, unsigned short flags)
2535 {
2536     Document* document = contextDocument();
2537     if (!document || !document->renderView())
2538         return Exception { InvalidAccessError };
2539
2540     element.document().updateLayoutIgnorePendingStylesheets();
2541
2542     if (!element.renderer())
2543         return Exception { InvalidAccessError };
2544
2545     DisplayList::AsTextFlags displayListFlags = 0;
2546     if (flags & DISPLAY_LIST_INCLUDES_PLATFORM_OPERATIONS)
2547         displayListFlags |= DisplayList::AsTextFlag::IncludesPlatformOperations;
2548
2549     if (is<HTMLCanvasElement>(element))
2550         return downcast<HTMLCanvasElement>(element).displayListAsText(displayListFlags);
2551
2552     if (!element.renderer()->hasLayer())
2553         return Exception { InvalidAccessError };
2554
2555     RenderLayer* layer = downcast<RenderLayerModelObject>(element.renderer())->layer();
2556     if (!layer->isComposited())
2557         return Exception { InvalidAccessError };
2558
2559     return layer->backing()->displayListAsText(displayListFlags);
2560 }
2561
2562 ExceptionOr<String> Internals::replayDisplayListForElement(Element& element, unsigned short flags)
2563 {
2564     Document* document = contextDocument();
2565     if (!document || !document->renderView())
2566         return Exception { InvalidAccessError };
2567
2568     element.document().updateLayoutIgnorePendingStylesheets();
2569
2570     if (!element.renderer())
2571         return Exception { InvalidAccessError };
2572
2573     DisplayList::AsTextFlags displayListFlags = 0;
2574     if (flags & DISPLAY_LIST_INCLUDES_PLATFORM_OPERATIONS)
2575         displayListFlags |= DisplayList::AsTextFlag::IncludesPlatformOperations;
2576
2577     if (is<HTMLCanvasElement>(element))
2578         return downcast<HTMLCanvasElement>(element).replayDisplayListAsText(displayListFlags);
2579
2580     if (!element.renderer()->hasLayer())
2581         return Exception { InvalidAccessError };
2582
2583     RenderLayer* layer = downcast<RenderLayerModelObject>(element.renderer())->layer();
2584     if (!layer->isComposited())
2585         return Exception { InvalidAccessError };
2586
2587     return layer->backing()->replayDisplayListAsText(displayListFlags);
2588 }
2589
2590 ExceptionOr<void> Internals::garbageCollectDocumentResources() const
2591 {
2592     Document* document = contextDocument();
2593     if (!document)
2594         return Exception { InvalidAccessError };
2595     document->cachedResourceLoader().garbageCollectDocumentResources();
2596     return { };
2597 }
2598
2599 bool Internals::isUnderMemoryPressure()
2600 {
2601     return MemoryPressureHandler::singleton().isUnderMemoryPressure();
2602 }
2603
2604 void Internals::beginSimulatedMemoryPressure()
2605 {
2606     MemoryPressureHandler::singleton().beginSimulatedMemoryPressure();
2607 }
2608
2609 void Internals::endSimulatedMemoryPressure()
2610 {
2611     MemoryPressureHandler::singleton().endSimulatedMemoryPressure();
2612 }
2613
2614 ExceptionOr<void> Internals::insertAuthorCSS(const String& css) const
2615 {
2616     Document* document = contextDocument();
2617     if (!document)
2618         return Exception { InvalidAccessError };
2619
2620     auto parsedSheet = StyleSheetContents::create(*document);
2621     parsedSheet.get().setIsUserStyleSheet(false);
2622     parsedSheet.get().parseString(css);
2623     document->extensionStyleSheets().addAuthorStyleSheetForTesting(WTFMove(parsedSheet));
2624     return { };
2625 }
2626
2627 ExceptionOr<void> Internals::insertUserCSS(const String& css) const
2628 {
2629     Document* document = contextDocument();
2630     if (!document)
2631         return Exception { InvalidAccessError };
2632
2633     auto parsedSheet = StyleSheetContents::create(*document);
2634     parsedSheet.get().setIsUserStyleSheet(true);
2635     parsedSheet.get().parseString(css);
2636     document->extensionStyleSheets().addUserStyleSheet(WTFMove(parsedSheet));
2637     return { };
2638 }
2639
2640 String Internals::counterValue(Element& element)
2641 {
2642     return counterValueForElement(&element);
2643 }
2644
2645 int Internals::pageNumber(Element& element, float pageWidth, float pageHeight)
2646 {
2647     return PrintContext::pageNumberForElement(&element, { pageWidth, pageHeight });
2648 }
2649
2650 Vector<String> Internals::shortcutIconURLs() const
2651 {
2652     if (!frame())
2653         return { };
2654     
2655     auto* documentLoader = frame()->loader().documentLoader();
2656     if (!documentLoader)
2657         return { };
2658
2659     Vector<String> result;
2660     for (auto& linkIcon : documentLoader->linkIcons())
2661         result.append(linkIcon.url.string());
2662     
2663     return result;
2664 }
2665
2666 int Internals::numberOfPages(float pageWidth, float pageHeight)
2667 {
2668     if (!frame())
2669         return -1;
2670
2671     return PrintContext::numberOfPages(*frame(), FloatSize(pageWidth, pageHeight));
2672 }
2673
2674 ExceptionOr<String> Internals::pageProperty(const String& propertyName, int pageNumber) const
2675 {
2676     if (!frame())
2677         return Exception { InvalidAccessError };
2678
2679     return PrintContext::pageProperty(frame(), propertyName.utf8().data(), pageNumber);
2680 }
2681
2682 ExceptionOr<String> Internals::pageSizeAndMarginsInPixels(int pageNumber, int width, int height, int marginTop, int marginRight, int marginBottom, int marginLeft) const
2683 {
2684     if (!frame())
2685         return Exception { InvalidAccessError };
2686
2687     return PrintContext::pageSizeAndMarginsInPixels(frame(), pageNumber, width, height, marginTop, marginRight, marginBottom, marginLeft);
2688 }
2689
2690 ExceptionOr<float> Internals::pageScaleFactor() const
2691 {
2692     Document* document = contextDocument();
2693     if (!document || !document->page())
2694         return Exception { InvalidAccessError };
2695
2696     return document->page()->pageScaleFactor();
2697 }
2698
2699 ExceptionOr<void> Internals::setPageScaleFactor(float scaleFactor, int x, int y)
2700 {
2701     Document* document = contextDocument();
2702     if (!document || !document->page())
2703         return Exception { InvalidAccessError };
2704
2705     document->page()->setPageScaleFactor(scaleFactor, IntPoint(x, y));
2706     return { };
2707 }
2708
2709 ExceptionOr<void> Internals::setPageZoomFactor(float zoomFactor)
2710 {
2711     Document* document = contextDocument();
2712     if (!document || !document->frame())
2713         return Exception { InvalidAccessError };
2714
2715     document->frame()->setPageZoomFactor(zoomFactor);
2716     return { };
2717 }
2718
2719 ExceptionOr<void> Internals::setTextZoomFactor(float zoomFactor)
2720 {
2721     Document* document = contextDocument();
2722     if (!document || !document->frame())
2723         return Exception { InvalidAccessError };
2724
2725     document->frame()->setTextZoomFactor(zoomFactor);
2726     return { };
2727 }
2728
2729 ExceptionOr<void> Internals::setUseFixedLayout(bool useFixedLayout)
2730 {
2731     Document* document = contextDocument();
2732     if (!document || !document->view())
2733         return Exception { InvalidAccessError };
2734
2735     document->view()->setUseFixedLayout(useFixedLayout);
2736     return { };
2737 }
2738
2739 ExceptionOr<void> Internals::setFixedLayoutSize(int width, int height)
2740 {
2741     Document* document = contextDocument();
2742     if (!document || !document->view())
2743         return Exception { InvalidAccessError };
2744
2745     document->view()->setFixedLayoutSize(IntSize(width, height));
2746     return { };
2747 }
2748
2749 ExceptionOr<void> Internals::setViewExposedRect(float x, float y, float width, float height)
2750 {
2751     Document* document = contextDocument();
2752     if (!document || !document->view())
2753         return Exception { InvalidAccessError };
2754
2755     document->view()->setViewExposedRect(FloatRect(x, y, width, height));
2756     return { };
2757 }
2758
2759 void Internals::setPrinting(int width, int height)
2760 {
2761     printContextForTesting() = std::make_unique<PrintContext>(frame());
2762     printContextForTesting()->begin(width, height);
2763 }
2764
2765 void Internals::setHeaderHeight(float height)
2766 {
2767     Document* document = contextDocument();
2768     if (!document || !document->view())
2769         return;
2770
2771     document->view()->setHeaderHeight(height);
2772 }
2773
2774 void Internals::setFooterHeight(float height)
2775 {
2776     Document* document = contextDocument();
2777     if (!document || !document->view())
2778         return;
2779
2780     document->view()->setFooterHeight(height);
2781 }
2782
2783 void Internals::setTopContentInset(float contentInset)
2784 {
2785     Document* document = contextDocument();
2786     if (!document || !document->page())
2787         return;
2788
2789     document->page()->setTopContentInset(contentInset);
2790 }
2791
2792 #if ENABLE(FULLSCREEN_API)
2793
2794 void Internals::webkitWillEnterFullScreenForElement(Element& element)
2795 {
2796     Document* document = contextDocument();
2797     if (!document)
2798         return;
2799     document->webkitWillEnterFullScreenForElement(&element);
2800 }
2801
2802 void Internals::webkitDidEnterFullScreenForElement(Element& element)
2803 {
2804     Document* document = contextDocument();
2805     if (!document)
2806         return;
2807     document->webkitDidEnterFullScreenForElement(&element);
2808 }
2809
2810 void Internals::webkitWillExitFullScreenForElement(Element& element)
2811 {
2812     Document* document = contextDocument();
2813     if (!document)
2814         return;
2815     document->webkitWillExitFullScreenForElement(&element);
2816 }
2817
2818 void Internals::webkitDidExitFullScreenForElement(Element& element)
2819 {
2820     Document* document = contextDocument();
2821     if (!document)
2822         return;
2823     document->webkitDidExitFullScreenForElement(&element);
2824 }
2825
2826 #endif
2827
2828 void Internals::setFullscreenInsetTop(double inset)
2829 {
2830     Page* page = contextDocument()->frame()->page();
2831     ASSERT(page);
2832
2833     page->setFullscreenInsetTop(inset);
2834 }
2835
2836 void Internals::setFullscreenAutoHideDelay(double delay)
2837 {
2838     Page* page = contextDocument()->frame()->page();
2839     ASSERT(page);
2840
2841     page->setFullscreenAutoHideDelay(delay);
2842 }
2843
2844 void Internals::setApplicationCacheOriginQuota(unsigned long long quota)
2845 {
2846     Document* document = contextDocument();
2847     if (!document || !document->page())
2848         return;
2849     document->page()->applicationCacheStorage().storeUpdatedQuotaForOrigin(&document->securityOrigin(), quota);
2850 }
2851
2852 void Internals::registerURLSchemeAsBypassingContentSecurityPolicy(const String& scheme)
2853 {
2854     SchemeRegistry::registerURLSchemeAsBypassingContentSecurityPolicy(scheme);
2855 }
2856
2857 void Internals::removeURLSchemeRegisteredAsBypassingContentSecurityPolicy(const String& scheme)
2858 {
2859     SchemeRegistry::removeURLSchemeRegisteredAsBypassingContentSecurityPolicy(scheme);
2860 }
2861
2862 void Internals::registerDefaultPortForProtocol(unsigned short port, const String& protocol)
2863 {
2864     registerDefaultPortForProtocolForTesting(port, protocol);
2865 }
2866
2867 Ref<MallocStatistics> Internals::mallocStatistics() const
2868 {
2869     return MallocStatistics::create();
2870 }
2871
2872 Ref<TypeConversions> Internals::typeConversions() const
2873 {
2874     return TypeConversions::create();
2875 }
2876
2877 Ref<MemoryInfo> Internals::memoryInfo() const
2878 {
2879     return MemoryInfo::create();
2880 }
2881
2882 Vector<String> Internals::getReferencedFilePaths() const
2883 {
2884     frame()->loader().history().saveDocumentAndScrollState();
2885     return FormController::referencedFilePaths(frame()->loader().history().currentItem()->documentState());
2886 }
2887
2888 ExceptionOr<void> Internals::startTrackingRepaints()
2889 {
2890     Document* document = contextDocument();
2891     if (!document || !document->view())
2892         return Exception { InvalidAccessError };
2893
2894     document->view()->setTracksRepaints(true);
2895     return { };
2896 }
2897
2898 ExceptionOr<void> Internals::stopTrackingRepaints()
2899 {
2900     Document* document = contextDocument();
2901     if (!document || !document->view())
2902         return Exception { InvalidAccessError };
2903
2904     document->view()->setTracksRepaints(false);
2905     return { };
2906 }
2907
2908 ExceptionOr<void> Internals::startTrackingLayerFlushes()
2909 {
2910     Document* document = contextDocument();
2911     if (!document || !document->renderView())
2912         return Exception { InvalidAccessError };
2913
2914     document->renderView()->compositor().startTrackingLayerFlushes();
2915     return { };
2916 }
2917
2918 ExceptionOr<unsigned> Internals::layerFlushCount()
2919 {
2920     Document* document = contextDocument();
2921     if (!document || !document->renderView())
2922         return Exception { InvalidAccessError };
2923
2924     return document->renderView()->compositor().layerFlushCount();
2925 }
2926
2927 ExceptionOr<void> Internals::startTrackingStyleRecalcs()
2928 {
2929     Document* document = contextDocument();
2930     if (!document)
2931         return Exception { InvalidAccessError };
2932
2933     document->startTrackingStyleRecalcs();
2934     return { };
2935 }
2936
2937 ExceptionOr<unsigned> Internals::styleRecalcCount()
2938 {
2939     Document* document = contextDocument();
2940     if (!document)
2941         return Exception { InvalidAccessError };
2942
2943     return document->styleRecalcCount();
2944 }
2945
2946 unsigned Internals::lastStyleUpdateSize() const
2947 {
2948     Document* document = contextDocument();
2949     if (!document)
2950         return 0;
2951     return document->lastStyleUpdateSizeForTesting();
2952 }
2953
2954 ExceptionOr<void> Internals::startTrackingCompositingUpdates()
2955 {
2956     Document* document = contextDocument();
2957     if (!document || !document->renderView())
2958         return Exception { InvalidAccessError };
2959
2960     document->renderView()->compositor().startTrackingCompositingUpdates();
2961     return { };
2962 }
2963
2964 ExceptionOr<unsigned> Internals::compositingUpdateCount()
2965 {
2966     Document* document = contextDocument();
2967     if (!document || !document->renderView())
2968         return Exception { InvalidAccessError };
2969
2970     return document->renderView()->compositor().compositingUpdateCount();
2971 }
2972
2973 ExceptionOr<void> Internals::updateLayoutIgnorePendingStylesheetsAndRunPostLayoutTasks(Node* node)
2974 {
2975     Document* document;
2976     if (!node)
2977         document = contextDocument();
2978     else if (is<Document>(*node))
2979         document = downcast<Document>(node);
2980     else if (is<HTMLIFrameElement>(*node))
2981         document = downcast<HTMLIFrameElement>(*node).contentDocument();
2982     else
2983         return Exception { TypeError };
2984
2985     document->updateLayoutIgnorePendingStylesheets(Document::RunPostLayoutTasks::Synchronously);
2986     return { };
2987 }
2988
2989 unsigned Internals::layoutCount() const
2990 {
2991     Document* document = contextDocument();
2992     if (!document || !document->view())
2993         return 0;
2994     return document->view()->layoutContext().layoutCount();
2995 }
2996
2997 #if !PLATFORM(IOS)
2998 static const char* cursorTypeToString(Cursor::Type cursorType)
2999 {
3000     switch (cursorType) {
3001     case Cursor::Pointer: return "Pointer";
3002     case Cursor::Cross: return "Cross";
3003     case Cursor::Hand: return "Hand";
3004     case Cursor::IBeam: return "IBeam";
3005     case Cursor::Wait: return "Wait";
3006     case Cursor::Help: return "Help";
3007     case Cursor::EastResize: return "EastResize";
3008     case Cursor::NorthResize: return "NorthResize";
3009     case Cursor::NorthEastResize: return "NorthEastResize";
3010     case Cursor::NorthWestResize: return "NorthWestResize";
3011     case Cursor::SouthResize: return "SouthResize";
3012     case Cursor::SouthEastResize: return "SouthEastResize";
3013     case Cursor::SouthWestResize: return "SouthWestResize";
3014     case Cursor::WestResize: return "WestResize";
3015     case Cursor::NorthSouthResize: return "NorthSouthResize";
3016     case Cursor::EastWestResize: return "EastWestResize";
3017     case Cursor::NorthEastSouthWestResize: return "NorthEastSouthWestResize";
3018     case Cursor::NorthWestSouthEastResize: return "NorthWestSouthEastResize";
3019     case Cursor::ColumnResize: return "ColumnResize";
3020     case Cursor::RowResize: return "RowResize";
3021     case Cursor::MiddlePanning: return "MiddlePanning";
3022     case Cursor::EastPanning: return "EastPanning";
3023     case Cursor::NorthPanning: return "NorthPanning";
3024     case Cursor::NorthEastPanning: return "NorthEastPanning";
3025     case Cursor::NorthWestPanning: return "NorthWestPanning";
3026     case Cursor::SouthPanning: return "SouthPanning";
3027     case Cursor::SouthEastPanning: return "SouthEastPanning";
3028     case Cursor::SouthWestPanning: return "SouthWestPanning";
3029     case Cursor::WestPanning: return "WestPanning";
3030     case Cursor::Move: return "Move";
3031     case Cursor::VerticalText: return "VerticalText";
3032     case Cursor::Cell: return "Cell";
3033     case Cursor::ContextMenu: return "ContextMenu";
3034     case Cursor::Alias: return "Alias";
3035     case Cursor::Progress: return "Progress";
3036     case Cursor::NoDrop: return "NoDrop";
3037     case Cursor::Copy: return "Copy";
3038     case Cursor::None: return "None";
3039     case Cursor::NotAllowed: return "NotAllowed";
3040     case Cursor::ZoomIn: return "ZoomIn";
3041     case Cursor::ZoomOut: return "ZoomOut";
3042     case Cursor::Grab: return "Grab";
3043     case Cursor::Grabbing: return "Grabbing";
3044     case Cursor::Custom: return "Custom";
3045     }
3046
3047     ASSERT_NOT_REACHED();
3048     return "UNKNOWN";
3049 }
3050 #endif
3051
3052 ExceptionOr<String> Internals::getCurrentCursorInfo()
3053 {
3054     Document* document = contextDocument();
3055     if (!document || !document->frame())
3056         return Exception { InvalidAccessError };
3057
3058 #if !PLATFORM(IOS)
3059     Cursor cursor = document->frame()->eventHandler().currentMouseCursor();
3060
3061     StringBuilder result;
3062     result.appendLiteral("type=");
3063     result.append(cursorTypeToString(cursor.type()));
3064     result.appendLiteral(" hotSpot=");
3065     result.appendNumber(cursor.hotSpot().x());
3066     result.append(',');
3067     result.appendNumber(cursor.hotSpot().y());
3068     if (cursor.image()) {
3069         FloatSize size = cursor.image()->size();
3070         result.appendLiteral(" image=");
3071         result.appendNumber(size.width());
3072         result.append('x');
3073         result.appendNumber(size.height());
3074     }
3075 #if ENABLE(MOUSE_CURSOR_SCALE)
3076     if (cursor.imageScaleFactor() != 1) {
3077         result.appendLiteral(" scale=");
3078         NumberToStringBuffer buffer;
3079         result.append(numberToFixedPrecisionString(cursor.imageScaleFactor(), 8, buffer, true));
3080     }
3081 #endif
3082     return result.toString();
3083 #else
3084     return String { "FAIL: Cursor details not available on this platform." };
3085 #endif
3086 }
3087
3088 Ref<ArrayBuffer> Internals::serializeObject(const RefPtr<SerializedScriptValue>& value) const
3089 {
3090     auto& bytes = value->data();
3091     return ArrayBuffer::create(bytes.data(), bytes.size());
3092 }
3093
3094 Ref<SerializedScriptValue> Internals::deserializeBuffer(ArrayBuffer& buffer) const
3095 {
3096     Vector<uint8_t> bytes;
3097     bytes.append(static_cast<const uint8_t*>(buffer.data()), buffer.byteLength());
3098     return SerializedScriptValue::adopt(WTFMove(bytes));
3099 }
3100
3101 bool Internals::isFromCurrentWorld(JSC::JSValue value) const
3102 {
3103     return isWorldCompatible(*contextDocument()->vm().topCallFrame, value);
3104 }
3105
3106 void Internals::setUsesOverlayScrollbars(bool enabled)
3107 {
3108     WebCore::DeprecatedGlobalSettings::setUsesOverlayScrollbars(enabled);
3109 }
3110
3111 void Internals::setUsesMockScrollAnimator(bool enabled)
3112 {
3113     WebCore::DeprecatedGlobalSettings::setUsesMockScrollAnimator(enabled);
3114 }
3115
3116 void Internals::forceReload(bool endToEnd)
3117 {
3118     OptionSet<ReloadOption> reloadOptions;
3119     if (endToEnd)
3120         reloadOptions |= ReloadOption::FromOrigin;
3121
3122     frame()->loader().reload(reloadOptions);
3123 }
3124
3125 void Internals::reloadExpiredOnly()
3126 {
3127     frame()->loader().reload(ReloadOption::ExpiredOnly);
3128 }
3129
3130 void Internals::enableAutoSizeMode(bool enabled, int minimumWidth, int minimumHeight, int maximumWidth, int maximumHeight)
3131 {
3132     auto* document = contextDocument();
3133     if (!document || !document->view())
3134         return;
3135     document->view()->enableAutoSizeMode(enabled, IntSize(minimumWidth, minimumHeight), IntSize(maximumWidth, maximumHeight));
3136 }
3137
3138 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
3139
3140 void Internals::initializeMockCDM()
3141 {
3142     LegacyCDM::registerCDMFactory([] (LegacyCDM* cdm) { return std::make_unique<LegacyMockCDM>(cdm); },
3143         LegacyMockCDM::supportsKeySystem, LegacyMockCDM::supportsKeySystemAndMimeType);
3144 }
3145
3146 #endif
3147
3148 #if ENABLE(ENCRYPTED_MEDIA)
3149
3150 Ref<MockCDMFactory> Internals::registerMockCDM()
3151 {
3152     return MockCDMFactory::create();
3153 }
3154
3155 #endif
3156
3157 String Internals::markerTextForListItem(Element& element)
3158 {
3159     return WebCore::markerTextForListItem(&element);
3160 }
3161
3162 String Internals::toolTipFromElement(Element& element) const
3163 {
3164     HitTestResult result;
3165     result.setInnerNode(&element);
3166     TextDirection direction;
3167     return result.title(direction);
3168 }
3169
3170 String Internals::getImageSourceURL(Element& element)
3171 {
3172     return element.imageSourceURL();
3173 }
3174
3175 #if ENABLE(VIDEO)
3176
3177 Vector<String> Internals::mediaResponseSources(HTMLMediaElement& media)
3178 {
3179     auto* resourceLoader = media.lastMediaResourceLoaderForTesting();
3180     if (!resourceLoader)
3181         return { };
3182     Vector<String> result;
3183     auto responses = resourceLoader->responsesForTesting();
3184     for (auto& response : responses)
3185         result.append(responseSourceToString(response));
3186     return result;
3187 }
3188
3189 Vector<String> Internals::mediaResponseContentRanges(HTMLMediaElement& media)
3190 {
3191     auto* resourceLoader = media.lastMediaResourceLoaderForTesting();
3192     if (!resourceLoader)
3193         return { };
3194     Vector<String> result;
3195     auto responses = resourceLoader->responsesForTesting();
3196     for (auto& response : responses)
3197         result.append(response.httpHeaderField(HTTPHeaderName::ContentRange));
3198     return result;
3199 }
3200
3201 void Internals::simulateAudioInterruption(HTMLMediaElement& element)
3202 {
3203 #if USE(GSTREAMER)
3204     element.player()->simulateAudioInterruption();
3205 #else
3206     UNUSED_PARAM(element);
3207 #endif
3208 }
3209
3210 ExceptionOr<bool> Internals::mediaElementHasCharacteristic(HTMLMediaElement& element, const String& characteristic)
3211 {
3212     if (equalLettersIgnoringASCIICase(characteristic, "audible"))
3213         return element.hasAudio();
3214     if (equalLettersIgnoringASCIICase(characteristic, "visual"))
3215         return element.hasVideo();
3216     if (equalLettersIgnoringASCIICase(characteristic, "legible"))
3217         return element.hasClosedCaptions();
3218
3219     return Exception { SyntaxError };
3220 }
3221
3222 void Internals::beginSimulatedHDCPError(HTMLMediaElement& element)
3223 {
3224     if (auto player = element.player())
3225         player->beginSimulatedHDCPError();
3226 }
3227
3228 void Internals::endSimulatedHDCPError(HTMLMediaElement& element)
3229 {
3230     if (auto player = element.player())
3231         player->endSimulatedHDCPError();
3232 }
3233
3234 #endif
3235
3236 bool Internals::isSelectPopupVisible(HTMLSelectElement& element)
3237 {
3238     element.document().updateLayoutIgnorePendingStylesheets();
3239
3240     auto* renderer = element.renderer();
3241     if (!is<RenderMenuList>(renderer))
3242         return false;
3243
3244 #if !PLATFORM(IOS)
3245     return downcast<RenderMenuList>(*renderer).popupIsVisible();
3246 #else
3247     return false;
3248 #endif
3249 }
3250
3251 ExceptionOr<String> Internals::captionsStyleSheetOverride()
3252 {
3253     Document* document = contextDocument();
3254     if (!document || !document->page())
3255         return Exception { InvalidAccessError };
3256
3257 #if ENABLE(VIDEO_TRACK)
3258     return document->page()->group().captionPreferences().captionsStyleSheetOverride();
3259 #else
3260     return String { emptyString() };
3261 #endif
3262 }
3263
3264 ExceptionOr<void> Internals::setCaptionsStyleSheetOverride(const String& override)
3265 {
3266     Document* document = contextDocument();
3267     if (!document || !document->page())
3268         return Exception { InvalidAccessError };
3269
3270 #if ENABLE(VIDEO_TRACK)
3271     document->page()->group().captionPreferences().setCaptionsStyleSheetOverride(override);
3272 #else
3273     UNUSED_PARAM(override);
3274 #endif
3275     return { };
3276 }
3277
3278 ExceptionOr<void> Internals::setPrimaryAudioTrackLanguageOverride(const String& language)
3279 {
3280     Document* document = contextDocument();
3281     if (!document || !document->page())
3282         return Exception { InvalidAccessError };
3283
3284 #if ENABLE(VIDEO_TRACK)
3285     document->page()->group().captionPreferences().setPrimaryAudioTrackLanguageOverride(language);
3286 #else
3287     UNUSED_PARAM(language);
3288 #endif
3289     return { };
3290 }
3291
3292 ExceptionOr<void> Internals::setCaptionDisplayMode(const String& mode)
3293 {
3294     Document* document = contextDocument();
3295     if (!document || !document->page())
3296         return Exception { InvalidAccessError };
3297
3298 #if ENABLE(VIDEO_TRACK)
3299     auto& captionPreferences = document->page()->group().captionPreferences();
3300
3301     if (equalLettersIgnoringASCIICase(mode, "automatic"))
3302         captionPreferences.setCaptionDisplayMode(CaptionUserPreferences::Automatic);
3303     else if (equalLettersIgnoringASCIICase(mode, "forcedonly"))
3304         captionPreferences.setCaptionDisplayMode(CaptionUserPreferences::ForcedOnly);
3305     else if (equalLettersIgnoringASCIICase(mode, "alwayson"))
3306         captionPreferences.setCaptionDisplayMode(CaptionUserPreferences::AlwaysOn);
3307     else if (equalLettersIgnoringASCIICase(mode, "manual"))
3308         captionPreferences.setCaptionDisplayMode(CaptionUserPreferences::Manual);
3309     else
3310         return Exception { SyntaxError };
3311 #else
3312     UNUSED_PARAM(mode);
3313 #endif
3314     return { };
3315 }
3316
3317 #if ENABLE(VIDEO)
3318
3319 Ref<TimeRanges> Internals::createTimeRanges(Float32Array& startTimes, Float32Array& endTimes)
3320 {
3321     ASSERT(startTimes.length() == endTimes.length());
3322     Ref<TimeRanges> ranges = TimeRanges::create();
3323
3324     unsigned count = std::min(startTimes.length(), endTimes.length());
3325     for (unsigned i = 0; i < count; ++i)
3326         ranges->add(startTimes.item(i), endTimes.item(i));
3327     return ranges;
3328 }
3329
3330 double Internals::closestTimeToTimeRanges(double time, TimeRanges& ranges)
3331 {
3332     return ranges.nearest(time);
3333 }
3334
3335 #endif
3336
3337 ExceptionOr<Ref<DOMRect>> Internals::selectionBounds()
3338 {
3339     Document* document = contextDocument();
3340     if (!document || !document->frame())
3341         return Exception { InvalidAccessError };
3342
3343     return DOMRect::create(document->frame()->selection().selectionBounds());
3344 }
3345
3346 ExceptionOr<bool> Internals::isPluginUnavailabilityIndicatorObscured(Element& element)
3347 {
3348     if (!is<HTMLPlugInElement>(element))
3349         return Exception { InvalidAccessError };
3350
3351     return downcast<HTMLPlugInElement>(element).isReplacementObscured();
3352 }
3353
3354 ExceptionOr<String> Internals::unavailablePluginReplacementText(Element& element)
3355 {
3356     if (!is<HTMLPlugInElement>(element))
3357         return Exception { InvalidAccessError };
3358
3359     auto* renderer = element.renderer();
3360     if (!is<RenderEmbeddedObject>(renderer))
3361         return String { };
3362
3363     return String { downcast<RenderEmbeddedObject>(*renderer).pluginReplacementTextIfUnavailable() };
3364 }
3365
3366 bool Internals::isPluginSnapshotted(Element& element)
3367 {
3368     return is<HTMLPlugInElement>(element) && downcast<HTMLPlugInElement>(element).displayState() <= HTMLPlugInElement::DisplayingSnapshot;
3369 }
3370
3371 #if ENABLE(MEDIA_SOURCE)
3372
3373 void Internals::initializeMockMediaSource()
3374 {
3375 #if USE(AVFOUNDATION)
3376     WebCore::DeprecatedGlobalSettings::setAVFoundationEnabled(false);
3377 #endif
3378 #if USE(GSTREAMER)
3379     WebCore::DeprecatedGlobalSettings::setGStreamerEnabled(false);
3380 #endif
3381     MediaPlayerFactorySupport::callRegisterMediaEngine(MockMediaPlayerMediaSource::registerMediaEngine);
3382 }
3383
3384 Vector<String> Internals::bufferedSamplesForTrackID(SourceBuffer& buffer, const AtomicString& trackID)
3385 {
3386     return buffer.bufferedSamplesForTrackID(trackID);
3387 }
3388
3389 Vector<String> Internals::enqueuedSamplesForTrackID(SourceBuffer& buffer, const AtomicString& trackID)
3390 {
3391     return buffer.enqueuedSamplesForTrackID(trackID);
3392 }
3393
3394 void Internals::setShouldGenerateTimestamps(SourceBuffer& buffer, bool flag)
3395 {
3396     buffer.setShouldGenerateTimestamps(flag);
3397 }
3398
3399 #endif
3400
3401 #if ENABLE(VIDEO)
3402
3403 ExceptionOr<void> Internals::beginMediaSessionInterruption(const String& interruptionString)
3404 {
3405     PlatformMediaSession::InterruptionType interruption = PlatformMediaSession::SystemInterruption;
3406
3407     if (equalLettersIgnoringASCIICase(interruptionString, "system"))
3408         interruption = PlatformMediaSession::SystemInterruption;
3409     else if (equalLettersIgnoringASCIICase(interruptionString, "systemsleep"))
3410         interruption = PlatformMediaSession::SystemSleep;
3411     else if (equalLettersIgnoringASCIICase(interruptionString, "enteringbackground"))
3412         interruption = PlatformMediaSession::EnteringBackground;
3413     else if (equalLettersIgnoringASCIICase(interruptionString, "suspendedunderlock"))
3414         interruption = PlatformMediaSession::SuspendedUnderLock;
3415     else
3416         return Exception { InvalidAccessError };
3417
3418     PlatformMediaSessionManager::sharedManager().beginInterruption(interruption);
3419     return { };
3420 }
3421
3422 void Internals::endMediaSessionInterruption(const String& flagsString)
3423 {
3424     PlatformMediaSession::EndInterruptionFlags flags = PlatformMediaSession::NoFlags;
3425
3426     if (equalLettersIgnoringASCIICase(flagsString, "mayresumeplaying"))
3427         flags = PlatformMediaSession::MayResumePlaying;
3428
3429     PlatformMediaSessionManager::sharedManager().endInterruption(flags);
3430 }
3431
3432 void Internals::applicationWillBecomeInactive()
3433 {
3434     PlatformMediaSessionManager::sharedManager().applicationWillBecomeInactive();
3435 }
3436
3437 void Internals::applicationDidBecomeActive()
3438 {
3439     PlatformMediaSessionManager::sharedManager().applicationDidBecomeActive();
3440 }
3441
3442 void Internals::applicationWillEnterForeground(bool suspendedUnderLock) const
3443 {
3444     PlatformMediaSessionManager::sharedManager().applicationWillEnterForeground(suspendedUnderLock);
3445 }
3446
3447 void Internals::applicationDidEnterBackground(bool suspendedUnderLock) const
3448 {
3449     PlatformMediaSessionManager::sharedManager().applicationDidEnterBackground(suspendedUnderLock);
3450 }
3451
3452 static PlatformMediaSession::MediaType mediaTypeFromString(const String& mediaTypeString)
3453 {
3454     if (equalLettersIgnoringASCIICase(mediaTypeString, "video"))
3455         return PlatformMediaSession::Video;
3456     if (equalLettersIgnoringASCIICase(mediaTypeString, "audio"))
3457         return PlatformMediaSession::Audio;
3458     if (equalLettersIgnoringASCIICase(mediaTypeString, "videoaudio"))
3459         return PlatformMediaSession::VideoAudio;
3460     if (equalLettersIgnoringASCIICase(mediaTypeString, "webaudio"))
3461         return PlatformMediaSession::WebAudio;
3462     if (equalLettersIgnoringASCIICase(mediaTypeString, "mediastreamcapturingaudio"))
3463         return PlatformMediaSession::MediaStreamCapturingAudio;
3464
3465     return PlatformMediaSession::None;
3466 }
3467
3468 ExceptionOr<void> Internals::setMediaSessionRestrictions(const String& mediaTypeString, StringView restrictionsString)
3469 {
3470     PlatformMediaSession::MediaType mediaType = mediaTypeFromString(mediaTypeString);
3471     if (mediaType == PlatformMediaSession::None)
3472         return Exception { InvalidAccessError };
3473
3474     PlatformMediaSessionManager::SessionRestrictions restrictions = PlatformMediaSessionManager::sharedManager().restrictions(mediaType);
3475     PlatformMediaSessionManager::sharedManager().removeRestriction(mediaType, restrictions);
3476
3477     restrictions = PlatformMediaSessionManager::NoRestrictions;
3478
3479     for (StringView restrictionString : restrictionsString.split(',')) {
3480         if (equalLettersIgnoringASCIICase(restrictionString, "concurrentplaybacknotpermitted"))
3481             restrictions |= PlatformMediaSessionManager::ConcurrentPlaybackNotPermitted;
3482         if (equalLettersIgnoringASCIICase(restrictionString, "backgroundprocessplaybackrestricted"))
3483             restrictions |= PlatformMediaSessionManager::BackgroundProcessPlaybackRestricted;
3484         if (equalLettersIgnoringASCIICase(restrictionString, "backgroundtabplaybackrestricted"))
3485             restrictions |= PlatformMediaSessionManager::BackgroundTabPlaybackRestricted;
3486         if (equalLettersIgnoringASCIICase(restrictionString, "interruptedplaybacknotpermitted"))
3487             restrictions |= PlatformMediaSessionManager::InterruptedPlaybackNotPermitted;
3488         if (equalLettersIgnoringASCIICase(restrictionString, "inactiveprocessplaybackrestricted"))
3489             restrictions |= PlatformMediaSessionManager::InactiveProcessPlaybackRestricted;
3490         if (equalLettersIgnoringASCIICase(restrictionString, "suspendedunderlockplaybackrestricted"))
3491             restrictions |= PlatformMediaSessionManager::SuspendedUnderLockPlaybackRestricted;
3492     }
3493     PlatformMediaSessionManager::sharedManager().addRestriction(mediaType, restrictions);
3494     return { };
3495 }
3496
3497 ExceptionOr<String> Internals::mediaSessionRestrictions(const String& mediaTypeString) const
3498 {
3499     PlatformMediaSession::MediaType mediaType = mediaTypeFromString(mediaTypeString);
3500     if (mediaType == PlatformMediaSession::None)
3501         return Exception { InvalidAccessError };
3502
3503     PlatformMediaSessionManager::SessionRestrictions restrictions = PlatformMediaSessionManager::sharedManager().restrictions(mediaType);
3504     if (restrictions == PlatformMediaSessionManager::NoRestrictions)
3505         return String();
3506
3507     StringBuilder builder;
3508     if (restrictions & PlatformMediaSessionManager::ConcurrentPlaybackNotPermitted)
3509         builder.append("concurrentplaybacknotpermitted");
3510     if (restrictions & PlatformMediaSessionManager::BackgroundProcessPlaybackRestricted) {
3511         if (!builder.isEmpty())
3512             builder.append(',');
3513         builder.append("backgroundprocessplaybackrestricted");
3514     }
3515     if (restrictions & PlatformMediaSessionManager::BackgroundTabPlaybackRestricted) {
3516         if (!builder.isEmpty())
3517             builder.append(',');
3518         builder.append("backgroundtabplaybackrestricted");
3519     }
3520     if (restrictions & PlatformMediaSessionManager::InterruptedPlaybackNotPermitted) {
3521         if (!builder.isEmpty())
3522             builder.append(',');
3523         builder.append("interruptedplaybacknotpermitted");
3524     }
3525     return builder.toString();
3526 }
3527
3528 void Internals::setMediaElementRestrictions(HTMLMediaElement& element, StringView restrictionsString)
3529 {
3530     MediaElementSession::BehaviorRestrictions restrictions = element.mediaSession().behaviorRestrictions();
3531     element.mediaSession().removeBehaviorRestriction(restrictions);
3532
3533     restrictions = MediaElementSession::NoRestrictions;
3534
3535     for (StringView restrictionString : restrictionsString.split(',')) {
3536         if (equalLettersIgnoringASCIICase(restrictionString, "norestrictions"))
3537             restrictions |= MediaElementSession::NoRestrictions;
3538         if (equalLettersIgnoringASCIICase(restrictionString, "requireusergestureforload"))
3539             restrictions |= MediaElementSession::RequireUserGestureForLoad;
3540         if (equalLettersIgnoringASCIICase(restrictionString, "requireusergestureforvideoratechange"))
3541             restrictions |= MediaElementSession::RequireUserGestureForVideoRateChange;
3542         if (equalLettersIgnoringASCIICase(restrictionString, "requireusergestureforfullscreen"))
3543             restrictions |= MediaElementSession::RequireUserGestureForFullscreen;
3544         if (equalLettersIgnoringASCIICase(restrictionString, "requirepageconsenttoloadmedia"))
3545             restrictions |= MediaElementSession::RequirePageConsentToLoadMedia;
3546         if (equalLettersIgnoringASCIICase(restrictionString, "requirepageconsenttoresumemedia"))
3547             restrictions |= MediaElementSession::RequirePageConsentToResumeMedia;
3548 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
3549         if (equalLettersIgnoringASCIICase(restrictionString, "requireusergesturetoshowplaybacktargetpicker"))
3550             restrictions |= MediaElementSession::RequireUserGestureToShowPlaybackTargetPicker;
3551         if (equalLettersIgnoringASCIICase(restrictionString, "wirelessvideoplaybackdisabled"))
3552             restrictions |= MediaElementSession::WirelessVideoPlaybackDisabled;
3553 #endif
3554         if (equalLettersIgnoringASCIICase(restrictionString, "requireusergestureforaudioratechange"))
3555             restrictions |= MediaElementSession::RequireUserGestureForAudioRateChange;
3556         if (equalLettersIgnoringASCIICase(restrictionString, "metadatapreloadingnotpermitted"))
3557             restrictions |= MediaElementSession::MetadataPreloadingNotPermitted;
3558         if (equalLettersIgnoringASCIICase(restrictionString, "autopreloadingnotpermitted"))
3559             restrictions |= MediaElementSession::AutoPreloadingNotPermitted;
3560         if (equalLettersIgnoringASCIICase(restrictionString, "invisibleautoplaynotpermitted"))
3561             restrictions |= MediaElementSession::InvisibleAutoplayNotPermitted;
3562         if (equalLettersIgnoringASCIICase(restrictionString, "overrideusergesturerequirementformaincontent"))
3563             restrictions |= MediaElementSession::OverrideUserGestureRequirementForMainContent;
3564     }
3565     element.mediaSession().addBehaviorRestriction(restrictions);
3566 }
3567
3568 ExceptionOr<void> Internals::postRemoteControlCommand(const String& commandString, float argument)
3569 {
3570     PlatformMediaSession::RemoteControlCommandType command;
3571     PlatformMediaSession::RemoteCommandArgument parameter { argument };
3572
3573     if (equalLettersIgnoringASCIICase(commandString, "play"))
3574         command = PlatformMediaSession::PlayCommand;
3575     else if (equalLettersIgnoringASCIICase(commandString, "pause"))
3576         command = PlatformMediaSession::PauseCommand;
3577     else if (equalLettersIgnoringASCIICase(commandString, "stop"))
3578         command = PlatformMediaSession::StopCommand;
3579     else if (equalLettersIgnoringASCIICase(commandString, "toggleplaypause"))
3580         command = PlatformMediaSession::TogglePlayPauseCommand;
3581     else if (equalLettersIgnoringASCIICase(commandString, "beginseekingbackward"))
3582         command = PlatformMediaSession::BeginSeekingBackwardCommand;
3583     else if (equalLettersIgnoringASCIICase(commandString, "endseekingbackward"))
3584         command = PlatformMediaSession::EndSeekingBackwardCommand;
3585     else if (equalLettersIgnoringASCIICase(commandString, "beginseekingforward"))
3586         command = PlatformMediaSession::BeginSeekingForwardCommand;
3587     else if (equalLettersIgnoringASCIICase(commandString, "endseekingforward"))
3588         command = PlatformMediaSession::EndSeekingForwardCommand;
3589     else if (equalLettersIgnoringASCIICase(commandString, "seektoplaybackposition"))
3590         command = PlatformMediaSession::SeekToPlaybackPositionCommand;
3591     else
3592         return Exception { InvalidAccessError };
3593
3594     PlatformMediaSessionManager::sharedManager().didReceiveRemoteControlCommand(command, &parameter);
3595     return { };
3596 }
3597
3598 bool Internals::elementIsBlockingDisplaySleep(HTMLMediaElement& element) const
3599 {
3600     return element.isDisablingSleep();
3601 }
3602
3603 #endif // ENABLE(VIDEO)
3604
3605 #if ENABLE(MEDIA_SESSION)
3606
3607 void Internals::sendMediaSessionStartOfInterruptionNotification(MediaSessionInterruptingCategory category)
3608 {
3609     MediaSessionManager::singleton().didReceiveStartOfInterruptionNotification(category);
3610 }
3611
3612 void Internals::sendMediaSessionEndOfInterruptionNotification(MediaSessionInterruptingCategory category)
3613 {
3614     MediaSessionManager::singleton().didReceiveEndOfInterruptionNotification(category);
3615 }
3616
3617 String Internals::mediaSessionCurrentState(MediaSession* session) const
3618 {
3619     switch (session->currentState()) {
3620     case MediaSession::State::Active:
3621         return "active";
3622     case MediaSession::State::Interrupted:
3623         return "interrupted";
3624     case MediaSession::State::Idle:
3625         return "idle";
3626     }
3627 }
3628
3629 double Internals::mediaElementPlayerVolume(HTMLMediaElement* element) const
3630 {
3631     ASSERT_ARG(element, element);
3632     return element->playerVolume();
3633 }
3634
3635 void Internals::sendMediaControlEvent(MediaControlEvent event)
3636 {
3637     // FIXME: No good reason to use a single function with an argument instead of three functions.
3638     switch (event) {
3639     case MediControlEvent::PlayPause:
3640         MediaSessionManager::singleton().togglePlayback();
3641         break;
3642     case MediControlEvent::NextTrack:
3643         MediaSessionManager::singleton().skipToNextTrack();
3644         break;
3645     case MediControlEvent::PreviousTrack:
3646         MediaSessionManager::singleton().skipToPreviousTrack();
3647         break;
3648     }
3649 }
3650
3651 #endif // ENABLE(MEDIA_SESSION)
3652
3653 #if ENABLE(WEB_AUDIO)
3654
3655 void Internals::setAudioContextRestrictions(AudioContext& context, StringView restrictionsString)
3656 {
3657     AudioContext::BehaviorRestrictions restrictions = context.behaviorRestrictions();
3658     context.removeBehaviorRestriction(restrictions);
3659
3660     restrictions = AudioContext::NoRestrictions;
3661
3662     for (StringView restrictionString : restrictionsString.split(',')) {
3663         if (equalLettersIgnoringASCIICase(restrictionString, "norestrictions"))
3664             restrictions |= AudioContext::NoRestrictions;
3665         if (equalLettersIgnoringASCIICase(restrictionString, "requireusergestureforaudiostart"))
3666             restrictions |= AudioContext::RequireUserGestureForAudioStartRestriction;
3667         if (equalLettersIgnoringASCIICase(restrictionString, "requirepageconsentforaudiostart"))
3668             restrictions |= AudioContext::RequirePageConsentForAudioStartRestriction;
3669     }
3670     context.addBehaviorRestriction(restrictions);
3671 }
3672
3673 #endif
3674
3675 void Internals::simulateSystemSleep() const
3676 {
3677 #if ENABLE(VIDEO)
3678     PlatformMediaSessionManager::sharedManager().systemWillSleep();
3679 #endif
3680 }
3681
3682 void Internals::simulateSystemWake() const
3683 {
3684 #if ENABLE(VIDEO)
3685     PlatformMediaSessionManager::sharedManager().systemDidWake();
3686 #endif
3687 }
3688
3689 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
3690
3691 void Internals::setMockMediaPlaybackTargetPickerEnabled(bool enabled)
3692 {
3693     Page* page = contextDocument()->frame()->page();
3694     ASSERT(page);
3695
3696     page->setMockMediaPlaybackTargetPickerEnabled(enabled);
3697 }
3698
3699 ExceptionOr<void> Internals::setMockMediaPlaybackTargetPickerState(const String& deviceName, const String& deviceState)