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