Implement the updated port/area-based Scroll Snap Module Level 1 Spec
[WebKit-https.git] / Source / WebCore / testing / Internals.cpp
1 /*
2  * Copyright (C) 2012 Google Inc. All rights reserved.
3  * Copyright (C) 2013-2016 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 RefPtr<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 RefPtr<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     Document* 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     Page* inspectedPage = contextDocument()->frame()->page();
1860     RefPtr<DOMWindow> window = inspectedPage->mainFrame().document()->domWindow();
1861     RefPtr<DOMWindow> frontendWindow = window->open(url, "", "", *window, *window);
1862     m_inspectorFrontend = std::make_unique<InspectorStubFrontend>(*inspectedPage, frontendWindow.copyRef());
1863
1864     return frontendWindow;
1865 }
1866
1867 void Internals::closeDummyInspectorFrontend()
1868 {
1869     m_inspectorFrontend = nullptr;
1870 }
1871
1872 ExceptionOr<void> Internals::setInspectorIsUnderTest(bool isUnderTest)
1873 {
1874     Page* page = contextDocument()->frame()->page();
1875     if (!page)
1876         return Exception { INVALID_ACCESS_ERR };
1877
1878     page->inspectorController().setIsUnderTest(isUnderTest);
1879     return { };
1880 }
1881
1882 bool Internals::hasGrammarMarker(int from, int length)
1883 {
1884     Document* document = contextDocument();
1885     if (!document || !document->frame())
1886         return false;
1887
1888     return document->frame()->editor().selectionStartHasMarkerFor(DocumentMarker::Grammar, from, length);
1889 }
1890
1891 unsigned Internals::numberOfScrollableAreas()
1892 {
1893     Document* document = contextDocument();
1894     if (!document || !document->frame())
1895         return 0;
1896
1897     unsigned count = 0;
1898     Frame* frame = document->frame();
1899     if (frame->view()->scrollableAreas())
1900         count += frame->view()->scrollableAreas()->size();
1901
1902     for (Frame* child = frame->tree().firstChild(); child; child = child->tree().nextSibling()) {
1903         if (child->view() && child->view()->scrollableAreas())
1904             count += child->view()->scrollableAreas()->size();
1905     }
1906
1907     return count;
1908 }
1909     
1910 ExceptionOr<bool> Internals::isPageBoxVisible(int pageNumber)
1911 {
1912     Document* document = contextDocument();
1913     if (!document)
1914         return Exception { INVALID_ACCESS_ERR };
1915
1916     return document->isPageBoxVisible(pageNumber);
1917 }
1918
1919 // FIXME: Remove the document argument. It is almost always the same as
1920 // contextDocument(), with the exception of a few tests that pass a
1921 // different document, and could just make the call through another Internals
1922 // instance instead.
1923 ExceptionOr<String> Internals::layerTreeAsText(Document& document, unsigned short flags) const
1924 {
1925     if (!document.frame())
1926         return Exception { INVALID_ACCESS_ERR };
1927
1928     LayerTreeFlags layerTreeFlags = 0;
1929     if (flags & LAYER_TREE_INCLUDES_VISIBLE_RECTS)
1930         layerTreeFlags |= LayerTreeFlagsIncludeVisibleRects;
1931     if (flags & LAYER_TREE_INCLUDES_TILE_CACHES)
1932         layerTreeFlags |= LayerTreeFlagsIncludeTileCaches;
1933     if (flags & LAYER_TREE_INCLUDES_REPAINT_RECTS)
1934         layerTreeFlags |= LayerTreeFlagsIncludeRepaintRects;
1935     if (flags & LAYER_TREE_INCLUDES_PAINTING_PHASES)
1936         layerTreeFlags |= LayerTreeFlagsIncludePaintingPhases;
1937     if (flags & LAYER_TREE_INCLUDES_CONTENT_LAYERS)
1938         layerTreeFlags |= LayerTreeFlagsIncludeContentLayers;
1939
1940     return document.frame()->layerTreeAsText(layerTreeFlags);
1941 }
1942
1943 ExceptionOr<String> Internals::repaintRectsAsText() const
1944 {
1945     Document* document = contextDocument();
1946     if (!document || !document->frame())
1947         return Exception { INVALID_ACCESS_ERR };
1948
1949     return document->frame()->trackedRepaintRectsAsText();
1950 }
1951
1952 ExceptionOr<String> Internals::scrollingStateTreeAsText() const
1953 {
1954     Document* document = contextDocument();
1955     if (!document || !document->frame())
1956         return Exception { INVALID_ACCESS_ERR };
1957
1958     Page* page = document->page();
1959     if (!page)
1960         return String();
1961
1962     return page->scrollingStateTreeAsText();
1963 }
1964
1965 ExceptionOr<String> Internals::mainThreadScrollingReasons() const
1966 {
1967     Document* document = contextDocument();
1968     if (!document || !document->frame())
1969         return Exception { INVALID_ACCESS_ERR };
1970
1971     Page* page = document->page();
1972     if (!page)
1973         return String();
1974
1975     return page->synchronousScrollingReasonsAsText();
1976 }
1977
1978 ExceptionOr<RefPtr<ClientRectList>> Internals::nonFastScrollableRects() const
1979 {
1980     Document* document = contextDocument();
1981     if (!document || !document->frame())
1982         return Exception { INVALID_ACCESS_ERR };
1983
1984     Page* page = document->page();
1985     if (!page)
1986         return nullptr;
1987
1988     return RefPtr<ClientRectList> { page->nonFastScrollableRects() };
1989 }
1990
1991 ExceptionOr<void> Internals::setElementUsesDisplayListDrawing(Element& element, bool usesDisplayListDrawing)
1992 {
1993     Document* document = contextDocument();
1994     if (!document || !document->renderView())
1995         return Exception { INVALID_ACCESS_ERR };
1996
1997     if (!element.renderer())
1998         return Exception { INVALID_ACCESS_ERR };
1999
2000     if (is<HTMLCanvasElement>(element)) {
2001         downcast<HTMLCanvasElement>(element).setUsesDisplayListDrawing(usesDisplayListDrawing);
2002         return { };
2003     }
2004
2005     if (!element.renderer()->hasLayer())
2006         return Exception { INVALID_ACCESS_ERR };
2007     
2008     RenderLayer* layer = downcast<RenderLayerModelObject>(element.renderer())->layer();
2009     if (!layer->isComposited())
2010         return Exception { INVALID_ACCESS_ERR };
2011     
2012     layer->backing()->setUsesDisplayListDrawing(usesDisplayListDrawing);
2013     return { };
2014 }
2015
2016 ExceptionOr<void> Internals::setElementTracksDisplayListReplay(Element& element, bool isTrackingReplay)
2017 {
2018     Document* document = contextDocument();
2019     if (!document || !document->renderView())
2020         return Exception { INVALID_ACCESS_ERR };
2021
2022     if (!element.renderer())
2023         return Exception { INVALID_ACCESS_ERR };
2024
2025     if (is<HTMLCanvasElement>(element)) {
2026         downcast<HTMLCanvasElement>(element).setTracksDisplayListReplay(isTrackingReplay);
2027         return { };
2028     }
2029
2030     if (!element.renderer()->hasLayer())
2031         return Exception { INVALID_ACCESS_ERR };
2032
2033     RenderLayer* layer = downcast<RenderLayerModelObject>(element.renderer())->layer();
2034     if (!layer->isComposited())
2035         return Exception { INVALID_ACCESS_ERR };
2036     
2037     layer->backing()->setIsTrackingDisplayListReplay(isTrackingReplay);
2038     return { };
2039 }
2040
2041 ExceptionOr<String> Internals::displayListForElement(Element& element, unsigned short flags)
2042 {
2043     Document* document = contextDocument();
2044     if (!document || !document->renderView())
2045         return Exception { INVALID_ACCESS_ERR };
2046
2047     if (!element.renderer())
2048         return Exception { INVALID_ACCESS_ERR };
2049
2050     DisplayList::AsTextFlags displayListFlags = 0;
2051     if (flags & DISPLAY_LIST_INCLUDES_PLATFORM_OPERATIONS)
2052         displayListFlags |= DisplayList::AsTextFlag::IncludesPlatformOperations;
2053
2054     if (is<HTMLCanvasElement>(element))
2055         return downcast<HTMLCanvasElement>(element).displayListAsText(displayListFlags);
2056
2057     if (!element.renderer()->hasLayer())
2058         return Exception { INVALID_ACCESS_ERR };
2059
2060     RenderLayer* layer = downcast<RenderLayerModelObject>(element.renderer())->layer();
2061     if (!layer->isComposited())
2062         return Exception { INVALID_ACCESS_ERR };
2063
2064     return layer->backing()->displayListAsText(displayListFlags);
2065 }
2066
2067 ExceptionOr<String> Internals::replayDisplayListForElement(Element& element, unsigned short flags)
2068 {
2069     Document* document = contextDocument();
2070     if (!document || !document->renderView())
2071         return Exception { INVALID_ACCESS_ERR };
2072
2073     if (!element.renderer())
2074         return Exception { INVALID_ACCESS_ERR };
2075
2076     DisplayList::AsTextFlags displayListFlags = 0;
2077     if (flags & DISPLAY_LIST_INCLUDES_PLATFORM_OPERATIONS)
2078         displayListFlags |= DisplayList::AsTextFlag::IncludesPlatformOperations;
2079
2080     if (is<HTMLCanvasElement>(element))
2081         return downcast<HTMLCanvasElement>(element).replayDisplayListAsText(displayListFlags);
2082
2083     if (!element.renderer()->hasLayer())
2084         return Exception { INVALID_ACCESS_ERR };
2085
2086     RenderLayer* layer = downcast<RenderLayerModelObject>(element.renderer())->layer();
2087     if (!layer->isComposited())
2088         return Exception { INVALID_ACCESS_ERR };
2089
2090     return layer->backing()->replayDisplayListAsText(displayListFlags);
2091 }
2092
2093 ExceptionOr<void> Internals::garbageCollectDocumentResources() const
2094 {
2095     Document* document = contextDocument();
2096     if (!document)
2097         return Exception { INVALID_ACCESS_ERR };
2098     document->cachedResourceLoader().garbageCollectDocumentResources();
2099     return { };
2100 }
2101
2102 bool Internals::isUnderMemoryPressure()
2103 {
2104     return MemoryPressureHandler::singleton().isUnderMemoryPressure();
2105 }
2106
2107 void Internals::beginSimulatedMemoryPressure()
2108 {
2109     MemoryPressureHandler::singleton().beginSimulatedMemoryPressure();
2110 }
2111
2112 void Internals::endSimulatedMemoryPressure()
2113 {
2114     MemoryPressureHandler::singleton().endSimulatedMemoryPressure();
2115 }
2116
2117 ExceptionOr<void> Internals::insertAuthorCSS(const String& css) const
2118 {
2119     Document* document = contextDocument();
2120     if (!document)
2121         return Exception { INVALID_ACCESS_ERR };
2122
2123     auto parsedSheet = StyleSheetContents::create(*document);
2124     parsedSheet.get().setIsUserStyleSheet(false);
2125     parsedSheet.get().parseString(css);
2126     document->extensionStyleSheets().addAuthorStyleSheetForTesting(WTFMove(parsedSheet));
2127     return { };
2128 }
2129
2130 ExceptionOr<void> Internals::insertUserCSS(const String& css) const
2131 {
2132     Document* document = contextDocument();
2133     if (!document)
2134         return Exception { INVALID_ACCESS_ERR };
2135
2136     auto parsedSheet = StyleSheetContents::create(*document);
2137     parsedSheet.get().setIsUserStyleSheet(true);
2138     parsedSheet.get().parseString(css);
2139     document->extensionStyleSheets().addUserStyleSheet(WTFMove(parsedSheet));
2140     return { };
2141 }
2142
2143 String Internals::counterValue(Element& element)
2144 {
2145     return counterValueForElement(&element);
2146 }
2147
2148 int Internals::pageNumber(Element& element, float pageWidth, float pageHeight)
2149 {
2150     return PrintContext::pageNumberForElement(&element, { pageWidth, pageHeight });
2151 }
2152
2153 Vector<String> Internals::shortcutIconURLs() const
2154 {
2155     Vector<String> vector;
2156
2157     if (!frame())
2158         return vector;
2159
2160     auto string = frame()->loader().icon().url().string();
2161     if (!string.isNull())
2162         vector.append(string);
2163     return vector;
2164 }
2165
2166 int Internals::numberOfPages(float pageWidth, float pageHeight)
2167 {
2168     if (!frame())
2169         return -1;
2170
2171     return PrintContext::numberOfPages(*frame(), FloatSize(pageWidth, pageHeight));
2172 }
2173
2174 ExceptionOr<String> Internals::pageProperty(const String& propertyName, int pageNumber) const
2175 {
2176     if (!frame())
2177         return Exception { INVALID_ACCESS_ERR };
2178
2179     return PrintContext::pageProperty(frame(), propertyName.utf8().data(), pageNumber);
2180 }
2181
2182 ExceptionOr<String> Internals::pageSizeAndMarginsInPixels(int pageNumber, int width, int height, int marginTop, int marginRight, int marginBottom, int marginLeft) const
2183 {
2184     if (!frame())
2185         return Exception { INVALID_ACCESS_ERR };
2186
2187     return PrintContext::pageSizeAndMarginsInPixels(frame(), pageNumber, width, height, marginTop, marginRight, marginBottom, marginLeft);
2188 }
2189
2190 ExceptionOr<float> Internals::pageScaleFactor() const
2191 {
2192     Document* document = contextDocument();
2193     if (!document || !document->page())
2194         return Exception { INVALID_ACCESS_ERR };
2195
2196     return document->page()->pageScaleFactor();
2197 }
2198
2199 ExceptionOr<void> Internals::setPageScaleFactor(float scaleFactor, int x, int y)
2200 {
2201     Document* document = contextDocument();
2202     if (!document || !document->page())
2203         return Exception { INVALID_ACCESS_ERR };
2204
2205     document->page()->setPageScaleFactor(scaleFactor, IntPoint(x, y));
2206     return { };
2207 }
2208
2209 ExceptionOr<void> Internals::setPageZoomFactor(float zoomFactor)
2210 {
2211     Document* document = contextDocument();
2212     if (!document || !document->frame())
2213         return Exception { INVALID_ACCESS_ERR };
2214
2215     document->frame()->setPageZoomFactor(zoomFactor);
2216     return { };
2217 }
2218
2219 ExceptionOr<void> Internals::setTextZoomFactor(float zoomFactor)
2220 {
2221     Document* document = contextDocument();
2222     if (!document || !document->frame())
2223         return Exception { INVALID_ACCESS_ERR };
2224
2225     document->frame()->setTextZoomFactor(zoomFactor);
2226     return { };
2227 }
2228
2229 ExceptionOr<void> Internals::setUseFixedLayout(bool useFixedLayout)
2230 {
2231     Document* document = contextDocument();
2232     if (!document || !document->view())
2233         return Exception { INVALID_ACCESS_ERR };
2234
2235     document->view()->setUseFixedLayout(useFixedLayout);
2236     return { };
2237 }
2238
2239 ExceptionOr<void> Internals::setFixedLayoutSize(int width, int height)
2240 {
2241     Document* document = contextDocument();
2242     if (!document || !document->view())
2243         return Exception { INVALID_ACCESS_ERR };
2244
2245     document->view()->setFixedLayoutSize(IntSize(width, height));
2246     return { };
2247 }
2248
2249 ExceptionOr<void> Internals::setViewExposedRect(float x, float y, float width, float height)
2250 {
2251     Document* document = contextDocument();
2252     if (!document || !document->view())
2253         return Exception { INVALID_ACCESS_ERR };
2254
2255     document->view()->setViewExposedRect(FloatRect(x, y, width, height));
2256     return { };
2257 }
2258
2259 void Internals::setHeaderHeight(float height)
2260 {
2261     Document* document = contextDocument();
2262     if (!document || !document->view())
2263         return;
2264
2265     document->view()->setHeaderHeight(height);
2266 }
2267
2268 void Internals::setFooterHeight(float height)
2269 {
2270     Document* document = contextDocument();
2271     if (!document || !document->view())
2272         return;
2273
2274     document->view()->setFooterHeight(height);
2275 }
2276     
2277 void Internals::setTopContentInset(float contentInset)
2278 {
2279     Document* document = contextDocument();
2280     if (!document || !document->page())
2281         return;
2282
2283     document->page()->setTopContentInset(contentInset);
2284 }
2285
2286 #if ENABLE(FULLSCREEN_API)
2287
2288 void Internals::webkitWillEnterFullScreenForElement(Element& element)
2289 {
2290     Document* document = contextDocument();
2291     if (!document)
2292         return;
2293     document->webkitWillEnterFullScreenForElement(&element);
2294 }
2295
2296 void Internals::webkitDidEnterFullScreenForElement(Element& element)
2297 {
2298     Document* document = contextDocument();
2299     if (!document)
2300         return;
2301     document->webkitDidEnterFullScreenForElement(&element);
2302 }
2303
2304 void Internals::webkitWillExitFullScreenForElement(Element& element)
2305 {
2306     Document* document = contextDocument();
2307     if (!document)
2308         return;
2309     document->webkitWillExitFullScreenForElement(&element);
2310 }
2311
2312 void Internals::webkitDidExitFullScreenForElement(Element& element)
2313 {
2314     Document* document = contextDocument();
2315     if (!document)
2316         return;
2317     document->webkitDidExitFullScreenForElement(&element);
2318 }
2319
2320 #endif
2321
2322 void Internals::setApplicationCacheOriginQuota(unsigned long long quota)
2323 {
2324     Document* document = contextDocument();
2325     if (!document || !document->page())
2326         return;
2327     document->page()->applicationCacheStorage().storeUpdatedQuotaForOrigin(document->securityOrigin(), quota);
2328 }
2329
2330 void Internals::registerURLSchemeAsBypassingContentSecurityPolicy(const String& scheme)
2331 {
2332     SchemeRegistry::registerURLSchemeAsBypassingContentSecurityPolicy(scheme);
2333 }
2334
2335 void Internals::removeURLSchemeRegisteredAsBypassingContentSecurityPolicy(const String& scheme)
2336 {
2337     SchemeRegistry::removeURLSchemeRegisteredAsBypassingContentSecurityPolicy(scheme);
2338 }
2339
2340 void Internals::registerDefaultPortForProtocol(unsigned short port, const String& protocol)
2341 {
2342     registerDefaultPortForProtocolForTesting(port, protocol);
2343 }
2344
2345 Ref<MallocStatistics> Internals::mallocStatistics() const
2346 {
2347     return MallocStatistics::create();
2348 }
2349
2350 Ref<TypeConversions> Internals::typeConversions() const
2351 {
2352     return TypeConversions::create();
2353 }
2354
2355 Ref<MemoryInfo> Internals::memoryInfo() const
2356 {
2357     return MemoryInfo::create();
2358 }
2359
2360 Vector<String> Internals::getReferencedFilePaths() const
2361 {
2362     frame()->loader().history().saveDocumentAndScrollState();
2363     return FormController::getReferencedFilePaths(frame()->loader().history().currentItem()->documentState());
2364 }
2365
2366 ExceptionOr<void> Internals::startTrackingRepaints()
2367 {
2368     Document* document = contextDocument();
2369     if (!document || !document->view())
2370         return Exception { INVALID_ACCESS_ERR };
2371
2372     document->view()->setTracksRepaints(true);
2373     return { };
2374 }
2375
2376 ExceptionOr<void> Internals::stopTrackingRepaints()
2377 {
2378     Document* document = contextDocument();
2379     if (!document || !document->view())
2380         return Exception { INVALID_ACCESS_ERR };
2381
2382     document->view()->setTracksRepaints(false);
2383     return { };
2384 }
2385
2386 ExceptionOr<void> Internals::startTrackingLayerFlushes()
2387 {
2388     Document* document = contextDocument();
2389     if (!document || !document->renderView())
2390         return Exception { INVALID_ACCESS_ERR };
2391
2392     document->renderView()->compositor().startTrackingLayerFlushes();
2393     return { };
2394 }
2395
2396 ExceptionOr<unsigned> Internals::layerFlushCount()
2397 {
2398     Document* document = contextDocument();
2399     if (!document || !document->renderView())
2400         return Exception { INVALID_ACCESS_ERR };
2401
2402     return document->renderView()->compositor().layerFlushCount();
2403 }
2404
2405 ExceptionOr<void> Internals::startTrackingStyleRecalcs()
2406 {
2407     Document* document = contextDocument();
2408     if (!document)
2409         return Exception { INVALID_ACCESS_ERR };
2410
2411     document->startTrackingStyleRecalcs();
2412     return { };
2413 }
2414
2415 ExceptionOr<unsigned> Internals::styleRecalcCount()
2416 {
2417     Document* document = contextDocument();
2418     if (!document)
2419         return Exception { INVALID_ACCESS_ERR };
2420     
2421     return document->styleRecalcCount();
2422 }
2423
2424 unsigned Internals::lastStyleUpdateSize() const
2425 {
2426     Document* document = contextDocument();
2427     if (!document)
2428         return 0;
2429     return document->lastStyleUpdateSizeForTesting();
2430 }
2431
2432 ExceptionOr<void> Internals::startTrackingCompositingUpdates()
2433 {
2434     Document* document = contextDocument();
2435     if (!document || !document->renderView())
2436         return Exception { INVALID_ACCESS_ERR };
2437
2438     document->renderView()->compositor().startTrackingCompositingUpdates();
2439     return { };
2440 }
2441
2442 ExceptionOr<unsigned> Internals::compositingUpdateCount()
2443 {
2444     Document* document = contextDocument();
2445     if (!document || !document->renderView())
2446         return Exception { INVALID_ACCESS_ERR };
2447     
2448     return document->renderView()->compositor().compositingUpdateCount();
2449 }
2450
2451 ExceptionOr<void> Internals::updateLayoutIgnorePendingStylesheetsAndRunPostLayoutTasks(Node* node)
2452 {
2453     Document* document;
2454     if (!node)
2455         document = contextDocument();
2456     else if (is<Document>(*node))
2457         document = downcast<Document>(node);
2458     else if (is<HTMLIFrameElement>(*node))
2459         document = downcast<HTMLIFrameElement>(*node).contentDocument();
2460     else
2461         return Exception { TypeError };
2462
2463     document->updateLayoutIgnorePendingStylesheets(Document::RunPostLayoutTasks::Synchronously);
2464     return { };
2465 }
2466
2467 unsigned Internals::layoutCount() const
2468 {
2469     Document* document = contextDocument();
2470     if (!document || !document->view())
2471         return 0;
2472     return document->view()->layoutCount();
2473 }
2474
2475 #if !PLATFORM(IOS)
2476 static const char* cursorTypeToString(Cursor::Type cursorType)
2477 {
2478     switch (cursorType) {
2479     case Cursor::Pointer: return "Pointer";
2480     case Cursor::Cross: return "Cross";
2481     case Cursor::Hand: return "Hand";
2482     case Cursor::IBeam: return "IBeam";
2483     case Cursor::Wait: return "Wait";
2484     case Cursor::Help: return "Help";
2485     case Cursor::EastResize: return "EastResize";
2486     case Cursor::NorthResize: return "NorthResize";
2487     case Cursor::NorthEastResize: return "NorthEastResize";
2488     case Cursor::NorthWestResize: return "NorthWestResize";
2489     case Cursor::SouthResize: return "SouthResize";
2490     case Cursor::SouthEastResize: return "SouthEastResize";
2491     case Cursor::SouthWestResize: return "SouthWestResize";
2492     case Cursor::WestResize: return "WestResize";
2493     case Cursor::NorthSouthResize: return "NorthSouthResize";
2494     case Cursor::EastWestResize: return "EastWestResize";
2495     case Cursor::NorthEastSouthWestResize: return "NorthEastSouthWestResize";
2496     case Cursor::NorthWestSouthEastResize: return "NorthWestSouthEastResize";
2497     case Cursor::ColumnResize: return "ColumnResize";
2498     case Cursor::RowResize: return "RowResize";
2499     case Cursor::MiddlePanning: return "MiddlePanning";
2500     case Cursor::EastPanning: return "EastPanning";
2501     case Cursor::NorthPanning: return "NorthPanning";
2502     case Cursor::NorthEastPanning: return "NorthEastPanning";
2503     case Cursor::NorthWestPanning: return "NorthWestPanning";
2504     case Cursor::SouthPanning: return "SouthPanning";
2505     case Cursor::SouthEastPanning: return "SouthEastPanning";
2506     case Cursor::SouthWestPanning: return "SouthWestPanning";
2507     case Cursor::WestPanning: return "WestPanning";
2508     case Cursor::Move: return "Move";
2509     case Cursor::VerticalText: return "VerticalText";
2510     case Cursor::Cell: return "Cell";
2511     case Cursor::ContextMenu: return "ContextMenu";
2512     case Cursor::Alias: return "Alias";
2513     case Cursor::Progress: return "Progress";
2514     case Cursor::NoDrop: return "NoDrop";
2515     case Cursor::Copy: return "Copy";
2516     case Cursor::None: return "None";
2517     case Cursor::NotAllowed: return "NotAllowed";
2518     case Cursor::ZoomIn: return "ZoomIn";
2519     case Cursor::ZoomOut: return "ZoomOut";
2520     case Cursor::Grab: return "Grab";
2521     case Cursor::Grabbing: return "Grabbing";
2522     case Cursor::Custom: return "Custom";
2523     }
2524
2525     ASSERT_NOT_REACHED();
2526     return "UNKNOWN";
2527 }
2528 #endif
2529
2530 ExceptionOr<String> Internals::getCurrentCursorInfo()
2531 {
2532     Document* document = contextDocument();
2533     if (!document || !document->frame())
2534         return Exception { INVALID_ACCESS_ERR };
2535
2536 #if !PLATFORM(IOS)
2537     Cursor cursor = document->frame()->eventHandler().currentMouseCursor();
2538
2539     StringBuilder result;
2540     result.appendLiteral("type=");
2541     result.append(cursorTypeToString(cursor.type()));
2542     result.appendLiteral(" hotSpot=");
2543     result.appendNumber(cursor.hotSpot().x());
2544     result.append(',');
2545     result.appendNumber(cursor.hotSpot().y());
2546     if (cursor.image()) {
2547         FloatSize size = cursor.image()->size();
2548         result.appendLiteral(" image=");
2549         result.appendNumber(size.width());
2550         result.append('x');
2551         result.appendNumber(size.height());
2552     }
2553 #if ENABLE(MOUSE_CURSOR_SCALE)
2554     if (cursor.imageScaleFactor() != 1) {
2555         result.appendLiteral(" scale=");
2556         NumberToStringBuffer buffer;
2557         result.append(numberToFixedPrecisionString(cursor.imageScaleFactor(), 8, buffer, true));
2558     }
2559 #endif
2560     return result.toString();
2561 #else
2562     return String { "FAIL: Cursor details not available on this platform." };
2563 #endif
2564 }
2565
2566 RefPtr<ArrayBuffer> Internals::serializeObject(PassRefPtr<SerializedScriptValue> value) const
2567 {
2568     auto& bytes = value->data();
2569     return ArrayBuffer::create(bytes.data(), bytes.size());
2570 }
2571
2572 RefPtr<SerializedScriptValue> Internals::deserializeBuffer(ArrayBuffer& buffer) const
2573 {
2574     Vector<uint8_t> bytes;
2575     bytes.append(static_cast<const uint8_t*>(buffer.data()), buffer.byteLength());
2576     return SerializedScriptValue::adopt(WTFMove(bytes));
2577 }
2578
2579 bool Internals::isFromCurrentWorld(JSC::JSValue value) const
2580 {
2581     ASSERT(value);
2582     JSC::ExecState& state = *contextDocument()->vm().topCallFrame;
2583     return !value.isObject() || &worldForDOMObject(asObject(value)) == &currentWorld(&state);
2584 }
2585
2586 void Internals::setUsesOverlayScrollbars(bool enabled)
2587 {
2588     WebCore::Settings::setUsesOverlayScrollbars(enabled);
2589 }
2590
2591 void Internals::setUsesMockScrollAnimator(bool enabled)
2592 {
2593     WebCore::Settings::setUsesMockScrollAnimator(enabled);
2594 }
2595
2596 void Internals::forceReload(bool endToEnd)
2597 {
2598     frame()->loader().reload(endToEnd);
2599 }
2600
2601 void Internals::enableAutoSizeMode(bool enabled, int minimumWidth, int minimumHeight, int maximumWidth, int maximumHeight)
2602 {
2603     Document* document = contextDocument();
2604     if (!document || !document->view())
2605         return;
2606     document->view()->enableAutoSizeMode(enabled, IntSize(minimumWidth, minimumHeight), IntSize(maximumWidth, maximumHeight));
2607 }
2608
2609 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
2610 void Internals::initializeMockCDM()
2611 {
2612     CDM::registerCDMFactory([](CDM* cdm) { return std::make_unique<MockCDM>(cdm); },
2613         MockCDM::supportsKeySystem, MockCDM::supportsKeySystemAndMimeType);
2614 }
2615 #endif
2616
2617 #if ENABLE(ENCRYPTED_MEDIA)
2618 Ref<MockCDMFactory> Internals::registerMockCDM()
2619 {
2620     return MockCDMFactory::create();
2621 }
2622 #endif
2623
2624
2625 String Internals::markerTextForListItem(Element& element)
2626 {
2627     return WebCore::markerTextForListItem(&element);
2628 }
2629
2630 String Internals::toolTipFromElement(Element& element) const
2631 {
2632     HitTestResult result;
2633     result.setInnerNode(&element);
2634     TextDirection direction;
2635     return result.title(direction);
2636 }
2637
2638 String Internals::getImageSourceURL(Element& element)
2639 {
2640     return element.imageSourceURL();
2641 }
2642
2643 #if ENABLE(VIDEO)
2644
2645 void Internals::simulateAudioInterruption(HTMLMediaElement& element)
2646 {
2647 #if USE(GSTREAMER)
2648     element.player()->simulateAudioInterruption();
2649 #else
2650     UNUSED_PARAM(element);
2651 #endif
2652 }
2653
2654 ExceptionOr<bool> Internals::mediaElementHasCharacteristic(HTMLMediaElement& element, const String& characteristic)
2655 {
2656     if (equalLettersIgnoringASCIICase(characteristic, "audible"))
2657         return element.hasAudio();
2658     if (equalLettersIgnoringASCIICase(characteristic, "visual"))
2659         return element.hasVideo();
2660     if (equalLettersIgnoringASCIICase(characteristic, "legible"))
2661         return element.hasClosedCaptions();
2662
2663     return Exception { SYNTAX_ERR };
2664 }
2665
2666 #endif
2667
2668 bool Internals::isSelectPopupVisible(HTMLSelectElement& element)
2669 {
2670     auto* renderer = element.renderer();
2671     ASSERT(renderer);
2672     if (!is<RenderMenuList>(*renderer))
2673         return false;
2674
2675 #if !PLATFORM(IOS)
2676     return downcast<RenderMenuList>(*renderer).popupIsVisible();
2677 #else
2678     return false;
2679 #endif
2680 }
2681
2682 ExceptionOr<String> Internals::captionsStyleSheetOverride()
2683 {
2684     Document* document = contextDocument();
2685     if (!document || !document->page())
2686         return Exception { INVALID_ACCESS_ERR };
2687
2688 #if ENABLE(VIDEO_TRACK)
2689     return document->page()->group().captionPreferences().captionsStyleSheetOverride();
2690 #else
2691     return String { emptyString() };
2692 #endif
2693 }
2694
2695 ExceptionOr<void> Internals::setCaptionsStyleSheetOverride(const String& override)
2696 {
2697     Document* document = contextDocument();
2698     if (!document || !document->page())
2699         return Exception { INVALID_ACCESS_ERR };
2700
2701 #if ENABLE(VIDEO_TRACK)
2702     document->page()->group().captionPreferences().setCaptionsStyleSheetOverride(override);
2703 #else
2704     UNUSED_PARAM(override);
2705 #endif
2706     return { };
2707 }
2708
2709 ExceptionOr<void> Internals::setPrimaryAudioTrackLanguageOverride(const String& language)
2710 {
2711     Document* document = contextDocument();
2712     if (!document || !document->page())
2713         return Exception { INVALID_ACCESS_ERR };
2714
2715 #if ENABLE(VIDEO_TRACK)
2716     document->page()->group().captionPreferences().setPrimaryAudioTrackLanguageOverride(language);
2717 #else
2718     UNUSED_PARAM(language);
2719 #endif
2720     return { };
2721 }
2722
2723 ExceptionOr<void> Internals::setCaptionDisplayMode(const String& mode)
2724 {
2725     Document* document = contextDocument();
2726     if (!document || !document->page())
2727         return Exception { INVALID_ACCESS_ERR };
2728     
2729 #if ENABLE(VIDEO_TRACK)
2730     auto& captionPreferences = document->page()->group().captionPreferences();
2731     
2732     if (equalLettersIgnoringASCIICase(mode, "automatic"))
2733         captionPreferences.setCaptionDisplayMode(CaptionUserPreferences::Automatic);
2734     else if (equalLettersIgnoringASCIICase(mode, "forcedonly"))
2735         captionPreferences.setCaptionDisplayMode(CaptionUserPreferences::ForcedOnly);
2736     else if (equalLettersIgnoringASCIICase(mode, "alwayson"))
2737         captionPreferences.setCaptionDisplayMode(CaptionUserPreferences::AlwaysOn);
2738     else if (equalLettersIgnoringASCIICase(mode, "manual"))
2739         captionPreferences.setCaptionDisplayMode(CaptionUserPreferences::Manual);
2740     else
2741         return Exception { SYNTAX_ERR };
2742 #else
2743     UNUSED_PARAM(mode);
2744 #endif
2745     return { };
2746 }
2747
2748 #if ENABLE(VIDEO)
2749
2750 Ref<TimeRanges> Internals::createTimeRanges(Float32Array& startTimes, Float32Array& endTimes)
2751 {
2752     ASSERT(startTimes.length() == endTimes.length());
2753     Ref<TimeRanges> ranges = TimeRanges::create();
2754
2755     unsigned count = std::min(startTimes.length(), endTimes.length());
2756     for (unsigned i = 0; i < count; ++i)
2757         ranges->add(startTimes.item(i), endTimes.item(i));
2758     return ranges;
2759 }
2760
2761 double Internals::closestTimeToTimeRanges(double time, TimeRanges& ranges)
2762 {
2763     return ranges.nearest(time);
2764 }
2765
2766 #endif
2767
2768 ExceptionOr<Ref<ClientRect>> Internals::selectionBounds()
2769 {
2770     Document* document = contextDocument();
2771     if (!document || !document->frame())
2772         return Exception { INVALID_ACCESS_ERR };
2773
2774     return ClientRect::create(document->frame()->selection().selectionBounds());
2775 }
2776
2777 #if ENABLE(VIBRATION)
2778
2779 bool Internals::isVibrating()
2780 {
2781     auto* document = contextDocument();
2782     auto* page = document ? document->page() : nullptr;
2783     return page && Vibration::from(page)->isVibrating();
2784 }
2785
2786 #endif
2787
2788 ExceptionOr<bool> Internals::isPluginUnavailabilityIndicatorObscured(Element& element)
2789 {
2790     auto* renderer = element.renderer();
2791     if (!is<RenderEmbeddedObject>(renderer))
2792         return Exception { INVALID_ACCESS_ERR };
2793
2794     return downcast<RenderEmbeddedObject>(*renderer).isReplacementObscured();
2795 }
2796     
2797 bool Internals::isPluginSnapshotted(Element& element)
2798 {
2799     return is<HTMLPlugInElement>(element) && downcast<HTMLPlugInElement>(element).displayState() <= HTMLPlugInElement::DisplayingSnapshot;
2800 }
2801     
2802 #if ENABLE(MEDIA_SOURCE)
2803
2804 void Internals::initializeMockMediaSource()
2805 {
2806 #if USE(AVFOUNDATION)
2807     WebCore::Settings::setAVFoundationEnabled(false);
2808 #endif
2809 #if USE(GSTREAMER)
2810     WebCore::Settings::setGStreamerEnabled(false);
2811 #endif
2812     MediaPlayerFactorySupport::callRegisterMediaEngine(MockMediaPlayerMediaSource::registerMediaEngine);
2813 }
2814
2815 Vector<String> Internals::bufferedSamplesForTrackID(SourceBuffer& buffer, const AtomicString& trackID)
2816 {
2817     return buffer.bufferedSamplesForTrackID(trackID);
2818 }
2819     
2820 Vector<String> Internals::enqueuedSamplesForTrackID(SourceBuffer& buffer, const AtomicString& trackID)
2821 {
2822     return buffer.enqueuedSamplesForTrackID(trackID);
2823 }
2824
2825 void Internals::setShouldGenerateTimestamps(SourceBuffer& buffer, bool flag)
2826 {
2827     buffer.setShouldGenerateTimestamps(flag);
2828 }
2829
2830 #endif
2831
2832 #if ENABLE(VIDEO)
2833
2834 ExceptionOr<void> Internals::beginMediaSessionInterruption(const String& interruptionString)
2835 {
2836     PlatformMediaSession::InterruptionType interruption = PlatformMediaSession::SystemInterruption;
2837
2838     if (equalLettersIgnoringASCIICase(interruptionString, "system"))
2839         interruption = PlatformMediaSession::SystemInterruption;
2840     else if (equalLettersIgnoringASCIICase(interruptionString, "systemsleep"))
2841         interruption = PlatformMediaSession::SystemSleep;
2842     else if (equalLettersIgnoringASCIICase(interruptionString, "enteringbackground"))
2843         interruption = PlatformMediaSession::EnteringBackground;
2844     else if (equalLettersIgnoringASCIICase(interruptionString, "suspendedunderlock"))
2845         interruption = PlatformMediaSession::SuspendedUnderLock;
2846     else
2847         return Exception { INVALID_ACCESS_ERR };
2848
2849     PlatformMediaSessionManager::sharedManager().beginInterruption(interruption);
2850     return { };
2851 }
2852
2853 void Internals::endMediaSessionInterruption(const String& flagsString)
2854 {
2855     PlatformMediaSession::EndInterruptionFlags flags = PlatformMediaSession::NoFlags;
2856
2857     if (equalLettersIgnoringASCIICase(flagsString, "mayresumeplaying"))
2858         flags = PlatformMediaSession::MayResumePlaying;
2859     
2860     PlatformMediaSessionManager::sharedManager().endInterruption(flags);
2861 }
2862
2863 void Internals::applicationDidEnterForeground() const
2864 {
2865     PlatformMediaSessionManager::sharedManager().applicationDidEnterForeground();
2866 }
2867
2868 void Internals::applicationWillEnterBackground() const
2869 {
2870     PlatformMediaSessionManager::sharedManager().applicationWillEnterBackground();
2871 }
2872
2873 static PlatformMediaSession::MediaType mediaTypeFromString(const String& mediaTypeString)
2874 {
2875     if (equalLettersIgnoringASCIICase(mediaTypeString, "video"))
2876         return PlatformMediaSession::Video;
2877     if (equalLettersIgnoringASCIICase(mediaTypeString, "audio"))
2878         return PlatformMediaSession::Audio;
2879     if (equalLettersIgnoringASCIICase(mediaTypeString, "videoaudio"))
2880         return PlatformMediaSession::VideoAudio;
2881     if (equalLettersIgnoringASCIICase(mediaTypeString, "webaudio"))
2882         return PlatformMediaSession::WebAudio;
2883
2884     return PlatformMediaSession::None;
2885 }
2886
2887 ExceptionOr<void> Internals::setMediaSessionRestrictions(const String& mediaTypeString, const String& restrictionsString)
2888 {
2889     PlatformMediaSession::MediaType mediaType = mediaTypeFromString(mediaTypeString);
2890     if (mediaType == PlatformMediaSession::None)
2891         return Exception { INVALID_ACCESS_ERR };
2892
2893     PlatformMediaSessionManager::SessionRestrictions restrictions = PlatformMediaSessionManager::sharedManager().restrictions(mediaType);
2894     PlatformMediaSessionManager::sharedManager().removeRestriction(mediaType, restrictions);
2895
2896     restrictions = PlatformMediaSessionManager::NoRestrictions;
2897
2898     Vector<String> restrictionsArray;
2899     restrictionsString.split(',', false, restrictionsArray);
2900     for (auto& restrictionString : restrictionsArray) {
2901         if (equalLettersIgnoringASCIICase(restrictionString, "concurrentplaybacknotpermitted"))
2902             restrictions |= PlatformMediaSessionManager::ConcurrentPlaybackNotPermitted;
2903         if (equalLettersIgnoringASCIICase(restrictionString, "backgroundprocessplaybackrestricted"))
2904             restrictions |= PlatformMediaSessionManager::BackgroundProcessPlaybackRestricted;
2905         if (equalLettersIgnoringASCIICase(restrictionString, "backgroundtabplaybackrestricted"))
2906             restrictions |= PlatformMediaSessionManager::BackgroundTabPlaybackRestricted;
2907         if (equalLettersIgnoringASCIICase(restrictionString, "interruptedplaybacknotpermitted"))
2908             restrictions |= PlatformMediaSessionManager::InterruptedPlaybackNotPermitted;
2909     }
2910     PlatformMediaSessionManager::sharedManager().addRestriction(mediaType, restrictions);
2911     return { };
2912 }
2913
2914 ExceptionOr<String> Internals::mediaSessionRestrictions(const String& mediaTypeString) const
2915 {
2916     PlatformMediaSession::MediaType mediaType = mediaTypeFromString(mediaTypeString);
2917     if (mediaType == PlatformMediaSession::None)
2918         return Exception { INVALID_ACCESS_ERR };
2919
2920     PlatformMediaSessionManager::SessionRestrictions restrictions = PlatformMediaSessionManager::sharedManager().restrictions(mediaType);
2921     if (restrictions == PlatformMediaSessionManager::NoRestrictions)
2922         return String();
2923
2924     StringBuilder builder;
2925     if (restrictions & PlatformMediaSessionManager::ConcurrentPlaybackNotPermitted)
2926         builder.append("concurrentplaybacknotpermitted");
2927     if (restrictions & PlatformMediaSessionManager::BackgroundProcessPlaybackRestricted) {
2928         if (!builder.isEmpty())
2929             builder.append(',');
2930         builder.append("backgroundprocessplaybackrestricted");
2931     }
2932     if (restrictions & PlatformMediaSessionManager::BackgroundTabPlaybackRestricted) {
2933         if (!builder.isEmpty())
2934             builder.append(',');
2935         builder.append("backgroundtabplaybackrestricted");
2936     }
2937     if (restrictions & PlatformMediaSessionManager::InterruptedPlaybackNotPermitted) {
2938         if (!builder.isEmpty())
2939             builder.append(',');
2940         builder.append("interruptedplaybacknotpermitted");
2941     }
2942     return builder.toString();
2943 }
2944
2945 void Internals::setMediaElementRestrictions(HTMLMediaElement& element, const String& restrictionsString)
2946 {
2947     MediaElementSession::BehaviorRestrictions restrictions = element.mediaSession().behaviorRestrictions();
2948     element.mediaSession().removeBehaviorRestriction(restrictions);
2949
2950     restrictions = MediaElementSession::NoRestrictions;
2951
2952     Vector<String> restrictionsArray;
2953     restrictionsString.split(',', false, restrictionsArray);
2954     for (auto& restrictionString : restrictionsArray) {
2955         if (equalLettersIgnoringASCIICase(restrictionString, "norestrictions"))
2956             restrictions |= MediaElementSession::NoRestrictions;
2957         if (equalLettersIgnoringASCIICase(restrictionString, "requireusergestureforload"))
2958             restrictions |= MediaElementSession::RequireUserGestureForLoad;
2959         if (equalLettersIgnoringASCIICase(restrictionString, "requireusergestureforvideoratechange"))
2960             restrictions |= MediaElementSession::RequireUserGestureForVideoRateChange;
2961         if (equalLettersIgnoringASCIICase(restrictionString, "requireusergestureforfullscreen"))
2962             restrictions |= MediaElementSession::RequireUserGestureForFullscreen;
2963         if (equalLettersIgnoringASCIICase(restrictionString, "requirepageconsenttoloadmedia"))
2964             restrictions |= MediaElementSession::RequirePageConsentToLoadMedia;
2965         if (equalLettersIgnoringASCIICase(restrictionString, "requirepageconsenttoresumemedia"))
2966             restrictions |= MediaElementSession::RequirePageConsentToResumeMedia;
2967 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2968         if (equalLettersIgnoringASCIICase(restrictionString, "requireusergesturetoshowplaybacktargetpicker"))
2969             restrictions |= MediaElementSession::RequireUserGestureToShowPlaybackTargetPicker;
2970         if (equalLettersIgnoringASCIICase(restrictionString, "wirelessvideoplaybackdisabled"))
2971             restrictions |= MediaElementSession::WirelessVideoPlaybackDisabled;
2972 #endif
2973         if (equalLettersIgnoringASCIICase(restrictionString, "requireusergestureforaudioratechange"))
2974             restrictions |= MediaElementSession::RequireUserGestureForAudioRateChange;
2975         if (equalLettersIgnoringASCIICase(restrictionString, "metadatapreloadingnotpermitted"))
2976             restrictions |= MediaElementSession::MetadataPreloadingNotPermitted;
2977         if (equalLettersIgnoringASCIICase(restrictionString, "autopreloadingnotpermitted"))
2978             restrictions |= MediaElementSession::AutoPreloadingNotPermitted;
2979         if (equalLettersIgnoringASCIICase(restrictionString, "invisibleautoplaynotpermitted"))
2980             restrictions |= MediaElementSession::InvisibleAutoplayNotPermitted;
2981         if (equalLettersIgnoringASCIICase(restrictionString, "overrideusergesturerequirementformaincontent"))
2982             restrictions |= MediaElementSession::OverrideUserGestureRequirementForMainContent;
2983     }
2984     element.mediaSession().addBehaviorRestriction(restrictions);
2985 }
2986
2987 ExceptionOr<void> Internals::postRemoteControlCommand(const String& commandString, float argument)
2988 {
2989     PlatformMediaSession::RemoteControlCommandType command;
2990     PlatformMediaSession::RemoteCommandArgument parameter { argument };
2991
2992     if (equalLettersIgnoringASCIICase(commandString, "play"))
2993         command = PlatformMediaSession::PlayCommand;
2994     else if (equalLettersIgnoringASCIICase(commandString, "pause"))
2995         command = PlatformMediaSession::PauseCommand;
2996     else if (equalLettersIgnoringASCIICase(commandString, "stop"))
2997         command = PlatformMediaSession::StopCommand;
2998     else if (equalLettersIgnoringASCIICase(commandString, "toggleplaypause"))
2999         command = PlatformMediaSession::TogglePlayPauseCommand;
3000     else if (equalLettersIgnoringASCIICase(commandString, "beginseekingbackward"))
3001         command = PlatformMediaSession::BeginSeekingBackwardCommand;
3002     else if (equalLettersIgnoringASCIICase(commandString, "endseekingbackward"))
3003         command = PlatformMediaSession::EndSeekingBackwardCommand;
3004     else if (equalLettersIgnoringASCIICase(commandString, "beginseekingforward"))
3005         command = PlatformMediaSession::BeginSeekingForwardCommand;
3006     else if (equalLettersIgnoringASCIICase(commandString, "endseekingforward"))
3007         command = PlatformMediaSession::EndSeekingForwardCommand;
3008     else if (equalLettersIgnoringASCIICase(commandString, "seektoplaybackposition"))
3009         command = PlatformMediaSession::SeekToPlaybackPositionCommand;
3010     else
3011         return Exception { INVALID_ACCESS_ERR };
3012     
3013     PlatformMediaSessionManager::sharedManager().didReceiveRemoteControlCommand(command, &parameter);
3014     return { };
3015 }
3016
3017 bool Internals::elementIsBlockingDisplaySleep(HTMLMediaElement& element) const
3018 {
3019     return element.isDisablingSleep();
3020 }
3021
3022 #endif // ENABLE(VIDEO)
3023
3024 #if ENABLE(MEDIA_SESSION)
3025
3026 void Internals::sendMediaSessionStartOfInterruptionNotification(MediaSessionInterruptingCategory category)
3027 {
3028     MediaSessionManager::singleton().didReceiveStartOfInterruptionNotification(category);
3029 }
3030
3031 void Internals::sendMediaSessionEndOfInterruptionNotification(MediaSessionInterruptingCategory category)
3032 {
3033     MediaSessionManager::singleton().didReceiveEndOfInterruptionNotification(category);
3034 }
3035
3036 String Internals::mediaSessionCurrentState(MediaSession* session) const
3037 {
3038     switch (session->currentState()) {
3039     case MediaSession::State::Active:
3040         return "active";
3041     case MediaSession::State::Interrupted:
3042         return "interrupted";
3043     case MediaSession::State::Idle:
3044         return "idle";
3045     }
3046 }
3047
3048 double Internals::mediaElementPlayerVolume(HTMLMediaElement* element) const
3049 {
3050     ASSERT_ARG(element, element);
3051     return element->playerVolume();
3052 }
3053
3054 void Internals::sendMediaControlEvent(MediaControlEvent event)
3055 {
3056     // FIXME: No good reason to use a single function with an argument instead of three functions.
3057     switch (event) {
3058     case MediControlEvent::PlayPause:
3059         MediaSessionManager::singleton().togglePlayback();
3060         break;
3061     case MediControlEvent::NextTrack:
3062         MediaSessionManager::singleton().skipToNextTrack();
3063         break;
3064     case MediControlEvent::PreviousTrack:
3065         MediaSessionManager::singleton().skipToPreviousTrack();
3066         break;
3067     }
3068 }
3069
3070 #endif // ENABLE(MEDIA_SESSION)
3071
3072 #if ENABLE(WEB_AUDIO)
3073
3074 void Internals::setAudioContextRestrictions(AudioContext& context, const String& restrictionsString)
3075 {
3076     AudioContext::BehaviorRestrictions restrictions = context.behaviorRestrictions();
3077     context.removeBehaviorRestriction(restrictions);
3078
3079     restrictions = AudioContext::NoRestrictions;
3080
3081     Vector<String> restrictionsArray;
3082     restrictionsString.split(',', false, restrictionsArray);
3083     for (auto& restrictionString : restrictionsArray) {
3084         if (equalLettersIgnoringASCIICase(restrictionString, "norestrictions"))
3085             restrictions |= AudioContext::NoRestrictions;
3086         if (equalLettersIgnoringASCIICase(restrictionString, "requireusergestureforaudiostart"))
3087             restrictions |= AudioContext::RequireUserGestureForAudioStartRestriction;
3088         if (equalLettersIgnoringASCIICase(restrictionString, "requirepageconsentforaudiostart"))
3089             restrictions |= AudioContext::RequirePageConsentForAudioStartRestriction;
3090     }
3091     context.addBehaviorRestriction(restrictions);
3092 }
3093
3094 #endif
3095
3096 void Internals::simulateSystemSleep() const
3097 {
3098 #if ENABLE(VIDEO)
3099     PlatformMediaSessionManager::sharedManager().systemWillSleep();
3100 #endif
3101 }
3102
3103 void Internals::simulateSystemWake() const
3104 {
3105 #if ENABLE(VIDEO)
3106     PlatformMediaSessionManager::sharedManager().systemDidWake();
3107 #endif
3108 }
3109
3110 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
3111
3112 void Internals::setMockMediaPlaybackTargetPickerEnabled(bool enabled)
3113 {
3114     Page* page = contextDocument()->frame()->page();
3115     ASSERT(page);
3116
3117     page->setMockMediaPlaybackTargetPickerEnabled(enabled);
3118 }
3119
3120 ExceptionOr<void> Internals::setMockMediaPlaybackTargetPickerState(const String& deviceName, const String& deviceState)
3121 {
3122     Page* page = contextDocument()->frame()->page();
3123     ASSERT(page);
3124
3125     MediaPlaybackTargetContext::State state = MediaPlaybackTargetContext::Unknown;
3126
3127     if (equalLettersIgnoringASCIICase(deviceState, "deviceavailable"))
3128         state = MediaPlaybackTargetContext::OutputDeviceAvailable;
3129     else if (equalLettersIgnoringASCIICase(deviceState, "deviceunavailable"))
3130         state = MediaPlaybackTargetContext::OutputDeviceUnavailable;
3131     else if (equalLettersIgnoringASCIICase(deviceState, "unknown"))
3132         state = MediaPlaybackTargetContext::Unknown;
3133     else
3134         return Exception { INVALID_ACCESS_ERR };
3135
3136     page->setMockMediaPlaybackTargetPickerState(deviceName, state);
3137     return { };
3138 }
3139
3140 #endif
3141
3142 ExceptionOr<Ref<MockPageOverlay>> Internals::installMockPageOverlay(PageOverlayType type)
3143 {
3144     Document* document = contextDocument();
3145     if (!document || !document->frame())
3146         return Exception { INVALID_ACCESS_ERR };
3147
3148     return MockPageOverlayClient::singleton().installOverlay(document->frame()->mainFrame(), type == PageOverlayType::View ? PageOverlay::OverlayType::View : PageOverlay::OverlayType::Document);
3149 }
3150
3151 ExceptionOr<String> Internals::pageOverlayLayerTreeAsText() const
3152 {
3153     Document* document = contextDocument();
3154     if (!document || !document->frame())
3155         return Exception { INVALID_ACCESS_ERR };
3156
3157     document->updateLayout();
3158
3159     return MockPageOverlayClient::singleton().layerTreeAsText(document->frame()->mainFrame());
3160 }
3161
3162 void Internals::setPageMuted(const String& states)
3163 {
3164     Document* document = contextDocument();
3165     if (!document)
3166         return;
3167
3168     WebCore::MediaProducer::MutedStateFlags state = MediaProducer::NoneMuted;
3169     Vector<String> stateString;
3170     states.split(',', false, stateString);
3171     for (auto& muteString : stateString) {
3172         if (equalLettersIgnoringASCIICase(muteString, "audio"))
3173             state |= MediaProducer::AudioIsMuted;
3174         if (equalLettersIgnoringASCIICase(muteString, "capturedevices"))
3175             state |= MediaProducer::CaptureDevicesAreMuted;
3176     }
3177
3178     if (Page* page = document->page())
3179         page->setMuted(state);
3180 }
3181
3182 String Internals::pageMediaState()
3183 {
3184     Document* document = contextDocument();
3185     if (!document || !document->page())
3186         return emptyString();
3187
3188     WebCore::MediaProducer::MediaStateFlags state = document->page()->mediaState();
3189     StringBuilder string;
3190     if (state & MediaProducer::IsPlayingAudio)
3191         string.append("IsPlayingAudio,");
3192     if (state & MediaProducer::IsPlayingVideo)
3193         string.append("IsPlayingVideo,");
3194     if (state & MediaProducer::IsPlayingToExternalDevice)
3195         string.append("IsPlayingToExternalDevice,");
3196     if (state & MediaProducer::RequiresPlaybackTargetMonitoring)
3197         string.append("RequiresPlaybackTargetMonitoring,");
3198     if (state & MediaProducer::ExternalDeviceAutoPlayCandidate)
3199         string.append("ExternalDeviceAutoPlayCandidate,");
3200     if (state & MediaProducer::DidPlayToEnd)
3201         string.append("DidPlayToEnd,");
3202     if (state & MediaProducer::IsSourceElementPlaying)
3203         string.append("IsSourceElementPlaying,");
3204
3205     if (state & MediaProducer::IsNextTrackControlEnabled)
3206         string.append("IsNextTrackControlEnabled,");
3207     if (state & MediaProducer::IsPreviousTrackControlEnabled)
3208         string.append("IsPreviousTrackControlEnabled,");
3209
3210     if (state & MediaProducer::HasPlaybackTargetAvailabilityListener)
3211         string.append("HasPlaybackTargetAvailabilityListener,");
3212     if (state & MediaProducer::HasAudioOrVideo)
3213         string.append("HasAudioOrVideo,");
3214     if (state & MediaProducer::HasActiveAudioCaptureDevice)
3215         string.append("HasActiveAudioCaptureDevice,");
3216     if (state & MediaProducer::HasActiveVideoCaptureDevice)
3217         string.append("HasActiveVideoCaptureDevice,");
3218
3219     if (string.isEmpty())
3220         string.append("IsNotPlaying");
3221     else
3222         string.resize(string.length() - 1);
3223
3224     return string.toString();
3225 }
3226
3227 void Internals::setPageDefersLoading(bool defersLoading)
3228 {
3229     Document* document = contextDocument();
3230     if (!document)
3231         return;
3232     if (Page* page = document->page())
3233         page->setDefersLoading(defersLoading);
3234 }
3235
3236 RefPtr<File> Internals::createFile(const String& path)
3237 {
3238     Document* document = contextDocument();
3239     if (!document)
3240         return nullptr;
3241
3242     URL url = document->completeURL(path);
3243     if (!url.isLocalFile())
3244         return nullptr;
3245
3246     return File::create(url.fileSystemPath());
3247 }
3248
3249 void Internals::queueMicroTask(int testNumber)
3250 {
3251     Document* document = contextDocument();
3252     if (!document)
3253         return;
3254
3255     auto microtask = std::make_unique<ActiveDOMCallbackMicrotask>(MicrotaskQueue::mainThreadQueue(), *document, [document, testNumber]() {
3256         document->addConsoleMessage(MessageSource::JS, MessageLevel::Debug, makeString("MicroTask #", String::number(testNumber), " has run."));
3257     });
3258
3259     MicrotaskQueue::mainThreadQueue().append(WTFMove(microtask));
3260 }
3261
3262 #if ENABLE(CONTENT_FILTERING)
3263
3264 MockContentFilterSettings& Internals::mockContentFilterSettings()
3265 {
3266     return MockContentFilterSettings::singleton();
3267 }
3268
3269 #endif
3270
3271 #if ENABLE(CSS_SCROLL_SNAP)
3272
3273 static void appendOffsets(StringBuilder& builder, const Vector<LayoutUnit>& snapOffsets)
3274 {
3275     bool justStarting = true;
3276
3277     builder.appendLiteral("{ ");
3278     for (auto& coordinate : snapOffsets) {
3279         if (!justStarting)
3280             builder.appendLiteral(", ");
3281         else
3282             justStarting = false;
3283         
3284         builder.append(String::number(coordinate.toUnsigned()));
3285     }
3286     builder.appendLiteral(" }");
3287 }
3288     
3289 ExceptionOr<String> Internals::scrollSnapOffsets(Element& element)
3290 {
3291     if (!element.renderBox())
3292         return String();
3293
3294     element.document().updateLayout();
3295
3296     RenderBox& box = *element.renderBox();
3297     ScrollableArea* scrollableArea;
3298     
3299     if (box.isBody()) {
3300         FrameView* frameView = box.frame().mainFrame().view();
3301         if (!frameView || !frameView->isScrollable())
3302             return Exception { INVALID_ACCESS_ERR };
3303         scrollableArea = frameView;
3304         
3305     } else {
3306         if (!box.canBeScrolledAndHasScrollableArea())
3307             return Exception { INVALID_ACCESS_ERR };
3308         scrollableArea = box.layer();
3309     }
3310
3311     if (!scrollableArea)
3312         return String();
3313     
3314     StringBuilder result;
3315
3316     if (scrollableArea->horizontalSnapOffsets()) {
3317         result.appendLiteral("horizontal = ");
3318         appendOffsets(result, *scrollableArea->horizontalSnapOffsets());
3319     }
3320
3321     if (scrollableArea->verticalSnapOffsets()) {
3322         if (result.length())
3323             result.appendLiteral(", ");
3324
3325         result.appendLiteral("vertical = ");
3326         appendOffsets(result, *scrollableArea->verticalSnapOffsets());
3327     }
3328
3329     return result.toString();
3330 }
3331
3332 #endif
3333
3334 bool Internals::testPreloaderSettingViewport()
3335 {
3336     return testPreloadScannerViewportSupport(contextDocument());
3337 }
3338
3339 ExceptionOr<String> Internals::pathStringWithShrinkWrappedRects(const Vector<double>& rectComponents, double radius)
3340 {
3341     if (rectComponents.size() % 4)
3342         return Exception { INVALID_ACCESS_ERR };
3343
3344     Vector<FloatRect> rects;
3345     for (unsigned i = 0; i < rectComponents.size(); i += 4)
3346         rects.append(FloatRect(rectComponents[i], rectComponents[i + 1], rectComponents[i + 2], rectComponents[i + 3]));
3347
3348     SVGPathStringBuilder builder;
3349     PathUtilities::pathWithShrinkWrappedRects(rects, radius).apply([&builder](const PathElement& element) {
3350         switch (element.type) {
3351         case PathElementMoveToPoint:
3352             builder.moveTo(element.points[0], false, AbsoluteCoordinates);
3353             return;
3354         case PathElementAddLineToPoint:
3355             builder.lineTo(element.points[0], AbsoluteCoordinates);
3356             return;
3357         case PathElementAddQuadCurveToPoint:
3358             builder.curveToQuadratic(element.points[0], element.points[1], AbsoluteCoordinates);
3359             return;
3360         case PathElementAddCurveToPoint:
3361             builder.curveToCubic(element.points[0], element.points[1], element.points[2], AbsoluteCoordinates);
3362             return;
3363         case PathElementCloseSubpath:
3364             builder.closePath();
3365             return;
3366         }
3367         ASSERT_NOT_REACHED();
3368     });
3369     return builder.result();
3370 }
3371
3372
3373 String Internals::getCurrentMediaControlsStatusForElement(HTMLMediaElement& mediaElement)
3374 {
3375 #if !ENABLE(MEDIA_CONTROLS_SCRIPT)
3376     UNUSED_PARAM(mediaElement);
3377     return String();
3378 #else
3379     return mediaElement.getCurrentMediaControlsStatus();
3380 #endif
3381 }
3382
3383 #if !PLATFORM(COCOA)
3384
3385 String Internals::userVisibleString(const DOMURL&)
3386 {
3387     // Cocoa-specific function. Could ASSERT_NOT_REACHED, but that's probably overkill.
3388     return String();
3389 }
3390
3391 #endif
3392
3393 void Internals::setShowAllPlugins(bool show)
3394 {
3395     Document* document = contextDocument();
3396     if (!document)
3397         return;
3398     
3399     Page* page = document->page();
3400     if (!page)
3401         return;
3402
3403     page->setShowAllPlugins(show);
3404 }
3405
3406 #if ENABLE(READABLE_STREAM_API)
3407
3408 bool Internals::isReadableStreamDisturbed(JSC::ExecState& state, JSValue stream)
3409 {
3410     JSGlobalObject* globalObject = state.vmEntryGlobalObject();
3411     JSVMClientData* clientData = static_cast<JSVMClientData*>(state.vm().clientData);
3412     const Identifier& privateName = clientData->builtinFunctions().readableStreamInternalsBuiltins().isReadableStreamDisturbedPrivateName();
3413     JSValue value;
3414     PropertySlot propertySlot(value, PropertySlot::InternalMethodType::Get);
3415     globalObject->methodTable()->getOwnPropertySlot(globalObject, &state, privateName, propertySlot);
3416     value = propertySlot.getValue(&state, privateName);
3417     ASSERT(value.isFunction());
3418
3419     JSObject* function = value.getObject();
3420     CallData callData;
3421     CallType callType = JSC::getCallData(function, callData);
3422     ASSERT(callType != JSC::CallType::None);
3423     MarkedArgumentBuffer arguments;
3424     arguments.append(stream);
3425     JSValue returnedValue = JSC::call(&state, function, callType, callData, JSC::jsUndefined(), arguments);
3426     ASSERT(returnedValue.isBoolean());
3427
3428     return returnedValue.asBoolean();
3429 }
3430
3431 #endif
3432
3433 String Internals::resourceLoadStatisticsForOrigin(const String& origin)
3434 {
3435     return ResourceLoadObserver::sharedObserver().statisticsForOrigin(origin);
3436 }
3437
3438 void Internals::setResourceLoadStatisticsEnabled(bool enable)
3439 {
3440     Settings::setResourceLoadStatisticsEnabled(enable);
3441 }
3442
3443 String Internals::composedTreeAsText(Node& node)
3444 {
3445     if (!is<ContainerNode>(node))
3446         return emptyString();
3447     return WebCore::composedTreeAsText(downcast<ContainerNode>(node));
3448 }
3449
3450 void Internals::setLinkPreloadSupport(bool enable)
3451 {
3452     RuntimeEnabledFeatures::sharedFeatures().setLinkPreloadEnabled(enable);
3453 }
3454
3455 #if ENABLE(CSS_GRID_LAYOUT)
3456
3457 void Internals::setCSSGridLayoutEnabled(bool enable)
3458 {
3459     RuntimeEnabledFeatures::sharedFeatures().setCSSGridLayoutEnabled(enable);
3460 }
3461
3462 #endif
3463
3464 #if ENABLE(WEBGL2)
3465
3466 bool Internals::webGL2Enabled() const
3467 {
3468     return RuntimeEnabledFeatures::sharedFeatures().webGL2Enabled();
3469 }
3470
3471 void Internals::setWebGL2Enabled(bool enable)
3472 {
3473     RuntimeEnabledFeatures::sharedFeatures().setWebGL2Enabled(enable);
3474 }
3475
3476 #endif
3477
3478 void Internals::setResourceTimingSupport(bool enable)
3479 {
3480     RuntimeEnabledFeatures::sharedFeatures().setResourceTimingEnabled(enable);
3481 }
3482
3483 bool Internals::isProcessingUserGesture()
3484 {
3485     return UserGestureIndicator::processingUserGesture();
3486 }
3487
3488 RefPtr<GCObservation> Internals::observeGC(JSC::JSValue value)
3489 {
3490     if (!value || value.isNull() || value.isUndefined() || !value.getObject())
3491         return nullptr;
3492
3493     return GCObservation::create(value.getObject());
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