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