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