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