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