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