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