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