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