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