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