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