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