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