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