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