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