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