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