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