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