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