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