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