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