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