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