2 * Copyright (C) 2012 Google Inc. All rights reserved.
3 * Copyright (C) 2013-2017 Apple Inc. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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.
28 #include "Internals.h"
30 #include "AXObjectCache.h"
31 #include "ActiveDOMCallbackMicrotask.h"
32 #include "ApplicationCacheStorage.h"
33 #include "AudioSession.h"
35 #include "BackForwardController.h"
36 #include "BitmapImage.h"
37 #include "CSSAnimationController.h"
38 #include "CSSKeyframesRule.h"
39 #include "CSSMediaRule.h"
40 #include "CSSStyleRule.h"
41 #include "CSSSupportsRule.h"
42 #include "CacheStorageConnection.h"
43 #include "CacheStorageProvider.h"
44 #include "CachedImage.h"
45 #include "CachedResourceLoader.h"
47 #include "ComposedTreeIterator.h"
50 #include "DOMRectList.h"
51 #include "DOMStringList.h"
52 #include "DOMWindow.h"
53 #include "DeprecatedGlobalSettings.h"
54 #include "DisplayList.h"
56 #include "DocumentLoader.h"
57 #include "DocumentMarkerController.h"
60 #include "EventHandler.h"
61 #include "ExtendableEvent.h"
62 #include "ExtensionStyleSheets.h"
63 #include "FetchEvent.h"
65 #include "FontCache.h"
66 #include "FormController.h"
67 #include "FrameLoader.h"
68 #include "FrameView.h"
69 #include "GCObservation.h"
70 #include "GridPosition.h"
71 #include "HTMLCanvasElement.h"
72 #include "HTMLIFrameElement.h"
73 #include "HTMLImageElement.h"
74 #include "HTMLInputElement.h"
75 #include "HTMLLinkElement.h"
76 #include "HTMLNames.h"
77 #include "HTMLPlugInElement.h"
78 #include "HTMLPreloadScanner.h"
79 #include "HTMLSelectElement.h"
80 #include "HTMLTextAreaElement.h"
81 #include "HTMLVideoElement.h"
82 #include "HistoryController.h"
83 #include "HistoryItem.h"
84 #include "HitTestResult.h"
85 #include "InspectorClient.h"
86 #include "InspectorController.h"
87 #include "InspectorFrontendClientLocal.h"
88 #include "InspectorOverlay.h"
89 #include "InstrumentingAgents.h"
91 #include "InternalSettings.h"
92 #include "JSFetchResponse.h"
93 #include "JSImageData.h"
94 #include "LibWebRTCProvider.h"
95 #include "MainFrame.h"
96 #include "MallocStatistics.h"
97 #include "MediaPlayer.h"
98 #include "MediaProducer.h"
99 #include "MediaResourceLoader.h"
100 #include "MediaStreamTrack.h"
101 #include "MemoryCache.h"
102 #include "MemoryInfo.h"
103 #include "MockLibWebRTCPeerConnection.h"
104 #include "MockPageOverlay.h"
105 #include "MockPageOverlayClient.h"
107 #include "PageCache.h"
108 #include "PageOverlay.h"
109 #include "PathUtilities.h"
110 #include "PlatformMediaSessionManager.h"
111 #include "PrintContext.h"
112 #include "PseudoElement.h"
114 #include "ReadableStream.h"
115 #include "RenderEmbeddedObject.h"
116 #include "RenderLayerBacking.h"
117 #include "RenderLayerCompositor.h"
118 #include "RenderMenuList.h"
119 #include "RenderTreeAsText.h"
120 #include "RenderView.h"
121 #include "RenderedDocumentMarker.h"
122 #include "ResourceLoadObserver.h"
123 #include "SMILTimeContainer.h"
124 #include "SVGDocumentExtensions.h"
125 #include "SVGPathStringBuilder.h"
126 #include "SVGSVGElement.h"
127 #include "SWClientConnection.h"
128 #include "SchemeRegistry.h"
129 #include "ScriptedAnimationController.h"
130 #include "ScrollingCoordinator.h"
131 #include "ScrollingMomentumCalculator.h"
132 #include "SecurityOrigin.h"
133 #include "SerializedScriptValue.h"
134 #include "ServiceWorkerProvider.h"
135 #include "ServiceWorkerRegistrationData.h"
136 #include "Settings.h"
137 #include "ShadowRoot.h"
138 #include "SourceBuffer.h"
139 #include "SpellChecker.h"
140 #include "StaticNodeList.h"
141 #include "StringCallback.h"
142 #include "StyleRule.h"
143 #include "StyleScope.h"
144 #include "StyleSheetContents.h"
145 #include "TextIterator.h"
146 #include "TreeScope.h"
147 #include "TypeConversions.h"
148 #include "UserGestureIndicator.h"
149 #include "UserMediaController.h"
150 #include "ViewportArguments.h"
151 #include "WebCoreJSClientData.h"
153 #include "WebGLRenderingContext.h"
155 #include "WorkerThread.h"
156 #include "WritingDirection.h"
157 #include "XMLHttpRequest.h"
158 #include <bytecode/CodeBlock.h>
159 #include <inspector/InspectorAgentBase.h>
160 #include <inspector/InspectorFrontendChannel.h>
161 #include <inspector/InspectorValues.h>
162 #include <runtime/JSCInlines.h>
163 #include <runtime/JSCJSValue.h>
164 #include <wtf/Language.h>
165 #include <wtf/MemoryPressureHandler.h>
166 #include <wtf/MonotonicTime.h>
167 #include <wtf/text/StringBuffer.h>
168 #include <wtf/text/StringBuilder.h>
169 #include <wtf/text/StringView.h>
171 #if ENABLE(INPUT_TYPE_COLOR)
172 #include "ColorChooser.h"
175 #if ENABLE(MOUSE_CURSOR_SCALE)
176 #include <wtf/dtoa.h>
179 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
180 #include "LegacyCDM.h"
181 #include "LegacyMockCDM.h"
184 #if ENABLE(ENCRYPTED_MEDIA)
185 #include "MockCDMFactory.h"
188 #if ENABLE(VIDEO_TRACK)
189 #include "CaptionUserPreferences.h"
190 #include "PageGroup.h"
194 #include "HTMLMediaElement.h"
195 #include "TimeRanges.h"
198 #if ENABLE(SPEECH_SYNTHESIS)
199 #include "DOMWindowSpeechSynthesis.h"
200 #include "PlatformSpeechSynthesizerMock.h"
201 #include "SpeechSynthesis.h"
204 #if ENABLE(MEDIA_STREAM)
205 #include "MediaStream.h"
206 #include "MockRealtimeMediaSourceCenter.h"
210 #include "RTCPeerConnection.h"
213 #if ENABLE(MEDIA_SOURCE)
214 #include "MockMediaPlayerMediaSource.h"
217 #if USE(LIBWEBRTC) && PLATFORM(COCOA)
218 #include "H264VideoToolboxEncoder.h"
222 #include "DictionaryLookup.h"
225 #if ENABLE(CONTENT_FILTERING)
226 #include "MockContentFilterSettings.h"
229 #if ENABLE(WEB_AUDIO)
230 #include "AudioContext.h"
233 #if ENABLE(MEDIA_SESSION)
234 #include "MediaSession.h"
235 #include "MediaSessionManager.h"
238 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
239 #include "MediaPlaybackTargetContext.h"
242 #if ENABLE(POINTER_LOCK)
243 #include "PointerLockController.h"
247 #include "MockPreviewLoaderClient.h"
248 #include "PreviewLoader.h"
251 #if ENABLE(APPLE_PAY)
252 #include "MockPaymentCoordinator.h"
253 #include "PaymentCoordinator.h"
258 using JSC::CodeBlock;
259 using JSC::FunctionExecutable;
260 using JSC::Identifier;
261 using JSC::JSFunction;
262 using JSC::JSGlobalObject;
265 using JSC::MarkedArgumentBuffer;
266 using JSC::PropertySlot;
267 using JSC::ScriptExecutable;
268 using JSC::StackVisitor;
272 using namespace Inspector;
274 using namespace HTMLNames;
276 class InspectorStubFrontend final : public InspectorFrontendClientLocal, public FrontendChannel {
278 InspectorStubFrontend(Page& inspectedPage, RefPtr<DOMWindow>&& frontendWindow);
279 virtual ~InspectorStubFrontend();
282 void attachWindow(DockSide) final { }
283 void detachWindow() final { }
284 void closeWindow() final;
285 void bringToFront() final { }
286 String localizedStringsURL() final { return String(); }
287 void inspectedURLChanged(const String&) final { }
288 void setAttachedWindowHeight(unsigned) final { }
289 void setAttachedWindowWidth(unsigned) final { }
291 void sendMessageToFrontend(const String& message) final;
292 ConnectionType connectionType() const final { return ConnectionType::Local; }
294 Page* frontendPage() const
296 if (!m_frontendWindow || !m_frontendWindow->document())
299 return m_frontendWindow->document()->page();
302 RefPtr<DOMWindow> m_frontendWindow;
303 InspectorController& m_frontendController;
306 InspectorStubFrontend::InspectorStubFrontend(Page& inspectedPage, RefPtr<DOMWindow>&& frontendWindow)
307 : InspectorFrontendClientLocal(&inspectedPage.inspectorController(), frontendWindow->document()->page(), std::make_unique<InspectorFrontendClientLocal::Settings>())
308 , m_frontendWindow(frontendWindow.copyRef())
309 , m_frontendController(frontendPage()->inspectorController())
311 ASSERT_ARG(frontendWindow, frontendWindow);
313 m_frontendController.setInspectorFrontendClient(this);
314 inspectedPage.inspectorController().connectFrontend(this);
317 InspectorStubFrontend::~InspectorStubFrontend()
322 void InspectorStubFrontend::closeWindow()
324 if (!m_frontendWindow)
327 m_frontendController.setInspectorFrontendClient(nullptr);
328 inspectedPage()->inspectorController().disconnectFrontend(this);
330 m_frontendWindow->close();
331 m_frontendWindow = nullptr;
334 void InspectorStubFrontend::sendMessageToFrontend(const String& message)
336 ASSERT_ARG(message, !message.isEmpty());
338 InspectorClient::doDispatchMessageOnFrontendPage(frontendPage(), message);
341 static bool markerTypeFrom(const String& markerType, DocumentMarker::MarkerType& result)
343 if (equalLettersIgnoringASCIICase(markerType, "spelling"))
344 result = DocumentMarker::Spelling;
345 else if (equalLettersIgnoringASCIICase(markerType, "grammar"))
346 result = DocumentMarker::Grammar;
347 else if (equalLettersIgnoringASCIICase(markerType, "textmatch"))
348 result = DocumentMarker::TextMatch;
349 else if (equalLettersIgnoringASCIICase(markerType, "replacement"))
350 result = DocumentMarker::Replacement;
351 else if (equalLettersIgnoringASCIICase(markerType, "correctionindicator"))
352 result = DocumentMarker::CorrectionIndicator;
353 else if (equalLettersIgnoringASCIICase(markerType, "rejectedcorrection"))
354 result = DocumentMarker::RejectedCorrection;
355 else if (equalLettersIgnoringASCIICase(markerType, "autocorrected"))
356 result = DocumentMarker::Autocorrected;
357 else if (equalLettersIgnoringASCIICase(markerType, "spellcheckingexemption"))
358 result = DocumentMarker::SpellCheckingExemption;
359 else if (equalLettersIgnoringASCIICase(markerType, "deletedautocorrection"))
360 result = DocumentMarker::DeletedAutocorrection;
361 else if (equalLettersIgnoringASCIICase(markerType, "dictationalternatives"))
362 result = DocumentMarker::DictationAlternatives;
363 #if ENABLE(TELEPHONE_NUMBER_DETECTION)
364 else if (equalLettersIgnoringASCIICase(markerType, "telephonenumber"))
365 result = DocumentMarker::TelephoneNumber;
373 static bool markerTypesFrom(const String& markerType, OptionSet<DocumentMarker::MarkerType>& result)
375 DocumentMarker::MarkerType singularResult;
377 if (markerType.isEmpty() || equalLettersIgnoringASCIICase(markerType, "all"))
378 result = DocumentMarker::allMarkers();
379 else if (markerTypeFrom(markerType, singularResult))
380 result = singularResult;
387 static std::unique_ptr<PrintContext>& printContextForTesting()
389 static NeverDestroyed<std::unique_ptr<PrintContext>> context;
393 const char* Internals::internalsId = "internals";
395 Ref<Internals> Internals::create(Document& document)
397 return adoptRef(*new Internals(document));
400 Internals::~Internals()
402 #if ENABLE(MEDIA_STREAM)
404 m_track->source().removeObserver(*this);
408 void Internals::resetToConsistentState(Page& page)
410 page.setPageScaleFactor(1, IntPoint(0, 0));
411 page.setPagination(Pagination());
412 page.setPaginationLineGridEnabled(false);
414 page.setDefersLoading(false);
416 page.mainFrame().setTextZoomFactor(1.0f);
418 FrameView* mainFrameView = page.mainFrame().view();
420 mainFrameView->setHeaderHeight(0);
421 mainFrameView->setFooterHeight(0);
422 page.setTopContentInset(0);
423 mainFrameView->setUseFixedLayout(false);
424 mainFrameView->setFixedLayoutSize(IntSize());
425 #if USE(COORDINATED_GRAPHICS)
426 mainFrameView->setFixedVisibleContentRect(IntRect());
427 page.chrome().client().resetUpdateAtlasForTesting();
429 if (auto* backing = mainFrameView->tiledBacking())
430 backing->setTileSizeUpdateDelayDisabledForTesting(false);
433 WebCore::clearDefaultPortForProtocolMapForTesting();
434 overrideUserPreferredLanguages(Vector<String>());
435 WebCore::DeprecatedGlobalSettings::setUsesOverlayScrollbars(false);
436 WebCore::DeprecatedGlobalSettings::setUsesMockScrollAnimator(false);
437 #if ENABLE(VIDEO_TRACK)
438 page.group().captionPreferences().setTestingMode(true);
439 page.group().captionPreferences().setCaptionsStyleSheetOverride(emptyString());
440 page.group().captionPreferences().setTestingMode(false);
442 if (!page.mainFrame().editor().isContinuousSpellCheckingEnabled())
443 page.mainFrame().editor().toggleContinuousSpellChecking();
444 if (page.mainFrame().editor().isOverwriteModeEnabled())
445 page.mainFrame().editor().toggleOverwriteModeEnabled();
446 page.mainFrame().loader().clearTestingOverrides();
447 page.applicationCacheStorage().setDefaultOriginQuota(ApplicationCacheStorage::noQuota());
449 PlatformMediaSessionManager::sharedManager().resetRestrictions();
450 PlatformMediaSessionManager::sharedManager().setWillIgnoreSystemInterruptions(true);
452 #if HAVE(ACCESSIBILITY)
453 AXObjectCache::setEnhancedUserInterfaceAccessibility(false);
454 AXObjectCache::disableAccessibility();
457 MockPageOverlayClient::singleton().uninstallAllOverlays();
459 #if ENABLE(CONTENT_FILTERING)
460 MockContentFilterSettings::reset();
463 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
464 page.setMockMediaPlaybackTargetPickerEnabled(true);
465 page.setMockMediaPlaybackTargetPickerState(emptyString(), MediaPlaybackTargetContext::Unknown);
468 page.setShowAllPlugins(false);
469 page.setLowPowerModeEnabledOverrideForTesting(std::nullopt);
472 MockPreviewLoaderClient::singleton().setPassword("");
473 PreviewLoader::setClientForTesting(nullptr);
476 printContextForTesting() = nullptr;
479 WebCore::useRealRTCPeerConnectionFactory(page.libWebRTCProvider());
482 page.settings().setStorageAccessAPIEnabled(false);
485 Internals::Internals(Document& document)
486 : ContextDestructionObserver(&document)
487 #if ENABLE(MEDIA_STREAM)
488 , m_orientationNotifier(0)
491 #if ENABLE(VIDEO_TRACK)
493 document.page()->group().captionPreferences().setTestingMode(true);
496 #if ENABLE(MEDIA_STREAM)
497 setMockMediaCaptureDevicesEnabled(true);
498 WebCore::DeprecatedGlobalSettings::setMediaCaptureRequiresSecureConnection(false);
501 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
503 document.page()->setMockMediaPlaybackTargetPickerEnabled(true);
506 if (contextDocument() && contextDocument()->frame()) {
507 setAutomaticSpellingCorrectionEnabled(true);
508 setAutomaticQuoteSubstitutionEnabled(false);
509 setAutomaticDashSubstitutionEnabled(false);
510 setAutomaticLinkDetectionEnabled(false);
511 setAutomaticTextReplacementEnabled(true);
514 setConsoleMessageListener(nullptr);
516 #if ENABLE(APPLE_PAY)
517 auto* frame = document.frame();
518 if (frame && frame->isMainFrame()) {
519 m_mockPaymentCoordinator = new MockPaymentCoordinator(frame->mainFrame());
520 frame->mainFrame().setPaymentCoordinator(std::make_unique<PaymentCoordinator>(*m_mockPaymentCoordinator));
525 Document* Internals::contextDocument() const
527 return downcast<Document>(scriptExecutionContext());
530 Frame* Internals::frame() const
532 if (!contextDocument())
534 return contextDocument()->frame();
537 InternalSettings* Internals::settings() const
539 Document* document = contextDocument();
542 Page* page = document->page();
545 return InternalSettings::from(page);
548 unsigned Internals::workerThreadCount() const
550 return WorkerThread::workerThreadCount();
553 ExceptionOr<bool> Internals::areSVGAnimationsPaused() const
555 auto* document = contextDocument();
557 return Exception { InvalidAccessError, ASCIILiteral("No context document") };
559 if (!document->svgExtensions())
560 return Exception { NotFoundError, ASCIILiteral("No SVG animations") };
562 return document->accessSVGExtensions().areAnimationsPaused();
565 ExceptionOr<double> Internals::svgAnimationsInterval(SVGSVGElement& element) const
567 auto* document = contextDocument();
571 if (!document->svgExtensions())
574 if (document->accessSVGExtensions().areAnimationsPaused())
577 return element.timeContainer().animationFrameDelay().value();
580 String Internals::address(Node& node)
582 return String::format("%p", &node);
585 bool Internals::nodeNeedsStyleRecalc(Node& node)
587 return node.needsStyleRecalc();
590 static String styleValidityToToString(Style::Validity validity)
593 case Style::Validity::Valid:
594 return "NoStyleChange";
595 case Style::Validity::ElementInvalid:
596 return "InlineStyleChange";
597 case Style::Validity::SubtreeInvalid:
598 return "FullStyleChange";
599 case Style::Validity::SubtreeAndRenderersInvalid:
600 return "ReconstructRenderTree";
602 ASSERT_NOT_REACHED();
606 String Internals::styleChangeType(Node& node)
608 node.document().styleScope().flushPendingUpdate();
610 return styleValidityToToString(node.styleValidity());
613 String Internals::description(JSC::JSValue value)
615 return toString(value);
618 bool Internals::isPreloaded(const String& url)
620 Document* document = contextDocument();
621 return document->cachedResourceLoader().isPreloaded(url);
624 bool Internals::isLoadingFromMemoryCache(const String& url)
626 if (!contextDocument() || !contextDocument()->page())
629 ResourceRequest request(contextDocument()->completeURL(url));
630 request.setDomainForCachePartition(contextDocument()->topOrigin().domainForCachePartition());
632 CachedResource* resource = MemoryCache::singleton().resourceForRequest(request, contextDocument()->page()->sessionID());
633 return resource && resource->status() == CachedResource::Cached;
636 static String responseSourceToString(const ResourceResponse& response)
638 if (response.isNull())
639 return "Null response";
640 switch (response.source()) {
641 case ResourceResponse::Source::Unknown:
643 case ResourceResponse::Source::Network:
645 case ResourceResponse::Source::ServiceWorker:
646 return "Service worker";
647 case ResourceResponse::Source::DiskCache:
649 case ResourceResponse::Source::DiskCacheAfterValidation:
650 return "Disk cache after validation";
651 case ResourceResponse::Source::MemoryCache:
652 return "Memory cache";
653 case ResourceResponse::Source::MemoryCacheAfterValidation:
654 return "Memory cache after validation";
656 ASSERT_NOT_REACHED();
660 String Internals::xhrResponseSource(XMLHttpRequest& request)
662 return responseSourceToString(request.resourceResponse());
665 String Internals::fetchResponseSource(FetchResponse& response)
667 return responseSourceToString(response.resourceResponse());
670 bool Internals::isSharingStyleSheetContents(HTMLLinkElement& a, HTMLLinkElement& b)
672 if (!a.sheet() || !b.sheet())
674 return &a.sheet()->contents() == &b.sheet()->contents();
677 bool Internals::isStyleSheetLoadingSubresources(HTMLLinkElement& link)
679 return link.sheet() && link.sheet()->contents().isLoadingSubresources();
682 static ResourceRequestCachePolicy toResourceRequestCachePolicy(Internals::CachePolicy policy)
685 case Internals::CachePolicy::UseProtocolCachePolicy:
686 return UseProtocolCachePolicy;
687 case Internals::CachePolicy::ReloadIgnoringCacheData:
688 return ReloadIgnoringCacheData;
689 case Internals::CachePolicy::ReturnCacheDataElseLoad:
690 return ReturnCacheDataElseLoad;
691 case Internals::CachePolicy::ReturnCacheDataDontLoad:
692 return ReturnCacheDataDontLoad;
694 ASSERT_NOT_REACHED();
695 return UseProtocolCachePolicy;
698 void Internals::setOverrideCachePolicy(CachePolicy policy)
700 frame()->loader().setOverrideCachePolicyForTesting(toResourceRequestCachePolicy(policy));
703 ExceptionOr<void> Internals::setCanShowModalDialogOverride(bool allow)
705 if (!contextDocument() || !contextDocument()->domWindow())
706 return Exception { InvalidAccessError };
708 contextDocument()->domWindow()->setCanShowModalDialogOverride(allow);
712 static ResourceLoadPriority toResourceLoadPriority(Internals::ResourceLoadPriority priority)
715 case Internals::ResourceLoadPriority::ResourceLoadPriorityVeryLow:
716 return ResourceLoadPriority::VeryLow;
717 case Internals::ResourceLoadPriority::ResourceLoadPriorityLow:
718 return ResourceLoadPriority::Low;
719 case Internals::ResourceLoadPriority::ResourceLoadPriorityMedium:
720 return ResourceLoadPriority::Medium;
721 case Internals::ResourceLoadPriority::ResourceLoadPriorityHigh:
722 return ResourceLoadPriority::High;
723 case Internals::ResourceLoadPriority::ResourceLoadPriorityVeryHigh:
724 return ResourceLoadPriority::VeryHigh;
726 ASSERT_NOT_REACHED();
727 return ResourceLoadPriority::Low;
730 void Internals::setOverrideResourceLoadPriority(ResourceLoadPriority priority)
732 frame()->loader().setOverrideResourceLoadPriorityForTesting(toResourceLoadPriority(priority));
735 void Internals::setStrictRawResourceValidationPolicyDisabled(bool disabled)
737 frame()->loader().setStrictRawResourceValidationPolicyDisabledForTesting(disabled);
740 void Internals::clearMemoryCache()
742 MemoryCache::singleton().evictResources();
745 void Internals::pruneMemoryCacheToSize(unsigned size)
747 MemoryCache::singleton().pruneDeadResourcesToSize(size);
748 MemoryCache::singleton().pruneLiveResourcesToSize(size, true);
751 void Internals::destroyDecodedDataForAllImages()
753 MemoryCache::singleton().destroyDecodedDataForAllImages();
756 unsigned Internals::memoryCacheSize() const
758 return MemoryCache::singleton().size();
761 static Image* imageFromImageElement(HTMLImageElement& element)
763 auto* cachedImage = element.cachedImage();
764 return cachedImage ? cachedImage->image() : nullptr;
767 static BitmapImage* bitmapImageFromImageElement(HTMLImageElement& element)
769 auto* image = imageFromImageElement(element);
770 return image && is<BitmapImage>(image) ? &downcast<BitmapImage>(*image) : nullptr;
773 unsigned Internals::imageFrameIndex(HTMLImageElement& element)
775 auto* bitmapImage = bitmapImageFromImageElement(element);
776 return bitmapImage ? bitmapImage->currentFrame() : 0;
779 void Internals::setImageFrameDecodingDuration(HTMLImageElement& element, float duration)
781 if (auto* bitmapImage = bitmapImageFromImageElement(element))
782 bitmapImage->setFrameDecodingDurationForTesting(Seconds { duration });
785 void Internals::resetImageAnimation(HTMLImageElement& element)
787 if (auto* image = imageFromImageElement(element))
788 image->resetAnimation();
791 bool Internals::isImageAnimating(HTMLImageElement& element)
793 auto* image = imageFromImageElement(element);
794 return image && (image->isAnimating() || image->animationPending());
797 void Internals::setClearDecoderAfterAsyncFrameRequestForTesting(HTMLImageElement& element, bool enabled)
799 if (auto* bitmapImage = bitmapImageFromImageElement(element))
800 bitmapImage->setClearDecoderAfterAsyncFrameRequestForTesting(enabled);
803 unsigned Internals::imageDecodeCount(HTMLImageElement& element)
805 auto* bitmapImage = bitmapImageFromImageElement(element);
806 return bitmapImage ? bitmapImage->decodeCountForTesting() : 0;
809 void Internals::setLargeImageAsyncDecodingEnabledForTesting(HTMLImageElement& element, bool enabled)
811 if (auto* bitmapImage = bitmapImageFromImageElement(element))
812 bitmapImage->setLargeImageAsyncDecodingEnabledForTesting(enabled);
815 void Internals::setGridMaxTracksLimit(unsigned maxTrackLimit)
817 GridPosition::setMaxPositionForTesting(maxTrackLimit);
820 void Internals::clearPageCache()
822 PageCache::singleton().pruneToSizeNow(0, PruningReason::None);
825 unsigned Internals::pageCacheSize() const
827 return PageCache::singleton().pageCount();
830 void Internals::disableTileSizeUpdateDelay()
832 Document* document = contextDocument();
833 if (!document || !document->frame())
836 auto* view = document->frame()->view();
840 if (auto* backing = view->tiledBacking())
841 backing->setTileSizeUpdateDelayDisabledForTesting(true);
844 void Internals::setSpeculativeTilingDelayDisabledForTesting(bool disabled)
846 Document* document = contextDocument();
847 if (!document || !document->frame())
850 if (auto* frameView = document->frame()->view())
851 frameView->setSpeculativeTilingDelayDisabledForTesting(disabled);
855 Node* Internals::treeScopeRootNode(Node& node)
857 return &node.treeScope().rootNode();
860 Node* Internals::parentTreeScope(Node& node)
862 const TreeScope* parentTreeScope = node.treeScope().parentTreeScope();
863 return parentTreeScope ? &parentTreeScope->rootNode() : nullptr;
866 ExceptionOr<unsigned> Internals::lastSpatialNavigationCandidateCount() const
868 if (!contextDocument() || !contextDocument()->page())
869 return Exception { InvalidAccessError };
871 return contextDocument()->page()->lastSpatialNavigationCandidateCount();
874 unsigned Internals::numberOfActiveAnimations() const
876 return frame()->animation().numberOfActiveAnimations(frame()->document());
879 ExceptionOr<bool> Internals::animationsAreSuspended() const
881 Document* document = contextDocument();
882 if (!document || !document->frame())
883 return Exception { InvalidAccessError };
885 return document->frame()->animation().animationsAreSuspendedForDocument(document);
888 double Internals::animationsInterval() const
890 Document* document = contextDocument();
891 if (!document || !document->frame())
894 return document->frame()->animation().animationInterval().value();
897 ExceptionOr<void> Internals::suspendAnimations() const
899 Document* document = contextDocument();
900 if (!document || !document->frame())
901 return Exception { InvalidAccessError };
903 document->frame()->animation().suspendAnimationsForDocument(document);
905 for (Frame* frame = document->frame(); frame; frame = frame->tree().traverseNext()) {
906 if (Document* document = frame->document())
907 frame->animation().suspendAnimationsForDocument(document);
913 ExceptionOr<void> Internals::resumeAnimations() const
915 Document* document = contextDocument();
916 if (!document || !document->frame())
917 return Exception { InvalidAccessError };
919 document->frame()->animation().resumeAnimationsForDocument(document);
921 for (Frame* frame = document->frame(); frame; frame = frame->tree().traverseNext()) {
922 if (Document* document = frame->document())
923 frame->animation().resumeAnimationsForDocument(document);
929 ExceptionOr<bool> Internals::pauseAnimationAtTimeOnElement(const String& animationName, double pauseTime, Element& element)
932 return Exception { InvalidAccessError };
933 return frame()->animation().pauseAnimationAtTime(element, AtomicString(animationName), pauseTime);
936 ExceptionOr<bool> Internals::pauseAnimationAtTimeOnPseudoElement(const String& animationName, double pauseTime, Element& element, const String& pseudoId)
939 return Exception { InvalidAccessError };
941 if (pseudoId != "before" && pseudoId != "after")
942 return Exception { InvalidAccessError };
944 PseudoElement* pseudoElement = pseudoId == "before" ? element.beforePseudoElement() : element.afterPseudoElement();
946 return Exception { InvalidAccessError };
948 return frame()->animation().pauseAnimationAtTime(*pseudoElement, AtomicString(animationName), pauseTime);
951 ExceptionOr<bool> Internals::pauseTransitionAtTimeOnElement(const String& propertyName, double pauseTime, Element& element)
954 return Exception { InvalidAccessError };
955 return frame()->animation().pauseTransitionAtTime(element, propertyName, pauseTime);
958 ExceptionOr<bool> Internals::pauseTransitionAtTimeOnPseudoElement(const String& property, double pauseTime, Element& element, const String& pseudoId)
961 return Exception { InvalidAccessError };
963 if (pseudoId != "before" && pseudoId != "after")
964 return Exception { InvalidAccessError };
966 PseudoElement* pseudoElement = pseudoId == "before" ? element.beforePseudoElement() : element.afterPseudoElement();
968 return Exception { InvalidAccessError };
970 return frame()->animation().pauseTransitionAtTime(*pseudoElement, property, pauseTime);
973 ExceptionOr<String> Internals::elementRenderTreeAsText(Element& element)
975 element.document().updateStyleIfNeeded();
977 String representation = externalRepresentation(&element);
978 if (representation.isEmpty())
979 return Exception { InvalidAccessError };
981 return WTFMove(representation);
984 bool Internals::hasPausedImageAnimations(Element& element)
986 return element.renderer() && element.renderer()->hasPausedImageAnimations();
989 bool Internals::isPaintingFrequently(Element& element)
991 return element.renderer() && element.renderer()->enclosingLayer() && element.renderer()->enclosingLayer()->paintingFrequently();
994 void Internals::incrementFrequentPaintCounter(Element& element)
996 if (element.renderer() && element.renderer()->enclosingLayer())
997 element.renderer()->enclosingLayer()->simulateFrequentPaint();
1000 Ref<CSSComputedStyleDeclaration> Internals::computedStyleIncludingVisitedInfo(Element& element) const
1002 bool allowVisitedStyle = true;
1003 return CSSComputedStyleDeclaration::create(element, allowVisitedStyle);
1006 Node* Internals::ensureUserAgentShadowRoot(Element& host)
1008 return &host.ensureUserAgentShadowRoot();
1011 Node* Internals::shadowRoot(Element& host)
1013 return host.shadowRoot();
1016 ExceptionOr<String> Internals::shadowRootType(const Node& root) const
1018 if (!is<ShadowRoot>(root))
1019 return Exception { InvalidAccessError };
1021 switch (downcast<ShadowRoot>(root).mode()) {
1022 case ShadowRootMode::UserAgent:
1023 return String("UserAgentShadowRoot");
1024 case ShadowRootMode::Closed:
1025 return String("ClosedShadowRoot");
1026 case ShadowRootMode::Open:
1027 return String("OpenShadowRoot");
1029 ASSERT_NOT_REACHED();
1030 return String("Unknown");
1034 String Internals::shadowPseudoId(Element& element)
1036 return element.shadowPseudoId().string();
1039 void Internals::setShadowPseudoId(Element& element, const String& id)
1041 return element.setPseudo(id);
1044 static unsigned deferredStyleRulesCountForList(const Vector<RefPtr<StyleRuleBase>>& childRules)
1047 for (auto rule : childRules) {
1048 if (is<StyleRule>(rule)) {
1049 auto* cssRule = downcast<StyleRule>(rule.get());
1050 if (!cssRule->propertiesWithoutDeferredParsing())
1055 StyleRuleGroup* groupRule = nullptr;
1056 if (is<StyleRuleMedia>(rule))
1057 groupRule = downcast<StyleRuleMedia>(rule.get());
1058 else if (is<StyleRuleSupports>(rule))
1059 groupRule = downcast<StyleRuleSupports>(rule.get());
1063 auto* groupChildRules = groupRule->childRulesWithoutDeferredParsing();
1064 if (!groupChildRules)
1067 count += deferredStyleRulesCountForList(*groupChildRules);
1073 unsigned Internals::deferredStyleRulesCount(StyleSheet& styleSheet)
1075 return deferredStyleRulesCountForList(downcast<CSSStyleSheet>(styleSheet).contents().childRules());
1078 static unsigned deferredGroupRulesCountForList(const Vector<RefPtr<StyleRuleBase>>& childRules)
1081 for (auto rule : childRules) {
1082 StyleRuleGroup* groupRule = nullptr;
1083 if (is<StyleRuleMedia>(rule))
1084 groupRule = downcast<StyleRuleMedia>(rule.get());
1085 else if (is<StyleRuleSupports>(rule))
1086 groupRule = downcast<StyleRuleSupports>(rule.get());
1090 auto* groupChildRules = groupRule->childRulesWithoutDeferredParsing();
1091 if (!groupChildRules)
1094 count += deferredGroupRulesCountForList(*groupChildRules);
1099 unsigned Internals::deferredGroupRulesCount(StyleSheet& styleSheet)
1101 return deferredGroupRulesCountForList(downcast<CSSStyleSheet>(styleSheet).contents().childRules());
1104 static unsigned deferredKeyframesRulesCountForList(const Vector<RefPtr<StyleRuleBase>>& childRules)
1107 for (auto rule : childRules) {
1108 if (is<StyleRuleKeyframes>(rule)) {
1109 auto* cssRule = downcast<StyleRuleKeyframes>(rule.get());
1110 if (!cssRule->keyframesWithoutDeferredParsing())
1115 StyleRuleGroup* groupRule = nullptr;
1116 if (is<StyleRuleMedia>(rule))
1117 groupRule = downcast<StyleRuleMedia>(rule.get());
1118 else if (is<StyleRuleSupports>(rule))
1119 groupRule = downcast<StyleRuleSupports>(rule.get());
1123 auto* groupChildRules = groupRule->childRulesWithoutDeferredParsing();
1124 if (!groupChildRules)
1127 count += deferredKeyframesRulesCountForList(*groupChildRules);
1133 unsigned Internals::deferredKeyframesRulesCount(StyleSheet& styleSheet)
1135 StyleSheetContents& contents = downcast<CSSStyleSheet>(styleSheet).contents();
1136 return deferredKeyframesRulesCountForList(contents.childRules());
1139 ExceptionOr<bool> Internals::isTimerThrottled(int timeoutId)
1141 auto* timer = scriptExecutionContext()->findTimeout(timeoutId);
1143 return Exception { NotFoundError };
1145 if (timer->intervalClampedToMinimum() > timer->m_originalInterval)
1148 return !!timer->alignedFireTime(MonotonicTime { });
1151 bool Internals::isRequestAnimationFrameThrottled() const
1153 auto* scriptedAnimationController = contextDocument()->scriptedAnimationController();
1154 if (!scriptedAnimationController)
1156 return scriptedAnimationController->isThrottled();
1159 double Internals::requestAnimationFrameInterval() const
1161 auto* scriptedAnimationController = contextDocument()->scriptedAnimationController();
1162 if (!scriptedAnimationController)
1164 return scriptedAnimationController->interval().value();
1167 bool Internals::scriptedAnimationsAreSuspended() const
1169 Document* document = contextDocument();
1170 if (!document || !document->page())
1173 return document->page()->scriptedAnimationsSuspended();
1176 bool Internals::areTimersThrottled() const
1178 return contextDocument()->isTimerThrottlingEnabled();
1181 void Internals::setEventThrottlingBehaviorOverride(std::optional<EventThrottlingBehavior> value)
1183 Document* document = contextDocument();
1184 if (!document || !document->page())
1188 document->page()->setEventThrottlingBehaviorOverride(std::nullopt);
1192 switch (value.value()) {
1193 case Internals::EventThrottlingBehavior::Responsive:
1194 document->page()->setEventThrottlingBehaviorOverride(WebCore::EventThrottlingBehavior::Responsive);
1196 case Internals::EventThrottlingBehavior::Unresponsive:
1197 document->page()->setEventThrottlingBehaviorOverride(WebCore::EventThrottlingBehavior::Unresponsive);
1202 std::optional<Internals::EventThrottlingBehavior> Internals::eventThrottlingBehaviorOverride() const
1204 Document* document = contextDocument();
1205 if (!document || !document->page())
1206 return std::nullopt;
1208 auto behavior = document->page()->eventThrottlingBehaviorOverride();
1210 return std::nullopt;
1212 switch (behavior.value()) {
1213 case WebCore::EventThrottlingBehavior::Responsive:
1214 return Internals::EventThrottlingBehavior::Responsive;
1215 case WebCore::EventThrottlingBehavior::Unresponsive:
1216 return Internals::EventThrottlingBehavior::Unresponsive;
1219 return std::nullopt;
1222 String Internals::visiblePlaceholder(Element& element)
1224 if (is<HTMLTextFormControlElement>(element)) {
1225 const HTMLTextFormControlElement& textFormControlElement = downcast<HTMLTextFormControlElement>(element);
1226 if (!textFormControlElement.isPlaceholderVisible())
1228 if (HTMLElement* placeholderElement = textFormControlElement.placeholderElement())
1229 return placeholderElement->textContent();
1235 void Internals::selectColorInColorChooser(HTMLInputElement& element, const String& colorValue)
1237 element.selectColor(Color(colorValue));
1240 ExceptionOr<Vector<String>> Internals::formControlStateOfPreviousHistoryItem()
1242 HistoryItem* mainItem = frame()->loader().history().previousItem();
1244 return Exception { InvalidAccessError };
1245 String uniqueName = frame()->tree().uniqueName();
1246 if (mainItem->target() != uniqueName && !mainItem->childItemWithTarget(uniqueName))
1247 return Exception { InvalidAccessError };
1248 return Vector<String> { mainItem->target() == uniqueName ? mainItem->documentState() : mainItem->childItemWithTarget(uniqueName)->documentState() };
1251 ExceptionOr<void> Internals::setFormControlStateOfPreviousHistoryItem(const Vector<String>& state)
1253 HistoryItem* mainItem = frame()->loader().history().previousItem();
1255 return Exception { InvalidAccessError };
1256 String uniqueName = frame()->tree().uniqueName();
1257 if (mainItem->target() == uniqueName)
1258 mainItem->setDocumentState(state);
1259 else if (HistoryItem* subItem = mainItem->childItemWithTarget(uniqueName))
1260 subItem->setDocumentState(state);
1262 return Exception { InvalidAccessError };
1266 #if ENABLE(SPEECH_SYNTHESIS)
1268 void Internals::enableMockSpeechSynthesizer()
1270 Document* document = contextDocument();
1271 if (!document || !document->domWindow())
1273 SpeechSynthesis* synthesis = DOMWindowSpeechSynthesis::speechSynthesis(*document->domWindow());
1277 synthesis->setPlatformSynthesizer(std::make_unique<PlatformSpeechSynthesizerMock>(synthesis));
1284 void Internals::emulateRTCPeerConnectionPlatformEvent(RTCPeerConnection& connection, const String& action)
1286 if (!LibWebRTCProvider::webRTCAvailable())
1289 connection.emulatePlatformEvent(action);
1292 void Internals::useMockRTCPeerConnectionFactory(const String& testCase)
1294 if (!LibWebRTCProvider::webRTCAvailable())
1298 Document* document = contextDocument();
1299 LibWebRTCProvider* provider = (document && document->page()) ? &document->page()->libWebRTCProvider() : nullptr;
1300 WebCore::useMockRTCPeerConnectionFactory(provider, testCase);
1302 UNUSED_PARAM(testCase);
1306 void Internals::setICECandidateFiltering(bool enabled)
1308 auto* page = contextDocument()->page();
1312 auto& rtcController = page->rtcController();
1314 rtcController.enableICECandidateFiltering();
1316 rtcController.disableICECandidateFiltering();
1319 void Internals::setEnumeratingAllNetworkInterfacesEnabled(bool enabled)
1322 Document* document = contextDocument();
1323 auto* page = document->page();
1326 auto& rtcProvider = page->libWebRTCProvider();
1328 rtcProvider.enableEnumeratingAllNetworkInterfaces();
1330 rtcProvider.disableEnumeratingAllNetworkInterfaces();
1332 UNUSED_PARAM(enabled);
1336 void Internals::stopPeerConnection(RTCPeerConnection& connection)
1338 ActiveDOMObject& object = connection;
1342 void Internals::applyRotationForOutgoingVideoSources(RTCPeerConnection& connection)
1344 connection.applyRotationForOutgoingVideoSources();
1348 #if ENABLE(MEDIA_STREAM)
1350 void Internals::setMockMediaCaptureDevicesEnabled(bool enabled)
1352 WebCore::DeprecatedGlobalSettings::setMockCaptureDevicesEnabled(enabled);
1357 ExceptionOr<Ref<DOMRect>> Internals::absoluteCaretBounds()
1359 Document* document = contextDocument();
1360 if (!document || !document->frame())
1361 return Exception { InvalidAccessError };
1363 return DOMRect::create(document->frame()->selection().absoluteCaretBounds());
1366 Ref<DOMRect> Internals::boundingBox(Element& element)
1368 element.document().updateLayoutIgnorePendingStylesheets();
1369 auto renderer = element.renderer();
1371 return DOMRect::create();
1372 return DOMRect::create(renderer->absoluteBoundingBoxRectIgnoringTransforms());
1375 ExceptionOr<Ref<DOMRectList>> Internals::inspectorHighlightRects()
1377 Document* document = contextDocument();
1378 if (!document || !document->page())
1379 return Exception { InvalidAccessError };
1381 Highlight highlight;
1382 document->page()->inspectorController().getHighlight(highlight, InspectorOverlay::CoordinateSystem::View);
1383 return DOMRectList::create(highlight.quads);
1386 ExceptionOr<String> Internals::inspectorHighlightObject()
1388 Document* document = contextDocument();
1389 if (!document || !document->page())
1390 return Exception { InvalidAccessError };
1392 return document->page()->inspectorController().buildObjectForHighlightedNodes()->toJSONString();
1395 ExceptionOr<unsigned> Internals::markerCountForNode(Node& node, const String& markerType)
1397 OptionSet<DocumentMarker::MarkerType> markerTypes;
1398 if (!markerTypesFrom(markerType, markerTypes))
1399 return Exception { SyntaxError };
1401 node.document().frame()->editor().updateEditorUINowIfScheduled();
1402 return node.document().markers().markersFor(&node, markerTypes).size();
1405 ExceptionOr<RenderedDocumentMarker*> Internals::markerAt(Node& node, const String& markerType, unsigned index)
1407 node.document().updateLayoutIgnorePendingStylesheets();
1409 OptionSet<DocumentMarker::MarkerType> markerTypes;
1410 if (!markerTypesFrom(markerType, markerTypes))
1411 return Exception { SyntaxError };
1413 node.document().frame()->editor().updateEditorUINowIfScheduled();
1415 Vector<RenderedDocumentMarker*> markers = node.document().markers().markersFor(&node, markerTypes);
1416 if (markers.size() <= index)
1418 return markers[index];
1421 ExceptionOr<RefPtr<Range>> Internals::markerRangeForNode(Node& node, const String& markerType, unsigned index)
1423 auto result = markerAt(node, markerType, index);
1424 if (result.hasException())
1425 return result.releaseException();
1426 auto marker = result.releaseReturnValue();
1429 return RefPtr<Range> { Range::create(node.document(), &node, marker->startOffset(), &node, marker->endOffset()) };
1432 ExceptionOr<String> Internals::markerDescriptionForNode(Node& node, const String& markerType, unsigned index)
1434 auto result = markerAt(node, markerType, index);
1435 if (result.hasException())
1436 return result.releaseException();
1437 auto marker = result.releaseReturnValue();
1440 return String { marker->description() };
1443 ExceptionOr<String> Internals::dumpMarkerRects(const String& markerTypeString)
1445 DocumentMarker::MarkerType markerType;
1446 if (!markerTypeFrom(markerTypeString, markerType))
1447 return Exception { SyntaxError };
1449 contextDocument()->markers().updateRectsForInvalidatedMarkersOfType(markerType);
1450 auto rects = contextDocument()->markers().renderedRectsForMarkers(markerType);
1452 StringBuilder rectString;
1453 rectString.appendLiteral("marker rects: ");
1454 for (const auto& rect : rects) {
1455 rectString.append('(');
1456 rectString.appendNumber(rect.x());
1457 rectString.appendLiteral(", ");
1458 rectString.appendNumber(rect.y());
1459 rectString.appendLiteral(", ");
1460 rectString.appendNumber(rect.width());
1461 rectString.appendLiteral(", ");
1462 rectString.appendNumber(rect.height());
1463 rectString.appendLiteral(") ");
1465 return rectString.toString();
1468 void Internals::addTextMatchMarker(const Range& range, bool isActive)
1470 range.ownerDocument().updateLayoutIgnorePendingStylesheets();
1471 range.ownerDocument().markers().addTextMatchMarker(&range, isActive);
1474 ExceptionOr<void> Internals::setMarkedTextMatchesAreHighlighted(bool flag)
1476 Document* document = contextDocument();
1477 if (!document || !document->frame())
1478 return Exception { InvalidAccessError };
1479 document->frame()->editor().setMarkedTextMatchesAreHighlighted(flag);
1483 void Internals::invalidateFontCache()
1485 FontCache::singleton().invalidate();
1488 void Internals::setFontSmoothingEnabled(bool enabled)
1490 WebCore::FontCascade::setShouldUseSmoothing(enabled);
1493 ExceptionOr<void> Internals::setLowPowerModeEnabled(bool isEnabled)
1495 auto* document = contextDocument();
1497 return Exception { InvalidAccessError };
1498 auto* page = document->page();
1500 return Exception { InvalidAccessError };
1502 page->setLowPowerModeEnabledOverrideForTesting(isEnabled);
1506 ExceptionOr<void> Internals::setScrollViewPosition(int x, int y)
1508 Document* document = contextDocument();
1509 if (!document || !document->view())
1510 return Exception { InvalidAccessError };
1512 auto& frameView = *document->view();
1513 bool constrainsScrollingToContentEdgeOldValue = frameView.constrainsScrollingToContentEdge();
1514 bool scrollbarsSuppressedOldValue = frameView.scrollbarsSuppressed();
1516 frameView.setConstrainsScrollingToContentEdge(false);
1517 frameView.setScrollbarsSuppressed(false);
1518 frameView.setScrollOffsetFromInternals({ x, y });
1519 frameView.setScrollbarsSuppressed(scrollbarsSuppressedOldValue);
1520 frameView.setConstrainsScrollingToContentEdge(constrainsScrollingToContentEdgeOldValue);
1525 ExceptionOr<void> Internals::unconstrainedScrollTo(Element& element, double x, double y)
1527 Document* document = contextDocument();
1528 if (!document || !document->view())
1529 return Exception { InvalidAccessError };
1531 element.scrollTo({ x, y }, ScrollClamping::Unclamped);
1535 ExceptionOr<Ref<DOMRect>> Internals::layoutViewportRect()
1537 Document* document = contextDocument();
1538 if (!document || !document->frame())
1539 return Exception { InvalidAccessError };
1541 document->updateLayoutIgnorePendingStylesheets();
1543 auto& frameView = *document->view();
1544 return DOMRect::create(frameView.layoutViewportRect());
1547 ExceptionOr<Ref<DOMRect>> Internals::visualViewportRect()
1549 Document* document = contextDocument();
1550 if (!document || !document->frame())
1551 return Exception { InvalidAccessError };
1553 document->updateLayoutIgnorePendingStylesheets();
1555 auto& frameView = *document->view();
1556 return DOMRect::create(frameView.visualViewportRect());
1559 ExceptionOr<void> Internals::setViewBaseBackgroundColor(const String& colorValue)
1561 Document* document = contextDocument();
1562 if (!document || !document->view())
1563 return Exception { InvalidAccessError };
1565 document->view()->setBaseBackgroundColor(Color(colorValue));
1569 ExceptionOr<void> Internals::setPagination(const String& mode, int gap, int pageLength)
1571 Document* document = contextDocument();
1572 if (!document || !document->page())
1573 return Exception { InvalidAccessError };
1575 Pagination pagination;
1576 if (mode == "Unpaginated")
1577 pagination.mode = Pagination::Unpaginated;
1578 else if (mode == "LeftToRightPaginated")
1579 pagination.mode = Pagination::LeftToRightPaginated;
1580 else if (mode == "RightToLeftPaginated")
1581 pagination.mode = Pagination::RightToLeftPaginated;
1582 else if (mode == "TopToBottomPaginated")
1583 pagination.mode = Pagination::TopToBottomPaginated;
1584 else if (mode == "BottomToTopPaginated")
1585 pagination.mode = Pagination::BottomToTopPaginated;
1587 return Exception { SyntaxError };
1589 pagination.gap = gap;
1590 pagination.pageLength = pageLength;
1591 document->page()->setPagination(pagination);
1596 ExceptionOr<void> Internals::setPaginationLineGridEnabled(bool enabled)
1598 Document* document = contextDocument();
1599 if (!document || !document->page())
1600 return Exception { InvalidAccessError };
1601 document->page()->setPaginationLineGridEnabled(enabled);
1605 ExceptionOr<String> Internals::configurationForViewport(float devicePixelRatio, int deviceWidth, int deviceHeight, int availableWidth, int availableHeight)
1607 Document* document = contextDocument();
1608 if (!document || !document->page())
1609 return Exception { InvalidAccessError };
1611 const int defaultLayoutWidthForNonMobilePages = 980;
1613 ViewportArguments arguments = document->page()->viewportArguments();
1614 ViewportAttributes attributes = computeViewportAttributes(arguments, defaultLayoutWidthForNonMobilePages, deviceWidth, deviceHeight, devicePixelRatio, IntSize(availableWidth, availableHeight));
1615 restrictMinimumScaleFactorToViewportSize(attributes, IntSize(availableWidth, availableHeight), devicePixelRatio);
1616 restrictScaleFactorToInitialScaleIfNotUserScalable(attributes);
1618 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") };
1621 ExceptionOr<bool> Internals::wasLastChangeUserEdit(Element& textField)
1623 if (is<HTMLInputElement>(textField))
1624 return downcast<HTMLInputElement>(textField).lastChangeWasUserEdit();
1626 if (is<HTMLTextAreaElement>(textField))
1627 return downcast<HTMLTextAreaElement>(textField).lastChangeWasUserEdit();
1629 return Exception { InvalidNodeTypeError };
1632 bool Internals::elementShouldAutoComplete(HTMLInputElement& element)
1634 return element.shouldAutocomplete();
1637 void Internals::setEditingValue(HTMLInputElement& element, const String& value)
1639 element.setEditingValue(value);
1642 void Internals::setAutofilled(HTMLInputElement& element, bool enabled)
1644 element.setAutoFilled(enabled);
1647 static AutoFillButtonType toAutoFillButtonType(Internals::AutoFillButtonType type)
1650 case Internals::AutoFillButtonType::AutoFillButtonTypeNone:
1651 return AutoFillButtonType::None;
1652 case Internals::AutoFillButtonType::AutoFillButtonTypeCredentials:
1653 return AutoFillButtonType::Credentials;
1654 case Internals::AutoFillButtonType::AutoFillButtonTypeContacts:
1655 return AutoFillButtonType::Contacts;
1657 ASSERT_NOT_REACHED();
1658 return AutoFillButtonType::None;
1661 void Internals::setShowAutoFillButton(HTMLInputElement& element, AutoFillButtonType type)
1663 element.setShowAutoFillButton(toAutoFillButtonType(type));
1666 ExceptionOr<void> Internals::scrollElementToRect(Element& element, int x, int y, int w, int h)
1668 FrameView* frameView = element.document().view();
1670 return Exception { InvalidAccessError };
1671 frameView->scrollElementToRect(element, { x, y, w, h });
1675 ExceptionOr<String> Internals::autofillFieldName(Element& element)
1677 if (!is<HTMLFormControlElement>(element))
1678 return Exception { InvalidNodeTypeError };
1680 return String { downcast<HTMLFormControlElement>(element).autofillData().fieldName };
1683 ExceptionOr<void> Internals::paintControlTints()
1685 Document* document = contextDocument();
1686 if (!document || !document->view())
1687 return Exception { InvalidAccessError };
1689 document->view()->paintControlTints();
1693 RefPtr<Range> Internals::rangeFromLocationAndLength(Element& scope, int rangeLocation, int rangeLength)
1695 return TextIterator::rangeFromLocationAndLength(&scope, rangeLocation, rangeLength);
1698 unsigned Internals::locationFromRange(Element& scope, const Range& range)
1700 size_t location = 0;
1701 size_t unusedLength = 0;
1702 TextIterator::getLocationAndLengthFromRange(&scope, &range, location, unusedLength);
1706 unsigned Internals::lengthFromRange(Element& scope, const Range& range)
1708 size_t unusedLocation = 0;
1710 TextIterator::getLocationAndLengthFromRange(&scope, &range, unusedLocation, length);
1714 String Internals::rangeAsText(const Range& range)
1716 return range.text();
1719 Ref<Range> Internals::subrange(Range& range, int rangeLocation, int rangeLength)
1721 return TextIterator::subrange(range, rangeLocation, rangeLength);
1724 RefPtr<Range> Internals::rangeOfStringNearLocation(const Range& searchRange, const String& text, unsigned targetOffset)
1726 return findClosestPlainText(searchRange, text, 0, targetOffset);
1729 ExceptionOr<RefPtr<Range>> Internals::rangeForDictionaryLookupAtLocation(int x, int y)
1732 auto* document = contextDocument();
1733 if (!document || !document->frame())
1734 return Exception { InvalidAccessError };
1736 document->updateLayoutIgnorePendingStylesheets();
1738 HitTestResult result = document->frame()->mainFrame().eventHandler().hitTestResultAtPoint(IntPoint(x, y));
1739 NSDictionary *options = nullptr;
1740 return DictionaryLookup::rangeAtHitTestResult(result, &options);
1744 return Exception { InvalidAccessError };
1748 ExceptionOr<void> Internals::setDelegatesScrolling(bool enabled)
1750 Document* document = contextDocument();
1751 // Delegate scrolling is valid only on mainframe's view.
1752 if (!document || !document->view() || !document->page() || &document->page()->mainFrame() != document->frame())
1753 return Exception { InvalidAccessError };
1755 document->view()->setDelegatesScrolling(enabled);
1759 ExceptionOr<int> Internals::lastSpellCheckRequestSequence()
1761 Document* document = contextDocument();
1762 if (!document || !document->frame())
1763 return Exception { InvalidAccessError };
1765 return document->frame()->editor().spellChecker().lastRequestSequence();
1768 ExceptionOr<int> Internals::lastSpellCheckProcessedSequence()
1770 Document* document = contextDocument();
1771 if (!document || !document->frame())
1772 return Exception { InvalidAccessError };
1774 return document->frame()->editor().spellChecker().lastProcessedSequence();
1777 Vector<String> Internals::userPreferredLanguages() const
1779 return WTF::userPreferredLanguages();
1782 void Internals::setUserPreferredLanguages(const Vector<String>& languages)
1784 overrideUserPreferredLanguages(languages);
1787 Vector<String> Internals::userPreferredAudioCharacteristics() const
1789 Document* document = contextDocument();
1790 if (!document || !document->page())
1791 return Vector<String>();
1792 #if ENABLE(VIDEO_TRACK)
1793 return document->page()->group().captionPreferences().preferredAudioCharacteristics();
1795 return Vector<String>();
1799 void Internals::setUserPreferredAudioCharacteristic(const String& characteristic)
1801 Document* document = contextDocument();
1802 if (!document || !document->page())
1804 #if ENABLE(VIDEO_TRACK)
1805 document->page()->group().captionPreferences().setPreferredAudioCharacteristic(characteristic);
1807 UNUSED_PARAM(characteristic);
1811 ExceptionOr<unsigned> Internals::wheelEventHandlerCount()
1813 Document* document = contextDocument();
1815 return Exception { InvalidAccessError };
1817 return document->wheelEventHandlerCount();
1820 ExceptionOr<unsigned> Internals::touchEventHandlerCount()
1822 Document* document = contextDocument();
1824 return Exception { InvalidAccessError };
1826 return document->touchEventHandlerCount();
1829 ExceptionOr<Ref<DOMRectList>> Internals::touchEventRectsForEvent(const String& eventName)
1831 Document* document = contextDocument();
1832 if (!document || !document->page())
1833 return Exception { InvalidAccessError };
1835 return document->page()->touchEventRectsForEvent(eventName);
1838 ExceptionOr<Ref<DOMRectList>> Internals::passiveTouchEventListenerRects()
1840 Document* document = contextDocument();
1841 if (!document || !document->page())
1842 return Exception { InvalidAccessError };
1844 return document->page()->passiveTouchEventListenerRects();
1847 // FIXME: Remove the document argument. It is almost always the same as
1848 // contextDocument(), with the exception of a few tests that pass a
1849 // different document, and could just make the call through another Internals
1850 // instance instead.
1851 ExceptionOr<RefPtr<NodeList>> Internals::nodesFromRect(Document& document, int centerX, int centerY, unsigned topPadding, unsigned rightPadding, unsigned bottomPadding, unsigned leftPadding, bool ignoreClipping, bool allowUserAgentShadowContent, bool allowChildFrameContent) const
1853 if (!document.frame() || !document.frame()->view())
1854 return Exception { InvalidAccessError };
1856 Frame* frame = document.frame();
1857 FrameView* frameView = document.view();
1858 RenderView* renderView = document.renderView();
1862 document.updateLayoutIgnorePendingStylesheets();
1864 float zoomFactor = frame->pageZoomFactor();
1865 LayoutPoint point(centerX * zoomFactor + frameView->scrollX(), centerY * zoomFactor + frameView->scrollY());
1867 HitTestRequest::HitTestRequestType hitType = HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::CollectMultipleElements;
1869 hitType |= HitTestRequest::IgnoreClipping;
1870 if (!allowUserAgentShadowContent)
1871 hitType |= HitTestRequest::DisallowUserAgentShadowContent;
1872 if (allowChildFrameContent)
1873 hitType |= HitTestRequest::AllowChildFrameContent;
1875 HitTestRequest request(hitType);
1877 // When ignoreClipping is false, this method returns null for coordinates outside of the viewport.
1878 if (!request.ignoreClipping() && !frameView->visibleContentRect().intersects(HitTestLocation::rectForPoint(point, topPadding, rightPadding, bottomPadding, leftPadding)))
1881 HitTestResult result(point, topPadding, rightPadding, bottomPadding, leftPadding);
1882 renderView->hitTest(request, result);
1883 const HitTestResult::NodeSet& nodeSet = result.listBasedTestResult();
1884 Vector<Ref<Node>> matches;
1885 matches.reserveInitialCapacity(nodeSet.size());
1886 for (auto& node : nodeSet)
1887 matches.uncheckedAppend(*node);
1889 return RefPtr<NodeList> { StaticNodeList::create(WTFMove(matches)) };
1892 class GetCallerCodeBlockFunctor {
1894 GetCallerCodeBlockFunctor()
1900 StackVisitor::Status operator()(StackVisitor& visitor) const
1903 if (m_iterations < 2)
1904 return StackVisitor::Continue;
1906 m_codeBlock = visitor->codeBlock();
1907 return StackVisitor::Done;
1910 CodeBlock* codeBlock() const { return m_codeBlock; }
1913 mutable int m_iterations;
1914 mutable CodeBlock* m_codeBlock;
1917 String Internals::parserMetaData(JSC::JSValue code)
1919 JSC::VM& vm = contextDocument()->vm();
1920 JSC::ExecState* exec = vm.topCallFrame;
1921 ScriptExecutable* executable;
1923 if (!code || code.isNull() || code.isUndefined()) {
1924 GetCallerCodeBlockFunctor iter;
1925 exec->iterate(iter);
1926 CodeBlock* codeBlock = iter.codeBlock();
1927 executable = codeBlock->ownerScriptExecutable();
1928 } else if (code.isFunction()) {
1929 JSFunction* funcObj = JSC::jsCast<JSFunction*>(code.toObject(exec));
1930 executable = funcObj->jsExecutable();
1934 unsigned startLine = executable->firstLine();
1935 unsigned startColumn = executable->startColumn();
1936 unsigned endLine = executable->lastLine();
1937 unsigned endColumn = executable->endColumn();
1939 StringBuilder result;
1941 if (executable->isFunctionExecutable()) {
1942 FunctionExecutable* funcExecutable = reinterpret_cast<FunctionExecutable*>(executable);
1943 String inferredName = funcExecutable->inferredName().string();
1944 result.appendLiteral("function \"");
1945 result.append(inferredName);
1947 } else if (executable->isEvalExecutable())
1948 result.appendLiteral("eval");
1949 else if (executable->isModuleProgramExecutable())
1950 result.appendLiteral("module");
1951 else if (executable->isProgramExecutable())
1952 result.appendLiteral("program");
1954 ASSERT_NOT_REACHED();
1956 result.appendLiteral(" { ");
1957 result.appendNumber(startLine);
1959 result.appendNumber(startColumn);
1960 result.appendLiteral(" - ");
1961 result.appendNumber(endLine);
1963 result.appendNumber(endColumn);
1964 result.appendLiteral(" }");
1966 return result.toString();
1969 void Internals::updateEditorUINowIfScheduled()
1971 if (Document* document = contextDocument()) {
1972 if (Frame* frame = document->frame())
1973 frame->editor().updateEditorUINowIfScheduled();
1977 bool Internals::hasSpellingMarker(int from, int length)
1979 Document* document = contextDocument();
1980 if (!document || !document->frame())
1983 updateEditorUINowIfScheduled();
1985 return document->frame()->editor().selectionStartHasMarkerFor(DocumentMarker::Spelling, from, length);
1988 bool Internals::hasAutocorrectedMarker(int from, int length)
1990 Document* document = contextDocument();
1991 if (!document || !document->frame())
1994 updateEditorUINowIfScheduled();
1996 return document->frame()->editor().selectionStartHasMarkerFor(DocumentMarker::Autocorrected, from, length);
1999 void Internals::setContinuousSpellCheckingEnabled(bool enabled)
2001 if (!contextDocument() || !contextDocument()->frame())
2004 if (enabled != contextDocument()->frame()->editor().isContinuousSpellCheckingEnabled())
2005 contextDocument()->frame()->editor().toggleContinuousSpellChecking();
2008 void Internals::setAutomaticQuoteSubstitutionEnabled(bool enabled)
2010 if (!contextDocument() || !contextDocument()->frame())
2013 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
2014 if (enabled != contextDocument()->frame()->editor().isAutomaticQuoteSubstitutionEnabled())
2015 contextDocument()->frame()->editor().toggleAutomaticQuoteSubstitution();
2017 UNUSED_PARAM(enabled);
2021 void Internals::setAutomaticLinkDetectionEnabled(bool enabled)
2023 if (!contextDocument() || !contextDocument()->frame())
2026 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
2027 if (enabled != contextDocument()->frame()->editor().isAutomaticLinkDetectionEnabled())
2028 contextDocument()->frame()->editor().toggleAutomaticLinkDetection();
2030 UNUSED_PARAM(enabled);
2034 void Internals::setAutomaticDashSubstitutionEnabled(bool enabled)
2036 if (!contextDocument() || !contextDocument()->frame())
2039 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
2040 if (enabled != contextDocument()->frame()->editor().isAutomaticDashSubstitutionEnabled())
2041 contextDocument()->frame()->editor().toggleAutomaticDashSubstitution();
2043 UNUSED_PARAM(enabled);
2047 void Internals::setAutomaticTextReplacementEnabled(bool enabled)
2049 if (!contextDocument() || !contextDocument()->frame())
2052 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
2053 if (enabled != contextDocument()->frame()->editor().isAutomaticTextReplacementEnabled())
2054 contextDocument()->frame()->editor().toggleAutomaticTextReplacement();
2056 UNUSED_PARAM(enabled);
2060 void Internals::setAutomaticSpellingCorrectionEnabled(bool enabled)
2062 if (!contextDocument() || !contextDocument()->frame())
2065 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
2066 if (enabled != contextDocument()->frame()->editor().isAutomaticSpellingCorrectionEnabled())
2067 contextDocument()->frame()->editor().toggleAutomaticSpellingCorrection();
2069 UNUSED_PARAM(enabled);
2073 void Internals::handleAcceptedCandidate(const String& candidate, unsigned location, unsigned length)
2075 if (!contextDocument() || !contextDocument()->frame())
2078 TextCheckingResult result;
2079 result.type = TextCheckingTypeNone;
2080 result.location = location;
2081 result.length = length;
2082 result.replacement = candidate;
2083 contextDocument()->frame()->editor().handleAcceptedCandidate(result);
2086 bool Internals::isOverwriteModeEnabled()
2088 Document* document = contextDocument();
2089 if (!document || !document->frame())
2092 return document->frame()->editor().isOverwriteModeEnabled();
2095 void Internals::toggleOverwriteModeEnabled()
2097 Document* document = contextDocument();
2098 if (!document || !document->frame())
2101 document->frame()->editor().toggleOverwriteModeEnabled();
2104 static ExceptionOr<FindOptions> parseFindOptions(const Vector<String>& optionList)
2108 FindOptionFlag value;
2110 {"CaseInsensitive", CaseInsensitive},
2111 {"AtWordStarts", AtWordStarts},
2112 {"TreatMedialCapitalAsWordStart", TreatMedialCapitalAsWordStart},
2113 {"Backwards", Backwards},
2114 {"WrapAround", WrapAround},
2115 {"StartInSelection", StartInSelection},
2116 {"DoNotRevealSelection", DoNotRevealSelection},
2117 {"AtWordEnds", AtWordEnds},
2118 {"DoNotTraverseFlatTree", DoNotTraverseFlatTree},
2120 FindOptions result = 0;
2121 for (auto& option : optionList) {
2123 for (auto& flag : flagList) {
2124 if (flag.name == option) {
2125 result |= flag.value;
2131 return Exception { SyntaxError };
2136 ExceptionOr<RefPtr<Range>> Internals::rangeOfString(const String& text, RefPtr<Range>&& referenceRange, const Vector<String>& findOptions)
2138 Document* document = contextDocument();
2139 if (!document || !document->frame())
2140 return Exception { InvalidAccessError };
2142 auto parsedOptions = parseFindOptions(findOptions);
2143 if (parsedOptions.hasException())
2144 return parsedOptions.releaseException();
2146 return document->frame()->editor().rangeOfString(text, referenceRange.get(), parsedOptions.releaseReturnValue());
2149 ExceptionOr<unsigned> Internals::countMatchesForText(const String& text, const Vector<String>& findOptions, const String& markMatches)
2151 Document* document = contextDocument();
2152 if (!document || !document->frame())
2153 return Exception { InvalidAccessError };
2155 auto parsedOptions = parseFindOptions(findOptions);
2156 if (parsedOptions.hasException())
2157 return parsedOptions.releaseException();
2159 bool mark = markMatches == "mark";
2160 return document->frame()->editor().countMatchesForText(text, nullptr, parsedOptions.releaseReturnValue(), 1000, mark, nullptr);
2163 ExceptionOr<unsigned> Internals::countFindMatches(const String& text, const Vector<String>& findOptions)
2165 Document* document = contextDocument();
2166 if (!document || !document->page())
2167 return Exception { InvalidAccessError };
2169 auto parsedOptions = parseFindOptions(findOptions);
2170 if (parsedOptions.hasException())
2171 return parsedOptions.releaseException();
2173 return document->page()->countFindMatches(text, parsedOptions.releaseReturnValue(), 1000);
2176 unsigned Internals::numberOfLiveNodes() const
2178 unsigned nodeCount = 0;
2179 for (auto* document : Document::allDocuments())
2180 nodeCount += document->referencingNodeCount();
2184 unsigned Internals::numberOfLiveDocuments() const
2186 return Document::allDocuments().size();
2189 unsigned Internals::referencingNodeCount(const Document& document) const
2191 return document.referencingNodeCount();
2194 RefPtr<DOMWindow> Internals::openDummyInspectorFrontend(const String& url)
2196 auto* inspectedPage = contextDocument()->frame()->page();
2197 auto* window = inspectedPage->mainFrame().document()->domWindow();
2198 auto frontendWindow = window->open(*window, *window, url, "", "");
2199 m_inspectorFrontend = std::make_unique<InspectorStubFrontend>(*inspectedPage, frontendWindow.copyRef());
2200 return frontendWindow;
2203 void Internals::closeDummyInspectorFrontend()
2205 m_inspectorFrontend = nullptr;
2208 ExceptionOr<void> Internals::setInspectorIsUnderTest(bool isUnderTest)
2210 Page* page = contextDocument()->frame()->page();
2212 return Exception { InvalidAccessError };
2214 page->inspectorController().setIsUnderTest(isUnderTest);
2218 bool Internals::hasGrammarMarker(int from, int length)
2220 Document* document = contextDocument();
2221 if (!document || !document->frame())
2224 return document->frame()->editor().selectionStartHasMarkerFor(DocumentMarker::Grammar, from, length);
2227 unsigned Internals::numberOfScrollableAreas()
2229 Document* document = contextDocument();
2230 if (!document || !document->frame())
2234 Frame* frame = document->frame();
2235 if (frame->view()->scrollableAreas())
2236 count += frame->view()->scrollableAreas()->size();
2238 for (Frame* child = frame->tree().firstChild(); child; child = child->tree().nextSibling()) {
2239 if (child->view() && child->view()->scrollableAreas())
2240 count += child->view()->scrollableAreas()->size();
2246 ExceptionOr<bool> Internals::isPageBoxVisible(int pageNumber)
2248 Document* document = contextDocument();
2250 return Exception { InvalidAccessError };
2252 return document->isPageBoxVisible(pageNumber);
2255 static LayerTreeFlags toLayerTreeFlags(unsigned short flags)
2257 LayerTreeFlags layerTreeFlags = 0;
2258 if (flags & Internals::LAYER_TREE_INCLUDES_VISIBLE_RECTS)
2259 layerTreeFlags |= LayerTreeFlagsIncludeVisibleRects;
2260 if (flags & Internals::LAYER_TREE_INCLUDES_TILE_CACHES)
2261 layerTreeFlags |= LayerTreeFlagsIncludeTileCaches;
2262 if (flags & Internals::LAYER_TREE_INCLUDES_REPAINT_RECTS)
2263 layerTreeFlags |= LayerTreeFlagsIncludeRepaintRects;
2264 if (flags & Internals::LAYER_TREE_INCLUDES_PAINTING_PHASES)
2265 layerTreeFlags |= LayerTreeFlagsIncludePaintingPhases;
2266 if (flags & Internals::LAYER_TREE_INCLUDES_CONTENT_LAYERS)
2267 layerTreeFlags |= LayerTreeFlagsIncludeContentLayers;
2268 if (flags & Internals::LAYER_TREE_INCLUDES_ACCELERATES_DRAWING)
2269 layerTreeFlags |= LayerTreeFlagsIncludeAcceleratesDrawing;
2270 if (flags & Internals::LAYER_TREE_INCLUDES_BACKING_STORE_ATTACHED)
2271 layerTreeFlags |= LayerTreeFlagsIncludeBackingStoreAttached;
2273 return layerTreeFlags;
2276 // FIXME: Remove the document argument. It is almost always the same as
2277 // contextDocument(), with the exception of a few tests that pass a
2278 // different document, and could just make the call through another Internals
2279 // instance instead.
2280 ExceptionOr<String> Internals::layerTreeAsText(Document& document, unsigned short flags) const
2282 if (!document.frame())
2283 return Exception { InvalidAccessError };
2285 document.updateLayoutIgnorePendingStylesheets();
2286 return document.frame()->layerTreeAsText(toLayerTreeFlags(flags));
2289 ExceptionOr<uint64_t> Internals::layerIDForElement(Element& element)
2291 Document* document = contextDocument();
2292 if (!document || !document->frame())
2293 return Exception { InvalidAccessError };
2295 element.document().updateLayoutIgnorePendingStylesheets();
2297 if (!element.renderer() || !element.renderer()->hasLayer())
2298 return Exception { NotFoundError };
2300 auto& layerModelObject = downcast<RenderLayerModelObject>(*element.renderer());
2301 if (!layerModelObject.layer()->isComposited())
2302 return Exception { NotFoundError };
2304 auto* backing = layerModelObject.layer()->backing();
2305 return backing->graphicsLayer()->primaryLayerID();
2308 ExceptionOr<String> Internals::repaintRectsAsText() const
2310 Document* document = contextDocument();
2311 if (!document || !document->frame())
2312 return Exception { InvalidAccessError };
2314 return document->frame()->trackedRepaintRectsAsText();
2317 ExceptionOr<String> Internals::scrollingStateTreeAsText() const
2319 Document* document = contextDocument();
2320 if (!document || !document->frame())
2321 return Exception { InvalidAccessError };
2323 Page* page = document->page();
2327 return page->scrollingStateTreeAsText();
2330 ExceptionOr<String> Internals::mainThreadScrollingReasons() const
2332 Document* document = contextDocument();
2333 if (!document || !document->frame())
2334 return Exception { InvalidAccessError };
2336 Page* page = document->page();
2340 return page->synchronousScrollingReasonsAsText();
2343 ExceptionOr<Ref<DOMRectList>> Internals::nonFastScrollableRects() const
2345 Document* document = contextDocument();
2346 if (!document || !document->frame())
2347 return Exception { InvalidAccessError };
2349 Page* page = document->page();
2351 return DOMRectList::create();
2353 return page->nonFastScrollableRects();
2356 ExceptionOr<void> Internals::setElementUsesDisplayListDrawing(Element& element, bool usesDisplayListDrawing)
2358 Document* document = contextDocument();
2359 if (!document || !document->renderView())
2360 return Exception { InvalidAccessError };
2362 element.document().updateLayoutIgnorePendingStylesheets();
2364 if (!element.renderer())
2365 return Exception { InvalidAccessError };
2367 if (is<HTMLCanvasElement>(element)) {
2368 downcast<HTMLCanvasElement>(element).setUsesDisplayListDrawing(usesDisplayListDrawing);
2372 if (!element.renderer()->hasLayer())
2373 return Exception { InvalidAccessError };
2375 RenderLayer* layer = downcast<RenderLayerModelObject>(element.renderer())->layer();
2376 if (!layer->isComposited())
2377 return Exception { InvalidAccessError };
2379 layer->backing()->setUsesDisplayListDrawing(usesDisplayListDrawing);
2383 ExceptionOr<void> Internals::setElementTracksDisplayListReplay(Element& element, bool isTrackingReplay)
2385 Document* document = contextDocument();
2386 if (!document || !document->renderView())
2387 return Exception { InvalidAccessError };
2389 element.document().updateLayoutIgnorePendingStylesheets();
2391 if (!element.renderer())
2392 return Exception { InvalidAccessError };
2394 if (is<HTMLCanvasElement>(element)) {
2395 downcast<HTMLCanvasElement>(element).setTracksDisplayListReplay(isTrackingReplay);
2399 if (!element.renderer()->hasLayer())
2400 return Exception { InvalidAccessError };
2402 RenderLayer* layer = downcast<RenderLayerModelObject>(element.renderer())->layer();
2403 if (!layer->isComposited())
2404 return Exception { InvalidAccessError };
2406 layer->backing()->setIsTrackingDisplayListReplay(isTrackingReplay);
2410 ExceptionOr<String> Internals::displayListForElement(Element& element, unsigned short flags)
2412 Document* document = contextDocument();
2413 if (!document || !document->renderView())
2414 return Exception { InvalidAccessError };
2416 element.document().updateLayoutIgnorePendingStylesheets();
2418 if (!element.renderer())
2419 return Exception { InvalidAccessError };
2421 DisplayList::AsTextFlags displayListFlags = 0;
2422 if (flags & DISPLAY_LIST_INCLUDES_PLATFORM_OPERATIONS)
2423 displayListFlags |= DisplayList::AsTextFlag::IncludesPlatformOperations;
2425 if (is<HTMLCanvasElement>(element))
2426 return downcast<HTMLCanvasElement>(element).displayListAsText(displayListFlags);
2428 if (!element.renderer()->hasLayer())
2429 return Exception { InvalidAccessError };
2431 RenderLayer* layer = downcast<RenderLayerModelObject>(element.renderer())->layer();
2432 if (!layer->isComposited())
2433 return Exception { InvalidAccessError };
2435 return layer->backing()->displayListAsText(displayListFlags);
2438 ExceptionOr<String> Internals::replayDisplayListForElement(Element& element, unsigned short flags)
2440 Document* document = contextDocument();
2441 if (!document || !document->renderView())
2442 return Exception { InvalidAccessError };
2444 element.document().updateLayoutIgnorePendingStylesheets();
2446 if (!element.renderer())
2447 return Exception { InvalidAccessError };
2449 DisplayList::AsTextFlags displayListFlags = 0;
2450 if (flags & DISPLAY_LIST_INCLUDES_PLATFORM_OPERATIONS)
2451 displayListFlags |= DisplayList::AsTextFlag::IncludesPlatformOperations;
2453 if (is<HTMLCanvasElement>(element))
2454 return downcast<HTMLCanvasElement>(element).replayDisplayListAsText(displayListFlags);
2456 if (!element.renderer()->hasLayer())
2457 return Exception { InvalidAccessError };
2459 RenderLayer* layer = downcast<RenderLayerModelObject>(element.renderer())->layer();
2460 if (!layer->isComposited())
2461 return Exception { InvalidAccessError };
2463 return layer->backing()->replayDisplayListAsText(displayListFlags);
2466 ExceptionOr<void> Internals::garbageCollectDocumentResources() const
2468 Document* document = contextDocument();
2470 return Exception { InvalidAccessError };
2471 document->cachedResourceLoader().garbageCollectDocumentResources();
2475 bool Internals::isUnderMemoryPressure()
2477 return MemoryPressureHandler::singleton().isUnderMemoryPressure();
2480 void Internals::beginSimulatedMemoryPressure()
2482 MemoryPressureHandler::singleton().beginSimulatedMemoryPressure();
2485 void Internals::endSimulatedMemoryPressure()
2487 MemoryPressureHandler::singleton().endSimulatedMemoryPressure();
2490 ExceptionOr<void> Internals::insertAuthorCSS(const String& css) const
2492 Document* document = contextDocument();
2494 return Exception { InvalidAccessError };
2496 auto parsedSheet = StyleSheetContents::create(*document);
2497 parsedSheet.get().setIsUserStyleSheet(false);
2498 parsedSheet.get().parseString(css);
2499 document->extensionStyleSheets().addAuthorStyleSheetForTesting(WTFMove(parsedSheet));
2503 ExceptionOr<void> Internals::insertUserCSS(const String& css) const
2505 Document* document = contextDocument();
2507 return Exception { InvalidAccessError };
2509 auto parsedSheet = StyleSheetContents::create(*document);
2510 parsedSheet.get().setIsUserStyleSheet(true);
2511 parsedSheet.get().parseString(css);
2512 document->extensionStyleSheets().addUserStyleSheet(WTFMove(parsedSheet));
2516 String Internals::counterValue(Element& element)
2518 return counterValueForElement(&element);
2521 int Internals::pageNumber(Element& element, float pageWidth, float pageHeight)
2523 return PrintContext::pageNumberForElement(&element, { pageWidth, pageHeight });
2526 Vector<String> Internals::shortcutIconURLs() const
2531 auto* documentLoader = frame()->loader().documentLoader();
2532 if (!documentLoader)
2535 Vector<String> result;
2536 for (auto& linkIcon : documentLoader->linkIcons())
2537 result.append(linkIcon.url.string());
2542 int Internals::numberOfPages(float pageWidth, float pageHeight)
2547 return PrintContext::numberOfPages(*frame(), FloatSize(pageWidth, pageHeight));
2550 ExceptionOr<String> Internals::pageProperty(const String& propertyName, int pageNumber) const
2553 return Exception { InvalidAccessError };
2555 return PrintContext::pageProperty(frame(), propertyName.utf8().data(), pageNumber);
2558 ExceptionOr<String> Internals::pageSizeAndMarginsInPixels(int pageNumber, int width, int height, int marginTop, int marginRight, int marginBottom, int marginLeft) const
2561 return Exception { InvalidAccessError };
2563 return PrintContext::pageSizeAndMarginsInPixels(frame(), pageNumber, width, height, marginTop, marginRight, marginBottom, marginLeft);
2566 ExceptionOr<float> Internals::pageScaleFactor() const
2568 Document* document = contextDocument();
2569 if (!document || !document->page())
2570 return Exception { InvalidAccessError };
2572 return document->page()->pageScaleFactor();
2575 ExceptionOr<void> Internals::setPageScaleFactor(float scaleFactor, int x, int y)
2577 Document* document = contextDocument();
2578 if (!document || !document->page())
2579 return Exception { InvalidAccessError };
2581 document->page()->setPageScaleFactor(scaleFactor, IntPoint(x, y));
2585 ExceptionOr<void> Internals::setPageZoomFactor(float zoomFactor)
2587 Document* document = contextDocument();
2588 if (!document || !document->frame())
2589 return Exception { InvalidAccessError };
2591 document->frame()->setPageZoomFactor(zoomFactor);
2595 ExceptionOr<void> Internals::setTextZoomFactor(float zoomFactor)
2597 Document* document = contextDocument();
2598 if (!document || !document->frame())
2599 return Exception { InvalidAccessError };
2601 document->frame()->setTextZoomFactor(zoomFactor);
2605 ExceptionOr<void> Internals::setUseFixedLayout(bool useFixedLayout)
2607 Document* document = contextDocument();
2608 if (!document || !document->view())
2609 return Exception { InvalidAccessError };
2611 document->view()->setUseFixedLayout(useFixedLayout);
2615 ExceptionOr<void> Internals::setFixedLayoutSize(int width, int height)
2617 Document* document = contextDocument();
2618 if (!document || !document->view())
2619 return Exception { InvalidAccessError };
2621 document->view()->setFixedLayoutSize(IntSize(width, height));
2625 ExceptionOr<void> Internals::setViewExposedRect(float x, float y, float width, float height)
2627 Document* document = contextDocument();
2628 if (!document || !document->view())
2629 return Exception { InvalidAccessError };
2631 document->view()->setViewExposedRect(FloatRect(x, y, width, height));
2635 void Internals::setPrinting(int width, int height)
2637 printContextForTesting() = std::make_unique<PrintContext>(frame());
2638 printContextForTesting()->begin(width, height);
2641 void Internals::setHeaderHeight(float height)
2643 Document* document = contextDocument();
2644 if (!document || !document->view())
2647 document->view()->setHeaderHeight(height);
2650 void Internals::setFooterHeight(float height)
2652 Document* document = contextDocument();
2653 if (!document || !document->view())
2656 document->view()->setFooterHeight(height);
2659 void Internals::setTopContentInset(float contentInset)
2661 Document* document = contextDocument();
2662 if (!document || !document->page())
2665 document->page()->setTopContentInset(contentInset);
2668 #if ENABLE(FULLSCREEN_API)
2670 void Internals::webkitWillEnterFullScreenForElement(Element& element)
2672 Document* document = contextDocument();
2675 document->webkitWillEnterFullScreenForElement(&element);
2678 void Internals::webkitDidEnterFullScreenForElement(Element& element)
2680 Document* document = contextDocument();
2683 document->webkitDidEnterFullScreenForElement(&element);
2686 void Internals::webkitWillExitFullScreenForElement(Element& element)
2688 Document* document = contextDocument();
2691 document->webkitWillExitFullScreenForElement(&element);
2694 void Internals::webkitDidExitFullScreenForElement(Element& element)
2696 Document* document = contextDocument();
2699 document->webkitDidExitFullScreenForElement(&element);
2704 void Internals::setApplicationCacheOriginQuota(unsigned long long quota)
2706 Document* document = contextDocument();
2707 if (!document || !document->page())
2709 document->page()->applicationCacheStorage().storeUpdatedQuotaForOrigin(&document->securityOrigin(), quota);
2712 void Internals::registerURLSchemeAsBypassingContentSecurityPolicy(const String& scheme)
2714 SchemeRegistry::registerURLSchemeAsBypassingContentSecurityPolicy(scheme);
2717 void Internals::removeURLSchemeRegisteredAsBypassingContentSecurityPolicy(const String& scheme)
2719 SchemeRegistry::removeURLSchemeRegisteredAsBypassingContentSecurityPolicy(scheme);
2722 void Internals::registerDefaultPortForProtocol(unsigned short port, const String& protocol)
2724 registerDefaultPortForProtocolForTesting(port, protocol);
2727 Ref<MallocStatistics> Internals::mallocStatistics() const
2729 return MallocStatistics::create();
2732 Ref<TypeConversions> Internals::typeConversions() const
2734 return TypeConversions::create();
2737 Ref<MemoryInfo> Internals::memoryInfo() const
2739 return MemoryInfo::create();
2742 Vector<String> Internals::getReferencedFilePaths() const
2744 frame()->loader().history().saveDocumentAndScrollState();
2745 return FormController::getReferencedFilePaths(frame()->loader().history().currentItem()->documentState());
2748 ExceptionOr<void> Internals::startTrackingRepaints()
2750 Document* document = contextDocument();
2751 if (!document || !document->view())
2752 return Exception { InvalidAccessError };
2754 document->view()->setTracksRepaints(true);
2758 ExceptionOr<void> Internals::stopTrackingRepaints()
2760 Document* document = contextDocument();
2761 if (!document || !document->view())
2762 return Exception { InvalidAccessError };
2764 document->view()->setTracksRepaints(false);
2768 ExceptionOr<void> Internals::startTrackingLayerFlushes()
2770 Document* document = contextDocument();
2771 if (!document || !document->renderView())
2772 return Exception { InvalidAccessError };
2774 document->renderView()->compositor().startTrackingLayerFlushes();
2778 ExceptionOr<unsigned> Internals::layerFlushCount()
2780 Document* document = contextDocument();
2781 if (!document || !document->renderView())
2782 return Exception { InvalidAccessError };
2784 return document->renderView()->compositor().layerFlushCount();
2787 ExceptionOr<void> Internals::startTrackingStyleRecalcs()
2789 Document* document = contextDocument();
2791 return Exception { InvalidAccessError };
2793 document->startTrackingStyleRecalcs();
2797 ExceptionOr<unsigned> Internals::styleRecalcCount()
2799 Document* document = contextDocument();
2801 return Exception { InvalidAccessError };
2803 return document->styleRecalcCount();
2806 unsigned Internals::lastStyleUpdateSize() const
2808 Document* document = contextDocument();
2811 return document->lastStyleUpdateSizeForTesting();
2814 ExceptionOr<void> Internals::startTrackingCompositingUpdates()
2816 Document* document = contextDocument();
2817 if (!document || !document->renderView())
2818 return Exception { InvalidAccessError };
2820 document->renderView()->compositor().startTrackingCompositingUpdates();
2824 ExceptionOr<unsigned> Internals::compositingUpdateCount()
2826 Document* document = contextDocument();
2827 if (!document || !document->renderView())
2828 return Exception { InvalidAccessError };
2830 return document->renderView()->compositor().compositingUpdateCount();
2833 ExceptionOr<void> Internals::updateLayoutIgnorePendingStylesheetsAndRunPostLayoutTasks(Node* node)
2837 document = contextDocument();
2838 else if (is<Document>(*node))
2839 document = downcast<Document>(node);
2840 else if (is<HTMLIFrameElement>(*node))
2841 document = downcast<HTMLIFrameElement>(*node).contentDocument();
2843 return Exception { TypeError };
2845 document->updateLayoutIgnorePendingStylesheets(Document::RunPostLayoutTasks::Synchronously);
2849 unsigned Internals::layoutCount() const
2851 Document* document = contextDocument();
2852 if (!document || !document->view())
2854 return document->view()->layoutContext().layoutCount();
2858 static const char* cursorTypeToString(Cursor::Type cursorType)
2860 switch (cursorType) {
2861 case Cursor::Pointer: return "Pointer";
2862 case Cursor::Cross: return "Cross";
2863 case Cursor::Hand: return "Hand";
2864 case Cursor::IBeam: return "IBeam";
2865 case Cursor::Wait: return "Wait";
2866 case Cursor::Help: return "Help";
2867 case Cursor::EastResize: return "EastResize";
2868 case Cursor::NorthResize: return "NorthResize";
2869 case Cursor::NorthEastResize: return "NorthEastResize";
2870 case Cursor::NorthWestResize: return "NorthWestResize";
2871 case Cursor::SouthResize: return "SouthResize";
2872 case Cursor::SouthEastResize: return "SouthEastResize";
2873 case Cursor::SouthWestResize: return "SouthWestResize";
2874 case Cursor::WestResize: return "WestResize";
2875 case Cursor::NorthSouthResize: return "NorthSouthResize";
2876 case Cursor::EastWestResize: return "EastWestResize";
2877 case Cursor::NorthEastSouthWestResize: return "NorthEastSouthWestResize";
2878 case Cursor::NorthWestSouthEastResize: return "NorthWestSouthEastResize";
2879 case Cursor::ColumnResize: return "ColumnResize";
2880 case Cursor::RowResize: return "RowResize";
2881 case Cursor::MiddlePanning: return "MiddlePanning";
2882 case Cursor::EastPanning: return "EastPanning";
2883 case Cursor::NorthPanning: return "NorthPanning";
2884 case Cursor::NorthEastPanning: return "NorthEastPanning";
2885 case Cursor::NorthWestPanning: return "NorthWestPanning";
2886 case Cursor::SouthPanning: return "SouthPanning";
2887 case Cursor::SouthEastPanning: return "SouthEastPanning";
2888 case Cursor::SouthWestPanning: return "SouthWestPanning";
2889 case Cursor::WestPanning: return "WestPanning";
2890 case Cursor::Move: return "Move";
2891 case Cursor::VerticalText: return "VerticalText";
2892 case Cursor::Cell: return "Cell";
2893 case Cursor::ContextMenu: return "ContextMenu";
2894 case Cursor::Alias: return "Alias";
2895 case Cursor::Progress: return "Progress";
2896 case Cursor::NoDrop: return "NoDrop";
2897 case Cursor::Copy: return "Copy";
2898 case Cursor::None: return "None";
2899 case Cursor::NotAllowed: return "NotAllowed";
2900 case Cursor::ZoomIn: return "ZoomIn";
2901 case Cursor::ZoomOut: return "ZoomOut";
2902 case Cursor::Grab: return "Grab";
2903 case Cursor::Grabbing: return "Grabbing";
2904 case Cursor::Custom: return "Custom";
2907 ASSERT_NOT_REACHED();
2912 ExceptionOr<String> Internals::getCurrentCursorInfo()
2914 Document* document = contextDocument();
2915 if (!document || !document->frame())
2916 return Exception { InvalidAccessError };
2919 Cursor cursor = document->frame()->eventHandler().currentMouseCursor();
2921 StringBuilder result;
2922 result.appendLiteral("type=");
2923 result.append(cursorTypeToString(cursor.type()));
2924 result.appendLiteral(" hotSpot=");
2925 result.appendNumber(cursor.hotSpot().x());
2927 result.appendNumber(cursor.hotSpot().y());
2928 if (cursor.image()) {
2929 FloatSize size = cursor.image()->size();
2930 result.appendLiteral(" image=");
2931 result.appendNumber(size.width());
2933 result.appendNumber(size.height());
2935 #if ENABLE(MOUSE_CURSOR_SCALE)
2936 if (cursor.imageScaleFactor() != 1) {
2937 result.appendLiteral(" scale=");
2938 NumberToStringBuffer buffer;
2939 result.append(numberToFixedPrecisionString(cursor.imageScaleFactor(), 8, buffer, true));
2942 return result.toString();
2944 return String { "FAIL: Cursor details not available on this platform." };
2948 Ref<ArrayBuffer> Internals::serializeObject(const RefPtr<SerializedScriptValue>& value) const
2950 auto& bytes = value->data();
2951 return ArrayBuffer::create(bytes.data(), bytes.size());
2954 Ref<SerializedScriptValue> Internals::deserializeBuffer(ArrayBuffer& buffer) const
2956 Vector<uint8_t> bytes;
2957 bytes.append(static_cast<const uint8_t*>(buffer.data()), buffer.byteLength());
2958 return SerializedScriptValue::adopt(WTFMove(bytes));
2961 bool Internals::isFromCurrentWorld(JSC::JSValue value) const
2963 auto& state = *contextDocument()->vm().topCallFrame;
2964 return !value.isObject() || &worldForDOMObject(asObject(value)) == ¤tWorld(&state);
2967 void Internals::setUsesOverlayScrollbars(bool enabled)
2969 WebCore::DeprecatedGlobalSettings::setUsesOverlayScrollbars(enabled);
2972 void Internals::setUsesMockScrollAnimator(bool enabled)
2974 WebCore::DeprecatedGlobalSettings::setUsesMockScrollAnimator(enabled);
2977 void Internals::forceReload(bool endToEnd)
2979 OptionSet<ReloadOption> reloadOptions;
2981 reloadOptions |= ReloadOption::FromOrigin;
2983 frame()->loader().reload(reloadOptions);
2986 void Internals::reloadExpiredOnly()
2988 frame()->loader().reload(ReloadOption::ExpiredOnly);
2991 void Internals::enableAutoSizeMode(bool enabled, int minimumWidth, int minimumHeight, int maximumWidth, int maximumHeight)
2993 auto* document = contextDocument();
2994 if (!document || !document->view())
2996 document->view()->enableAutoSizeMode(enabled, IntSize(minimumWidth, minimumHeight), IntSize(maximumWidth, maximumHeight));
2999 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
3001 void Internals::initializeMockCDM()
3003 LegacyCDM::registerCDMFactory([] (LegacyCDM* cdm) { return std::make_unique<LegacyMockCDM>(cdm); },
3004 LegacyMockCDM::supportsKeySystem, LegacyMockCDM::supportsKeySystemAndMimeType);
3009 #if ENABLE(ENCRYPTED_MEDIA)
3011 Ref<MockCDMFactory> Internals::registerMockCDM()
3013 return MockCDMFactory::create();
3018 String Internals::markerTextForListItem(Element& element)
3020 return WebCore::markerTextForListItem(&element);
3023 String Internals::toolTipFromElement(Element& element) const
3025 HitTestResult result;
3026 result.setInnerNode(&element);
3027 TextDirection direction;
3028 return result.title(direction);
3031 String Internals::getImageSourceURL(Element& element)
3033 return element.imageSourceURL();
3038 Vector<String> Internals::mediaResponseSources(HTMLMediaElement& media)
3040 auto* resourceLoader = media.lastMediaResourceLoaderForTesting();
3041 if (!resourceLoader)
3043 Vector<String> result;
3044 auto responses = resourceLoader->responsesForTesting();
3045 for (auto& response : responses)
3046 result.append(responseSourceToString(response));
3050 Vector<String> Internals::mediaResponseContentRanges(HTMLMediaElement& media)
3052 auto* resourceLoader = media.lastMediaResourceLoaderForTesting();
3053 if (!resourceLoader)
3055 Vector<String> result;
3056 auto responses = resourceLoader->responsesForTesting();
3057 for (auto& response : responses)
3058 result.append(response.httpHeaderField(HTTPHeaderName::ContentRange));
3062 void Internals::simulateAudioInterruption(HTMLMediaElement& element)
3065 element.player()->simulateAudioInterruption();
3067 UNUSED_PARAM(element);
3071 ExceptionOr<bool> Internals::mediaElementHasCharacteristic(HTMLMediaElement& element, const String& characteristic)
3073 if (equalLettersIgnoringASCIICase(characteristic, "audible"))
3074 return element.hasAudio();
3075 if (equalLettersIgnoringASCIICase(characteristic, "visual"))
3076 return element.hasVideo();
3077 if (equalLettersIgnoringASCIICase(characteristic, "legible"))
3078 return element.hasClosedCaptions();
3080 return Exception { SyntaxError };
3085 bool Internals::isSelectPopupVisible(HTMLSelectElement& element)
3087 element.document().updateLayoutIgnorePendingStylesheets();
3089 auto* renderer = element.renderer();
3090 if (!is<RenderMenuList>(renderer))
3094 return downcast<RenderMenuList>(*renderer).popupIsVisible();
3100 ExceptionOr<String> Internals::captionsStyleSheetOverride()
3102 Document* document = contextDocument();
3103 if (!document || !document->page())
3104 return Exception { InvalidAccessError };
3106 #if ENABLE(VIDEO_TRACK)
3107 return document->page()->group().captionPreferences().captionsStyleSheetOverride();
3109 return String { emptyString() };
3113 ExceptionOr<void> Internals::setCaptionsStyleSheetOverride(const String& override)
3115 Document* document = contextDocument();
3116 if (!document || !document->page())
3117 return Exception { InvalidAccessError };
3119 #if ENABLE(VIDEO_TRACK)
3120 document->page()->group().captionPreferences().setCaptionsStyleSheetOverride(override);
3122 UNUSED_PARAM(override);
3127 ExceptionOr<void> Internals::setPrimaryAudioTrackLanguageOverride(const String& language)
3129 Document* document = contextDocument();
3130 if (!document || !document->page())
3131 return Exception { InvalidAccessError };
3133 #if ENABLE(VIDEO_TRACK)
3134 document->page()->group().captionPreferences().setPrimaryAudioTrackLanguageOverride(language);
3136 UNUSED_PARAM(language);
3141 ExceptionOr<void> Internals::setCaptionDisplayMode(const String& mode)
3143 Document* document = contextDocument();
3144 if (!document || !document->page())
3145 return Exception { InvalidAccessError };
3147 #if ENABLE(VIDEO_TRACK)
3148 auto& captionPreferences = document->page()->group().captionPreferences();
3150 if (equalLettersIgnoringASCIICase(mode, "automatic"))
3151 captionPreferences.setCaptionDisplayMode(CaptionUserPreferences::Automatic);
3152 else if (equalLettersIgnoringASCIICase(mode, "forcedonly"))
3153 captionPreferences.setCaptionDisplayMode(CaptionUserPreferences::ForcedOnly);
3154 else if (equalLettersIgnoringASCIICase(mode, "alwayson"))
3155 captionPreferences.setCaptionDisplayMode(CaptionUserPreferences::AlwaysOn);
3156 else if (equalLettersIgnoringASCIICase(mode, "manual"))
3157 captionPreferences.setCaptionDisplayMode(CaptionUserPreferences::Manual);
3159 return Exception { SyntaxError };
3168 Ref<TimeRanges> Internals::createTimeRanges(Float32Array& startTimes, Float32Array& endTimes)
3170 ASSERT(startTimes.length() == endTimes.length());
3171 Ref<TimeRanges> ranges = TimeRanges::create();
3173 unsigned count = std::min(startTimes.length(), endTimes.length());
3174 for (unsigned i = 0; i < count; ++i)
3175 ranges->add(startTimes.item(i), endTimes.item(i));
3179 double Internals::closestTimeToTimeRanges(double time, TimeRanges& ranges)
3181 return ranges.nearest(time);
3186 ExceptionOr<Ref<DOMRect>> Internals::selectionBounds()
3188 Document* document = contextDocument();
3189 if (!document || !document->frame())
3190 return Exception { InvalidAccessError };
3192 return DOMRect::create(document->frame()->selection().selectionBounds());
3195 ExceptionOr<bool> Internals::isPluginUnavailabilityIndicatorObscured(Element& element)
3197 if (!is<HTMLPlugInElement>(element))
3198 return Exception { InvalidAccessError };
3200 return downcast<HTMLPlugInElement>(element).isReplacementObscured();
3203 bool Internals::isPluginSnapshotted(Element& element)
3205 return is<HTMLPlugInElement>(element) && downcast<HTMLPlugInElement>(element).displayState() <= HTMLPlugInElement::DisplayingSnapshot;
3208 #if ENABLE(MEDIA_SOURCE)
3210 void Internals::initializeMockMediaSource()
3212 #if USE(AVFOUNDATION)
3213 WebCore::DeprecatedGlobalSettings::setAVFoundationEnabled(false);
3216 WebCore::DeprecatedGlobalSettings::setGStreamerEnabled(false);
3218 MediaPlayerFactorySupport::callRegisterMediaEngine(MockMediaPlayerMediaSource::registerMediaEngine);
3221 Vector<String> Internals::bufferedSamplesForTrackID(SourceBuffer& buffer, const AtomicString& trackID)
3223 return buffer.bufferedSamplesForTrackID(trackID);
3226 Vector<String> Internals::enqueuedSamplesForTrackID(SourceBuffer& buffer, const AtomicString& trackID)
3228 return buffer.enqueuedSamplesForTrackID(trackID);
3231 void Internals::setShouldGenerateTimestamps(SourceBuffer& buffer, bool flag)
3233 buffer.setShouldGenerateTimestamps(flag);
3240 ExceptionOr<void> Internals::beginMediaSessionInterruption(const String& interruptionString)
3242 PlatformMediaSession::InterruptionType interruption = PlatformMediaSession::SystemInterruption;
3244 if (equalLettersIgnoringASCIICase(interruptionString, "system"))
3245 interruption = PlatformMediaSession::SystemInterruption;
3246 else if (equalLettersIgnoringASCIICase(interruptionString, "systemsleep"))
3247 interruption = PlatformMediaSession::SystemSleep;
3248 else if (equalLettersIgnoringASCIICase(interruptionString, "enteringbackground"))
3249 interruption = PlatformMediaSession::EnteringBackground;
3250 else if (equalLettersIgnoringASCIICase(interruptionString, "suspendedunderlock"))
3251 interruption = PlatformMediaSession::SuspendedUnderLock;
3253 return Exception { InvalidAccessError };
3255 PlatformMediaSessionManager::sharedManager().beginInterruption(interruption);
3259 void Internals::endMediaSessionInterruption(const String& flagsString)
3261 PlatformMediaSession::EndInterruptionFlags flags = PlatformMediaSession::NoFlags;
3263 if (equalLettersIgnoringASCIICase(flagsString, "mayresumeplaying"))
3264 flags = PlatformMediaSession::MayResumePlaying;
3266 PlatformMediaSessionManager::sharedManager().endInterruption(flags);
3269 void Internals::applicationWillBecomeInactive()
3271 PlatformMediaSessionManager::sharedManager().applicationWillBecomeInactive();
3274 void Internals::applicationDidBecomeActive()
3276 PlatformMediaSessionManager::sharedManager().applicationDidBecomeActive();
3279 void Internals::applicationWillEnterForeground(bool suspendedUnderLock) const
3281 PlatformMediaSessionManager::sharedManager().applicationWillEnterForeground(suspendedUnderLock);
3284 void Internals::applicationDidEnterBackground(bool suspendedUnderLock) const
3286 PlatformMediaSessionManager::sharedManager().applicationDidEnterBackground(suspendedUnderLock);
3289 static PlatformMediaSession::MediaType mediaTypeFromString(const String& mediaTypeString)
3291 if (equalLettersIgnoringASCIICase(mediaTypeString, "video"))
3292 return PlatformMediaSession::Video;
3293 if (equalLettersIgnoringASCIICase(mediaTypeString, "audio"))
3294 return PlatformMediaSession::Audio;
3295 if (equalLettersIgnoringASCIICase(mediaTypeString, "videoaudio"))
3296 return PlatformMediaSession::VideoAudio;
3297 if (equalLettersIgnoringASCIICase(mediaTypeString, "webaudio"))
3298 return PlatformMediaSession::WebAudio;
3299 if (equalLettersIgnoringASCIICase(mediaTypeString, "mediastreamcapturingaudio"))
3300 return PlatformMediaSession::MediaStreamCapturingAudio;
3302 return PlatformMediaSession::None;
3305 ExceptionOr<void> Internals::setMediaSessionRestrictions(const String& mediaTypeString, StringView restrictionsString)
3307 PlatformMediaSession::MediaType mediaType = mediaTypeFromString(mediaTypeString);
3308 if (mediaType == PlatformMediaSession::None)
3309 return Exception { InvalidAccessError };
3311 PlatformMediaSessionManager::SessionRestrictions restrictions = PlatformMediaSessionManager::sharedManager().restrictions(mediaType);
3312 PlatformMediaSessionManager::sharedManager().removeRestriction(mediaType, restrictions);
3314 restrictions = PlatformMediaSessionManager::NoRestrictions;
3316 for (StringView restrictionString : restrictionsString.split(',')) {
3317 if (equalLettersIgnoringASCIICase(restrictionString, "concurrentplaybacknotpermitted"))
3318 restrictions |= PlatformMediaSessionManager::ConcurrentPlaybackNotPermitted;
3319 if (equalLettersIgnoringASCIICase(restrictionString, "backgroundprocessplaybackrestricted"))
3320 restrictions |= PlatformMediaSessionManager::BackgroundProcessPlaybackRestricted;
3321 if (equalLettersIgnoringASCIICase(restrictionString, "backgroundtabplaybackrestricted"))
3322 restrictions |= PlatformMediaSessionManager::BackgroundTabPlaybackRestricted;
3323 if (equalLettersIgnoringASCIICase(restrictionString, "interruptedplaybacknotpermitted"))
3324 restrictions |= PlatformMediaSessionManager::InterruptedPlaybackNotPermitted;
3325 if (equalLettersIgnoringASCIICase(restrictionString, "inactiveprocessplaybackrestricted"))
3326 restrictions |= PlatformMediaSessionManager::InactiveProcessPlaybackRestricted;
3327 if (equalLettersIgnoringASCIICase(restrictionString, "suspendedunderlockplaybackrestricted"))
3328 restrictions |= PlatformMediaSessionManager::SuspendedUnderLockPlaybackRestricted;
3330 PlatformMediaSessionManager::sharedManager().addRestriction(mediaType, restrictions);
3334 ExceptionOr<String> Internals::mediaSessionRestrictions(const String& mediaTypeString) const
3336 PlatformMediaSession::MediaType mediaType = mediaTypeFromString(mediaTypeString);
3337 if (mediaType == PlatformMediaSession::None)
3338 return Exception { InvalidAccessError };
3340 PlatformMediaSessionManager::SessionRestrictions restrictions = PlatformMediaSessionManager::sharedManager().restrictions(mediaType);
3341 if (restrictions == PlatformMediaSessionManager::NoRestrictions)
3344 StringBuilder builder;
3345 if (restrictions & PlatformMediaSessionManager::ConcurrentPlaybackNotPermitted)
3346 builder.append("concurrentplaybacknotpermitted");
3347 if (restrictions & PlatformMediaSessionManager::BackgroundProcessPlaybackRestricted) {
3348 if (!builder.isEmpty())
3349 builder.append(',');
3350 builder.append("backgroundprocessplaybackrestricted");
3352 if (restrictions & PlatformMediaSessionManager::BackgroundTabPlaybackRestricted) {
3353 if (!builder.isEmpty())
3354 builder.append(',');
3355 builder.append("backgroundtabplaybackrestricted");
3357 if (restrictions & PlatformMediaSessionManager::InterruptedPlaybackNotPermitted) {
3358 if (!builder.isEmpty())
3359 builder.append(',');
3360 builder.append("interruptedplaybacknotpermitted");
3362 return builder.toString();
3365 void Internals::setMediaElementRestrictions(HTMLMediaElement& element, StringView restrictionsString)
3367 MediaElementSession::BehaviorRestrictions restrictions = element.mediaSession().behaviorRestrictions();
3368 element.mediaSession().removeBehaviorRestriction(restrictions);
3370 restrictions = MediaElementSession::NoRestrictions;
3372 for (StringView restrictionString : restrictionsString.split(',')) {
3373 if (equalLettersIgnoringASCIICase(restrictionString, "norestrictions"))
3374 restrictions |= MediaElementSession::NoRestrictions;
3375 if (equalLettersIgnoringASCIICase(restrictionString, "requireusergestureforload"))
3376 restrictions |= MediaElementSession::RequireUserGestureForLoad;
3377 if (equalLettersIgnoringASCIICase(restrictionString, "requireusergestureforvideoratechange"))
3378 restrictions |= MediaElementSession::RequireUserGestureForVideoRateChange;
3379 if (equalLettersIgnoringASCIICase(restrictionString, "requireusergestureforfullscreen"))
3380 restrictions |= MediaElementSession::RequireUserGestureForFullscreen;
3381 if (equalLettersIgnoringASCIICase(restrictionString, "requirepageconsenttoloadmedia"))
3382 restrictions |= MediaElementSession::RequirePageConsentToLoadMedia;
3383 if (equalLettersIgnoringASCIICase(restrictionString, "requirepageconsenttoresumemedia"))
3384 restrictions |= MediaElementSession::RequirePageConsentToResumeMedia;
3385 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
3386 if (equalLettersIgnoringASCIICase(restrictionString, "requireusergesturetoshowplaybacktargetpicker"))
3387 restrictions |= MediaElementSession::RequireUserGestureToShowPlaybackTargetPicker;
3388 if (equalLettersIgnoringASCIICase(restrictionString, "wirelessvideoplaybackdisabled"))
3389 restrictions |= MediaElementSession::WirelessVideoPlaybackDisabled;
3391 if (equalLettersIgnoringASCIICase(restrictionString, "requireusergestureforaudioratechange"))
3392 restrictions |= MediaElementSession::RequireUserGestureForAudioRateChange;
3393 if (equalLettersIgnoringASCIICase(restrictionString, "metadatapreloadingnotpermitted"))
3394 restrictions |= MediaElementSession::MetadataPreloadingNotPermitted;
3395 if (equalLettersIgnoringASCIICase(restrictionString, "autopreloadingnotpermitted"))
3396 restrictions |= MediaElementSession::AutoPreloadingNotPermitted;
3397 if (equalLettersIgnoringASCIICase(restrictionString, "invisibleautoplaynotpermitted"))
3398 restrictions |= MediaElementSession::InvisibleAutoplayNotPermitted;
3399 if (equalLettersIgnoringASCIICase(restrictionString, "overrideusergesturerequirementformaincontent"))
3400 restrictions |= MediaElementSession::OverrideUserGestureRequirementForMainContent;
3402 element.mediaSession().addBehaviorRestriction(restrictions);
3405 ExceptionOr<void> Internals::postRemoteControlCommand(const String& commandString, float argument)
3407 PlatformMediaSession::RemoteControlCommandType command;
3408 PlatformMediaSession::RemoteCommandArgument parameter { argument };
3410 if (equalLettersIgnoringASCIICase(commandString, "play"))
3411 command = PlatformMediaSession::PlayCommand;
3412 else if (equalLettersIgnoringASCIICase(commandString, "pause"))
3413 command = PlatformMediaSession::PauseCommand;
3414 else if (equalLettersIgnoringASCIICase(commandString, "stop"))
3415 command = PlatformMediaSession::StopCommand;
3416 else if (equalLettersIgnoringASCIICase(commandString, "toggleplaypause"))
3417 command = PlatformMediaSession::TogglePlayPauseCommand;
3418 else if (equalLettersIgnoringASCIICase(commandString, "beginseekingbackward"))
3419 command = PlatformMediaSession::BeginSeekingBackwardCommand;
3420 else if (equalLettersIgnoringASCIICase(commandString, "endseekingbackward"))
3421 command = PlatformMediaSession::EndSeekingBackwardCommand;
3422 else if (equalLettersIgnoringASCIICase(commandString, "beginseekingforward"))
3423 command = PlatformMediaSession::BeginSeekingForwardCommand;
3424 else if (equalLettersIgnoringASCIICase(commandString, "endseekingforward"))
3425 command = PlatformMediaSession::EndSeekingForwardCommand;
3426 else if (equalLettersIgnoringASCIICase(commandString, "seektoplaybackposition"))
3427 command = PlatformMediaSession::SeekToPlaybackPositionCommand;
3429 return Exception { InvalidAccessError };
3431 PlatformMediaSessionManager::sharedManager().didReceiveRemoteControlCommand(command, ¶meter);
3435 bool Internals::elementIsBlockingDisplaySleep(HTMLMediaElement& element) const
3437 return element.isDisablingSleep();
3440 #endif // ENABLE(VIDEO)
3442 #if ENABLE(MEDIA_SESSION)
3444 void Internals::sendMediaSessionStartOfInterruptionNotification(MediaSessionInterruptingCategory category)
3446 MediaSessionManager::singleton().didReceiveStartOfInterruptionNotification(category);
3449 void Internals::sendMediaSessionEndOfInterruptionNotification(MediaSessionInterruptingCategory category)
3451 MediaSessionManager::singleton().didReceiveEndOfInterruptionNotification(category);
3454 String Internals::mediaSessionCurrentState(MediaSession* session) const
3456 switch (session->currentState()) {
3457 case MediaSession::State::Active:
3459 case MediaSession::State::Interrupted:
3460 return "interrupted";
3461 case MediaSession::State::Idle:
3466 double Internals::mediaElementPlayerVolume(HTMLMediaElement* element) const
3468 ASSERT_ARG(element, element);
3469 return element->playerVolume();
3472 void Internals::sendMediaControlEvent(MediaControlEvent event)
3474 // FIXME: No good reason to use a single function with an argument instead of three functions.
3476 case MediControlEvent::PlayPause:
3477 MediaSessionManager::singleton().togglePlayback();
3479 case MediControlEvent::NextTrack:
3480 MediaSessionManager::singleton().skipToNextTrack();
3482 case MediControlEvent::PreviousTrack:
3483 MediaSessionManager::singleton().skipToPreviousTrack();
3488 #endif // ENABLE(MEDIA_SESSION)
3490 #if ENABLE(WEB_AUDIO)
3492 void Internals::setAudioContextRestrictions(AudioContext& context, StringView restrictionsString)
3494 AudioContext::BehaviorRestrictions restrictions = context.behaviorRestrictions();
3495 context.removeBehaviorRestriction(restrictions);
3497 restrictions = AudioContext::NoRestrictions;
3499 for (StringView restrictionString : restrictionsString.split(',')) {
3500 if (equalLettersIgnoringASCIICase(restrictionString, "norestrictions"))
3501 restrictions |= AudioContext::NoRestrictions;
3502 if (equalLettersIgnoringASCIICase(restrictionString, "requireusergestureforaudiostart"))
3503 restrictions |= AudioContext::RequireUserGestureForAudioStartRestriction;
3504 if (equalLettersIgnoringASCIICase(restrictionString, "requirepageconsentforaudiostart"))
3505 restrictions |= AudioContext::RequirePageConsentForAudioStartRestriction;
3507 context.addBehaviorRestriction(restrictions);
3512 void Internals::simulateSystemSleep() const
3515 PlatformMediaSessionManager::sharedManager().systemWillSleep();
3519 void Internals::simulateSystemWake() const
3522 PlatformMediaSessionManager::sharedManager().systemDidWake();
3526 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
3528 void Internals::setMockMediaPlaybackTargetPickerEnabled(bool enabled)
3530 Page* page = contextDocument()->frame()->page();
3533 page->setMockMediaPlaybackTargetPickerEnabled(enabled);
3536 ExceptionOr<void> Internals::setMockMediaPlaybackTargetPickerState(const String& deviceName, const String& deviceState)
3538 Page* page = contextDocument()->frame()->page();
3541 MediaPlaybackTargetContext::State state = MediaPlaybackTargetContext::Unknown;
3543 if (equalLettersIgnoringASCIICase(deviceState, "deviceavailable"))
3544 state = MediaPlaybackTargetContext::OutputDeviceAvailable;
3545 else if (equalLettersIgnoringASCIICase(deviceState, "deviceunavailable"))
3546 state = MediaPlaybackTargetContext::OutputDeviceUnavailable;
3547 else if (equalLettersIgnoringASCIICase(deviceState, "unknown"))
3548 state = MediaPlaybackTargetContext::Unknown;
3550 return Exception { InvalidAccessError };
3552 page->setMockMediaPlaybackTargetPickerState(deviceName, state);
3558 ExceptionOr<Ref<MockPageOverlay>> Internals::installMockPageOverlay(PageOverlayType type)
3560 Document* document = contextDocument();
3561 if (!document || !document->frame())
3562 return Exception { InvalidAccessError };
3564 return MockPageOverlayClient::singleton().installOverlay(document->frame()->mainFrame(), type == PageOverlayType::View ? PageOverlay::OverlayType::View : PageOverlay::OverlayType::Document);
3567 ExceptionOr<String> Internals::pageOverlayLayerTreeAsText(unsigned short flags) const
3569 Document* document = contextDocument();
3570 if (!document || !document->frame())
3571 return Exception { InvalidAccessError };
3573 document->updateLayoutIgnorePendingStylesheets();
3575 return MockPageOverlayClient::singleton().layerTreeAsText(document->frame()->mainFrame(), toLayerTreeFlags(flags));
3578 void Internals::setPageMuted(StringView statesString)
3580 Document* document = contextDocument();
3584 WebCore::MediaProducer::MutedStateFlags state = MediaProducer::NoneMuted;
3585 for (StringView stateString : statesString.split(',')) {
3586 if (equalLettersIgnoringASCIICase(stateString, "audio"))
3587 state |= MediaProducer::AudioIsMuted;
3588 if (equalLettersIgnoringASCIICase(stateString, "capturedevices"))
3589 state |= MediaProducer::CaptureDevicesAreMuted;
3592 if (Page* page = document->page())
3593 page->setMuted(state);
3596 String Internals::pageMediaState()
3598 Document* document = contextDocument();
3599 if (!document || !document->page())
3600 return emptyString();
3602 WebCore::MediaProducer::MediaStateFlags state = document->page()->mediaState();
3603 StringBuilder string;
3604 if (state & MediaProducer::IsPlayingAudio)
3605 string.append("IsPlayingAudio,");
3606 if (state & MediaProducer::IsPlayingVideo)
3607 string.append("IsPlayingVideo,");
3608 if (state & MediaProducer::IsPlayingToExternalDevice)
3609 string.append("IsPlayingToExternalDevice,");
3610 if (state & MediaProducer::RequiresPlaybackTargetMonitoring)
3611 string.append("RequiresPlaybackTargetMonitoring,");
3612 if (state & MediaProducer::ExternalDeviceAutoPlayCandidate)
3613 string.append("ExternalDeviceAutoPlayCandidate,");
3614 if (state & MediaProducer::DidPlayToEnd)
3615 string.append("DidPlayToEnd,");
3616 if (state & MediaProducer::IsSourceElementPlaying)
3617 string.append("IsSourceElementPlaying,");
3619 if (state & MediaProducer::IsNextTrackControlEnabled)
3620 string.append("IsNextTrackControlEnabled,");
3621 if (state & MediaProducer::IsPreviousTrackControlEnabled)
3622 string.append("IsPreviousTrackControlEnabled,");
3624 if (state & MediaProducer::HasPlaybackTargetAvailabilityListener)
3625 string.append("HasPlaybackTargetAvailabilityListener,");
3626 if (state & MediaProducer::HasAudioOrVideo)
3627 string.append("HasAudioOrVideo,");
3628 if (state & MediaProducer::HasActiveAudioCaptureDevice)
3629 string.append("HasActiveAudioCaptureDevice,");
3630 if (state & MediaProducer::HasActiveVideoCaptureDevice)
3631 string.append("HasActiveVideoCaptureDevice,");
3632 if (state & MediaProducer::HasMutedAudioCaptureDevice)
3633 string.append("HasMutedAudioCaptureDevice,");
3634 if (state & MediaProducer::HasMutedVideoCaptureDevice)
3635 string.append("HasMutedVideoCaptureDevice,");
3636 if (state & MediaProducer::HasUserInteractedWithMediaElement)
3637 string.append("HasUserInteractedWithMediaElement,");
3639 if (string.isEmpty())
3640 string.append("IsNotPlaying");
3642 string.resize(string.length() - 1);
3644 return string.toString();
3647 void Internals::setPageDefersLoading(bool defersLoading)
3649 Document* document = contextDocument();
3652 if (Page* page = document->page())
3653 page->setDefersLoading(defersLoading);
3656 RefPtr<File> Internals::createFile(const String& path)
3658 Document* document = contextDocument();
3662 URL url = document->completeURL(path);
3663 if (!url.isLocalFile())
3666 return File::create(url.fileSystemPath());
3669 void Internals::queueMicroTask(int testNumber)
3671 Document* document = contextDocument();
3675 auto microtask = std::make_unique<ActiveDOMCallbackMicrotask>(MicrotaskQueue::mainThreadQueue(), *document, [document, testNumber]() {
3676 document->addConsoleMessage(MessageSource::JS, MessageLevel::Debug, makeString("MicroTask #", String::number(testNumber), " has run."));
3679 MicrotaskQueue::mainThreadQueue().append(WTFMove(microtask));
3682 #if ENABLE(CONTENT_FILTERING)
3684 MockContentFilterSettings& Internals::mockContentFilterSettings()
3686 return MockContentFilterSettings::singleton();
3691 #if ENABLE(CSS_SCROLL_SNAP)
3693 static void appendOffsets(StringBuilder& builder, const Vector<LayoutUnit>& snapOffsets)
3695 bool justStarting = true;
3697 builder.appendLiteral("{ ");
3698 for (auto& coordinate : snapOffsets) {