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