2 * Copyright (C) 2012 Google Inc. All rights reserved.
3 * Copyright (C) 2013-2015 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 "AnimationController.h"
33 #include "ApplicationCacheStorage.h"
35 #include "BackForwardController.h"
36 #include "BitmapImage.h"
37 #include "CachedImage.h"
38 #include "CachedResourceLoader.h"
40 #include "ChromeClient.h"
41 #include "ClientRect.h"
42 #include "ClientRectList.h"
43 #include "ComposedTreeIterator.h"
46 #include "DOMStringList.h"
47 #include "DOMWindow.h"
48 #include "DisplayList.h"
50 #include "DocumentMarker.h"
51 #include "DocumentMarkerController.h"
54 #include "EventHandler.h"
55 #include "ExceptionCode.h"
56 #include "ExtensionStyleSheets.h"
58 #include "FontCache.h"
59 #include "FormController.h"
60 #include "FrameLoader.h"
61 #include "FrameView.h"
62 #include "GCObservation.h"
63 #include "HTMLCanvasElement.h"
64 #include "HTMLIFrameElement.h"
65 #include "HTMLImageElement.h"
66 #include "HTMLInputElement.h"
67 #include "HTMLLinkElement.h"
68 #include "HTMLNames.h"
69 #include "HTMLPlugInElement.h"
70 #include "HTMLPreloadScanner.h"
71 #include "HTMLSelectElement.h"
72 #include "HTMLTextAreaElement.h"
73 #include "HTMLVideoElement.h"
74 #include "HistoryController.h"
75 #include "HistoryItem.h"
76 #include "HitTestResult.h"
77 #include "IconController.h"
78 #include "InspectorClient.h"
79 #include "InspectorController.h"
80 #include "InspectorFrontendClientLocal.h"
81 #include "InspectorOverlay.h"
82 #include "InstrumentingAgents.h"
84 #include "InternalSettings.h"
86 #include "MainFrame.h"
87 #include "MallocStatistics.h"
88 #include "MediaPlayer.h"
89 #include "MediaProducer.h"
90 #include "MemoryCache.h"
91 #include "MemoryInfo.h"
92 #include "MemoryPressureHandler.h"
93 #include "MockPageOverlay.h"
94 #include "MockPageOverlayClient.h"
96 #include "PageCache.h"
97 #include "PageOverlay.h"
98 #include "PathUtilities.h"
99 #include "PlatformMediaSessionManager.h"
100 #include "PrintContext.h"
101 #include "PseudoElement.h"
103 #include "RenderEmbeddedObject.h"
104 #include "RenderLayerBacking.h"
105 #include "RenderLayerCompositor.h"
106 #include "RenderMenuList.h"
107 #include "RenderTreeAsText.h"
108 #include "RenderView.h"
109 #include "RenderedDocumentMarker.h"
110 #include "ResourceLoadObserver.h"
111 #include "RuntimeEnabledFeatures.h"
112 #include "SVGPathStringBuilder.h"
113 #include "SchemeRegistry.h"
114 #include "ScriptedAnimationController.h"
115 #include "ScrollingCoordinator.h"
116 #include "SerializedScriptValue.h"
117 #include "Settings.h"
118 #include "ShadowRoot.h"
119 #include "SourceBuffer.h"
120 #include "SpellChecker.h"
121 #include "StaticNodeList.h"
122 #include "StyleScope.h"
123 #include "StyleSheetContents.h"
124 #include "TextIterator.h"
125 #include "TreeScope.h"
126 #include "TypeConversions.h"
127 #include "UserGestureIndicator.h"
128 #include "UserMediaController.h"
129 #include "ViewportArguments.h"
130 #include "WebCoreJSClientData.h"
131 #include "WorkerThread.h"
132 #include "XMLHttpRequest.h"
133 #include <bytecode/CodeBlock.h>
134 #include <inspector/InspectorAgentBase.h>
135 #include <inspector/InspectorFrontendChannel.h>
136 #include <inspector/InspectorValues.h>
137 #include <runtime/JSCInlines.h>
138 #include <runtime/JSCJSValue.h>
139 #include <wtf/text/CString.h>
140 #include <wtf/text/StringBuffer.h>
142 #if ENABLE(INPUT_TYPE_COLOR)
143 #include "ColorChooser.h"
146 #if ENABLE(BATTERY_STATUS)
147 #include "BatteryController.h"
150 #if ENABLE(PROXIMITY_EVENTS)
151 #include "DeviceProximityController.h"
154 #if ENABLE(MOUSE_CURSOR_SCALE)
155 #include <wtf/dtoa.h>
158 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
163 #if ENABLE(VIDEO_TRACK)
164 #include "CaptionUserPreferences.h"
165 #include "PageGroup.h"
169 #include "HTMLMediaElement.h"
170 #include "TimeRanges.h"
173 #if ENABLE(SPEECH_SYNTHESIS)
174 #include "DOMWindowSpeechSynthesis.h"
175 #include "PlatformSpeechSynthesizerMock.h"
176 #include "SpeechSynthesis.h"
179 #if ENABLE(VIBRATION)
180 #include "Vibration.h"
183 #if ENABLE(MEDIA_STREAM)
184 #include "MockRealtimeMediaSourceCenter.h"
188 #include "MockMediaEndpoint.h"
189 #include "RTCPeerConnection.h"
190 #include "RTCPeerConnectionHandlerMock.h"
193 #if ENABLE(MEDIA_SOURCE)
194 #include "MockMediaPlayerMediaSource.h"
198 #include "DictionaryLookup.h"
201 #if ENABLE(CONTENT_FILTERING)
202 #include "MockContentFilterSettings.h"
205 #if ENABLE(WEB_AUDIO)
206 #include "AudioContext.h"
209 #if ENABLE(MEDIA_SESSION)
210 #include "MediaSession.h"
211 #include "MediaSessionManager.h"
214 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
215 #include "MediaPlaybackTargetContext.h"
220 using JSC::CodeBlock;
221 using JSC::FunctionExecutable;
222 using JSC::Identifier;
223 using JSC::JSFunction;
224 using JSC::JSGlobalObject;
227 using JSC::MarkedArgumentBuffer;
228 using JSC::PropertySlot;
229 using JSC::ScriptExecutable;
230 using JSC::StackVisitor;
232 using namespace Inspector;
236 using namespace HTMLNames;
238 class InspectorStubFrontend final : public InspectorFrontendClientLocal, public FrontendChannel {
240 InspectorStubFrontend(Page& inspectedPage, RefPtr<DOMWindow>&& frontendWindow);
241 virtual ~InspectorStubFrontend();
244 void attachWindow(DockSide) final { }
245 void detachWindow() final { }
246 void closeWindow() final;
247 void bringToFront() final { }
248 String localizedStringsURL() final { return String(); }
249 void inspectedURLChanged(const String&) final { }
250 void setAttachedWindowHeight(unsigned) final { }
251 void setAttachedWindowWidth(unsigned) final { }
253 bool sendMessageToFrontend(const String& message) final;
254 ConnectionType connectionType() const final { return ConnectionType::Local; }
256 Page* frontendPage() const
258 if (!m_frontendWindow || !m_frontendWindow->document())
261 return m_frontendWindow->document()->page();
264 RefPtr<DOMWindow> m_frontendWindow;
265 InspectorController& m_frontendController;
268 InspectorStubFrontend::InspectorStubFrontend(Page& inspectedPage, RefPtr<DOMWindow>&& frontendWindow)
269 : InspectorFrontendClientLocal(&inspectedPage.inspectorController(), frontendWindow->document()->page(), std::make_unique<InspectorFrontendClientLocal::Settings>())
270 , m_frontendWindow(frontendWindow.copyRef())
271 , m_frontendController(frontendPage()->inspectorController())
273 ASSERT_ARG(frontendWindow, frontendWindow);
275 m_frontendController.setInspectorFrontendClient(this);
276 inspectedPage.inspectorController().connectFrontend(this);
279 InspectorStubFrontend::~InspectorStubFrontend()
284 void InspectorStubFrontend::closeWindow()
286 if (!m_frontendWindow)
289 m_frontendController.setInspectorFrontendClient(nullptr);
290 inspectedPage()->inspectorController().disconnectFrontend(this);
292 m_frontendWindow->close();
293 m_frontendWindow = nullptr;
296 bool InspectorStubFrontend::sendMessageToFrontend(const String& message)
298 ASSERT_ARG(message, !message.isEmpty());
300 return InspectorClient::doDispatchMessageOnFrontendPage(frontendPage(), message);
303 static bool markerTypeFrom(const String& markerType, DocumentMarker::MarkerType& result)
305 if (equalLettersIgnoringASCIICase(markerType, "spelling"))
306 result = DocumentMarker::Spelling;
307 else if (equalLettersIgnoringASCIICase(markerType, "grammar"))
308 result = DocumentMarker::Grammar;
309 else if (equalLettersIgnoringASCIICase(markerType, "textmatch"))
310 result = DocumentMarker::TextMatch;
311 else if (equalLettersIgnoringASCIICase(markerType, "replacement"))
312 result = DocumentMarker::Replacement;
313 else if (equalLettersIgnoringASCIICase(markerType, "correctionindicator"))
314 result = DocumentMarker::CorrectionIndicator;
315 else if (equalLettersIgnoringASCIICase(markerType, "rejectedcorrection"))
316 result = DocumentMarker::RejectedCorrection;
317 else if (equalLettersIgnoringASCIICase(markerType, "autocorrected"))
318 result = DocumentMarker::Autocorrected;
319 else if (equalLettersIgnoringASCIICase(markerType, "spellcheckingexemption"))
320 result = DocumentMarker::SpellCheckingExemption;
321 else if (equalLettersIgnoringASCIICase(markerType, "deletedautocorrection"))
322 result = DocumentMarker::DeletedAutocorrection;
323 else if (equalLettersIgnoringASCIICase(markerType, "dictationalternatives"))
324 result = DocumentMarker::DictationAlternatives;
325 #if ENABLE(TELEPHONE_NUMBER_DETECTION)
326 else if (equalLettersIgnoringASCIICase(markerType, "telephonenumber"))
327 result = DocumentMarker::TelephoneNumber;
335 static bool markerTypesFrom(const String& markerType, DocumentMarker::MarkerTypes& result)
337 DocumentMarker::MarkerType singularResult;
339 if (markerType.isEmpty() || equalLettersIgnoringASCIICase(markerType, "all"))
340 result = DocumentMarker::AllMarkers();
341 else if (markerTypeFrom(markerType, singularResult))
342 result = singularResult;
349 const char* Internals::internalsId = "internals";
351 Ref<Internals> Internals::create(Document& document)
353 return adoptRef(*new Internals(document));
356 Internals::~Internals()
360 void Internals::resetToConsistentState(Page& page)
362 page.setPageScaleFactor(1, IntPoint(0, 0));
363 page.setPagination(Pagination());
364 page.setPaginationLineGridEnabled(false);
366 page.setDefersLoading(false);
368 page.mainFrame().setTextZoomFactor(1.0f);
370 FrameView* mainFrameView = page.mainFrame().view();
372 mainFrameView->setHeaderHeight(0);
373 mainFrameView->setFooterHeight(0);
374 page.setTopContentInset(0);
375 mainFrameView->setUseFixedLayout(false);
376 mainFrameView->setFixedLayoutSize(IntSize());
377 #if USE(COORDINATED_GRAPHICS)
378 mainFrameView->setFixedVisibleContentRect(IntRect());
382 WebCore::overrideUserPreferredLanguages(Vector<String>());
383 WebCore::Settings::setUsesOverlayScrollbars(false);
384 WebCore::Settings::setUsesMockScrollAnimator(false);
385 #if ENABLE(VIDEO_TRACK)
386 page.group().captionPreferences().setTestingMode(true);
387 page.group().captionPreferences().setCaptionsStyleSheetOverride(emptyString());
388 page.group().captionPreferences().setTestingMode(false);
390 if (!page.mainFrame().editor().isContinuousSpellCheckingEnabled())
391 page.mainFrame().editor().toggleContinuousSpellChecking();
392 if (page.mainFrame().editor().isOverwriteModeEnabled())
393 page.mainFrame().editor().toggleOverwriteModeEnabled();
394 page.mainFrame().loader().clearTestingOverrides();
395 page.applicationCacheStorage().setDefaultOriginQuota(ApplicationCacheStorage::noQuota());
397 PlatformMediaSessionManager::sharedManager().resetRestrictions();
398 PlatformMediaSessionManager::sharedManager().setWillIgnoreSystemInterruptions(true);
400 #if HAVE(ACCESSIBILITY)
401 AXObjectCache::setEnhancedUserInterfaceAccessibility(false);
402 AXObjectCache::disableAccessibility();
405 MockPageOverlayClient::singleton().uninstallAllOverlays();
407 #if ENABLE(CONTENT_FILTERING)
408 MockContentFilterSettings::reset();
411 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
412 page.setMockMediaPlaybackTargetPickerEnabled(true);
413 page.setMockMediaPlaybackTargetPickerState(emptyString(), MediaPlaybackTargetContext::Unknown);
416 page.setShowAllPlugins(false);
419 Internals::Internals(Document& document)
420 : ContextDestructionObserver(&document)
422 #if ENABLE(VIDEO_TRACK)
424 document.page()->group().captionPreferences().setTestingMode(true);
427 #if ENABLE(MEDIA_STREAM)
428 setMockMediaCaptureDevicesEnabled(true);
432 enableMockMediaEndpoint();
433 enableMockRTCPeerConnectionHandler();
436 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
438 document.page()->setMockMediaPlaybackTargetPickerEnabled(true);
440 RuntimeEnabledFeatures::sharedFeatures().reset();
442 if (contextDocument() && contextDocument()->frame()) {
443 setAutomaticSpellingCorrectionEnabled(true);
444 setAutomaticQuoteSubstitutionEnabled(false);
445 setAutomaticDashSubstitutionEnabled(false);
446 setAutomaticLinkDetectionEnabled(false);
447 setAutomaticTextReplacementEnabled(true);
451 Document* Internals::contextDocument() const
453 return downcast<Document>(scriptExecutionContext());
456 Frame* Internals::frame() const
458 if (!contextDocument())
460 return contextDocument()->frame();
463 InternalSettings* Internals::settings() const
465 Document* document = contextDocument();
468 Page* page = document->page();
471 return InternalSettings::from(page);
474 unsigned Internals::workerThreadCount() const
476 return WorkerThread::workerThreadCount();
479 String Internals::address(Node& node)
481 return String::format("%p", &node);
484 bool Internals::nodeNeedsStyleRecalc(Node& node)
486 return node.needsStyleRecalc();
489 static String styleValidityToToString(Style::Validity validity)
492 case Style::Validity::Valid:
493 return "NoStyleChange";
494 case Style::Validity::ElementInvalid:
495 return "InlineStyleChange";
496 case Style::Validity::SubtreeInvalid:
497 return "FullStyleChange";
498 case Style::Validity::SubtreeAndRenderersInvalid:
499 return "ReconstructRenderTree";
501 ASSERT_NOT_REACHED();
505 String Internals::styleChangeType(Node& node)
507 node.document().styleScope().flushPendingUpdate();
509 return styleValidityToToString(node.styleValidity());
512 String Internals::description(JSC::JSValue value)
514 return toString(value);
517 bool Internals::isPreloaded(const String& url)
519 Document* document = contextDocument();
520 return document->cachedResourceLoader().isPreloaded(url);
523 bool Internals::isLoadingFromMemoryCache(const String& url)
525 if (!contextDocument() || !contextDocument()->page())
528 ResourceRequest request(contextDocument()->completeURL(url));
529 #if ENABLE(CACHE_PARTITIONING)
530 request.setDomainForCachePartition(contextDocument()->topOrigin()->domainForCachePartition());
532 CachedResource* resource = MemoryCache::singleton().resourceForRequest(request, contextDocument()->page()->sessionID());
533 return resource && resource->status() == CachedResource::Cached;
536 String Internals::xhrResponseSource(XMLHttpRequest& request)
538 if (request.resourceResponse().isNull())
539 return "Null response";
540 switch (request.resourceResponse().source()) {
541 case ResourceResponse::Source::Unknown:
543 case ResourceResponse::Source::Network:
545 case ResourceResponse::Source::DiskCache:
547 case ResourceResponse::Source::DiskCacheAfterValidation:
548 return "Disk cache after validation";
549 case ResourceResponse::Source::MemoryCache:
550 return "Memory cache";
551 case ResourceResponse::Source::MemoryCacheAfterValidation:
552 return "Memory cache after validation";
554 ASSERT_NOT_REACHED();
558 bool Internals::isSharingStyleSheetContents(HTMLLinkElement& a, HTMLLinkElement& b)
560 if (!a.sheet() || !b.sheet())
562 return &a.sheet()->contents() == &b.sheet()->contents();
565 bool Internals::isStyleSheetLoadingSubresources(HTMLLinkElement& link)
567 return link.sheet() && link.sheet()->contents().isLoadingSubresources();
570 static ResourceRequestCachePolicy toResourceRequestCachePolicy(Internals::CachePolicy policy)
573 case Internals::CachePolicy::UseProtocolCachePolicy:
574 return UseProtocolCachePolicy;
575 case Internals::CachePolicy::ReloadIgnoringCacheData:
576 return ReloadIgnoringCacheData;
577 case Internals::CachePolicy::ReturnCacheDataElseLoad:
578 return ReturnCacheDataElseLoad;
579 case Internals::CachePolicy::ReturnCacheDataDontLoad:
580 return ReturnCacheDataDontLoad;
582 ASSERT_NOT_REACHED();
583 return UseProtocolCachePolicy;
586 void Internals::setOverrideCachePolicy(CachePolicy policy)
588 frame()->loader().setOverrideCachePolicyForTesting(toResourceRequestCachePolicy(policy));
591 ExceptionOr<void> Internals::setCanShowModalDialogOverride(bool allow)
593 if (!contextDocument() || !contextDocument()->domWindow())
594 return Exception { INVALID_ACCESS_ERR };
596 contextDocument()->domWindow()->setCanShowModalDialogOverride(allow);
600 static ResourceLoadPriority toResourceLoadPriority(Internals::ResourceLoadPriority priority)
603 case Internals::ResourceLoadPriority::ResourceLoadPriorityVeryLow:
604 return ResourceLoadPriority::VeryLow;
605 case Internals::ResourceLoadPriority::ResourceLoadPriorityLow:
606 return ResourceLoadPriority::Low;
607 case Internals::ResourceLoadPriority::ResourceLoadPriorityMedium:
608 return ResourceLoadPriority::Medium;
609 case Internals::ResourceLoadPriority::ResourceLoadPriorityHigh:
610 return ResourceLoadPriority::High;
611 case Internals::ResourceLoadPriority::ResourceLoadPriorityVeryHigh:
612 return ResourceLoadPriority::VeryHigh;
614 ASSERT_NOT_REACHED();
615 return ResourceLoadPriority::Low;
618 void Internals::setOverrideResourceLoadPriority(ResourceLoadPriority priority)
620 frame()->loader().setOverrideResourceLoadPriorityForTesting(toResourceLoadPriority(priority));
623 void Internals::setStrictRawResourceValidationPolicyDisabled(bool disabled)
625 frame()->loader().setStrictRawResourceValidationPolicyDisabledForTesting(disabled);
628 void Internals::clearMemoryCache()
630 MemoryCache::singleton().evictResources();
633 void Internals::pruneMemoryCacheToSize(unsigned size)
635 MemoryCache::singleton().pruneDeadResourcesToSize(size);
636 MemoryCache::singleton().pruneLiveResourcesToSize(size, true);
639 unsigned Internals::memoryCacheSize() const
641 return MemoryCache::singleton().size();
644 unsigned Internals::imageFrameIndex(HTMLImageElement& element)
646 auto* cachedImage = element.cachedImage();
650 auto* image = cachedImage->image();
651 return is<BitmapImage>(image) ? downcast<BitmapImage>(*image).currentFrame() : 0;
654 void Internals::clearPageCache()
656 PageCache::singleton().pruneToSizeNow(0, PruningReason::None);
659 unsigned Internals::pageCacheSize() const
661 return PageCache::singleton().pageCount();
664 Node* Internals::treeScopeRootNode(Node& node)
666 return &node.treeScope().rootNode();
669 Node* Internals::parentTreeScope(Node& node)
671 const TreeScope* parentTreeScope = node.treeScope().parentTreeScope();
672 return parentTreeScope ? &parentTreeScope->rootNode() : nullptr;
675 ExceptionOr<unsigned> Internals::lastSpatialNavigationCandidateCount() const
677 if (!contextDocument() || !contextDocument()->page())
678 return Exception { INVALID_ACCESS_ERR };
680 return contextDocument()->page()->lastSpatialNavigationCandidateCount();
683 unsigned Internals::numberOfActiveAnimations() const
685 return frame()->animation().numberOfActiveAnimations(frame()->document());
688 ExceptionOr<bool> Internals::animationsAreSuspended() const
690 Document* document = contextDocument();
691 if (!document || !document->frame())
692 return Exception { INVALID_ACCESS_ERR };
694 return document->frame()->animation().isSuspended();
697 ExceptionOr<void> Internals::suspendAnimations() const
699 Document* document = contextDocument();
700 if (!document || !document->frame())
701 return Exception { INVALID_ACCESS_ERR };
703 document->frame()->animation().suspendAnimations();
707 ExceptionOr<void> Internals::resumeAnimations() const
709 Document* document = contextDocument();
710 if (!document || !document->frame())
711 return Exception { INVALID_ACCESS_ERR };
713 document->frame()->animation().resumeAnimations();
717 ExceptionOr<bool> Internals::pauseAnimationAtTimeOnElement(const String& animationName, double pauseTime, Element& element)
720 return Exception { INVALID_ACCESS_ERR };
721 return frame()->animation().pauseAnimationAtTime(element.renderer(), AtomicString(animationName), pauseTime);
724 ExceptionOr<bool> Internals::pauseAnimationAtTimeOnPseudoElement(const String& animationName, double pauseTime, Element& element, const String& pseudoId)
727 return Exception { INVALID_ACCESS_ERR };
729 if (pseudoId != "before" && pseudoId != "after")
730 return Exception { INVALID_ACCESS_ERR };
732 PseudoElement* pseudoElement = pseudoId == "before" ? element.beforePseudoElement() : element.afterPseudoElement();
734 return Exception { INVALID_ACCESS_ERR };
736 return frame()->animation().pauseAnimationAtTime(pseudoElement->renderer(), AtomicString(animationName), pauseTime);
739 ExceptionOr<bool> Internals::pauseTransitionAtTimeOnElement(const String& propertyName, double pauseTime, Element& element)
742 return Exception { INVALID_ACCESS_ERR };
743 return frame()->animation().pauseTransitionAtTime(element.renderer(), propertyName, pauseTime);
746 ExceptionOr<bool> Internals::pauseTransitionAtTimeOnPseudoElement(const String& property, double pauseTime, Element& element, const String& pseudoId)
749 return Exception { INVALID_ACCESS_ERR };
751 if (pseudoId != "before" && pseudoId != "after")
752 return Exception { INVALID_ACCESS_ERR };
754 PseudoElement* pseudoElement = pseudoId == "before" ? element.beforePseudoElement() : element.afterPseudoElement();
756 return Exception { INVALID_ACCESS_ERR };
758 return frame()->animation().pauseTransitionAtTime(pseudoElement->renderer(), property, pauseTime);
761 ExceptionOr<String> Internals::elementRenderTreeAsText(Element& element)
763 element.document().updateStyleIfNeeded();
765 String representation = externalRepresentation(&element);
766 if (representation.isEmpty())
767 return Exception { INVALID_ACCESS_ERR };
769 return WTFMove(representation);
772 bool Internals::hasPausedImageAnimations(Element& element)
774 return element.renderer() && element.renderer()->hasPausedImageAnimations();
777 RefPtr<CSSComputedStyleDeclaration> Internals::computedStyleIncludingVisitedInfo(Element& element) const
779 bool allowVisitedStyle = true;
780 return CSSComputedStyleDeclaration::create(element, allowVisitedStyle);
783 ExceptionOr<Node*> Internals::ensureShadowRoot(Element& host)
785 if (ShadowRoot* shadowRoot = host.shadowRoot())
788 ExceptionCode ec = 0;
789 auto result = host.createShadowRoot(ec);
791 return Exception { ec };
795 Node* Internals::ensureUserAgentShadowRoot(Element& host)
797 return &host.ensureUserAgentShadowRoot();
800 ExceptionOr<Node*> Internals::createShadowRoot(Element& host)
802 ExceptionCode ec = 0;
803 auto result = host.createShadowRoot(ec);
805 return Exception { ec };
809 Node* Internals::shadowRoot(Element& host)
811 return host.shadowRoot();
814 ExceptionOr<String> Internals::shadowRootType(const Node& root) const
816 if (!is<ShadowRoot>(root))
817 return Exception { INVALID_ACCESS_ERR };
819 switch (downcast<ShadowRoot>(root).mode()) {
820 case ShadowRoot::Mode::UserAgent:
821 return String("UserAgentShadowRoot");
822 case ShadowRoot::Mode::Closed:
823 return String("ClosedShadowRoot");
824 case ShadowRoot::Mode::Open:
825 return String("OpenShadowRoot");
827 ASSERT_NOT_REACHED();
828 return String("Unknown");
832 String Internals::shadowPseudoId(Element& element)
834 return element.shadowPseudoId().string();
837 void Internals::setShadowPseudoId(Element& element, const String& id)
839 return element.setPseudo(id);
842 ExceptionOr<bool> Internals::isTimerThrottled(int timeoutId)
844 DOMTimer* timer = scriptExecutionContext()->findTimeout(timeoutId);
846 return Exception { NOT_FOUND_ERR };
847 return timer->m_throttleState == DOMTimer::ShouldThrottle;
850 bool Internals::isRequestAnimationFrameThrottled() const
852 #if ENABLE(REQUEST_ANIMATION_FRAME)
853 auto* scriptedAnimationController = contextDocument()->scriptedAnimationController();
854 if (!scriptedAnimationController)
856 return scriptedAnimationController->isThrottled();
862 bool Internals::areTimersThrottled() const
864 return contextDocument()->isTimerThrottlingEnabled();
867 String Internals::visiblePlaceholder(Element& element)
869 if (is<HTMLTextFormControlElement>(element)) {
870 const HTMLTextFormControlElement& textFormControlElement = downcast<HTMLTextFormControlElement>(element);
871 if (!textFormControlElement.isPlaceholderVisible())
873 if (HTMLElement* placeholderElement = textFormControlElement.placeholderElement())
874 return placeholderElement->textContent();
880 void Internals::selectColorInColorChooser(HTMLInputElement& element, const String& colorValue)
882 element.selectColor(Color(colorValue));
885 ExceptionOr<Vector<String>> Internals::formControlStateOfPreviousHistoryItem()
887 HistoryItem* mainItem = frame()->loader().history().previousItem();
889 return Exception { INVALID_ACCESS_ERR };
890 String uniqueName = frame()->tree().uniqueName();
891 if (mainItem->target() != uniqueName && !mainItem->childItemWithTarget(uniqueName))
892 return Exception { INVALID_ACCESS_ERR };
893 return Vector<String> { mainItem->target() == uniqueName ? mainItem->documentState() : mainItem->childItemWithTarget(uniqueName)->documentState() };
896 ExceptionOr<void> Internals::setFormControlStateOfPreviousHistoryItem(const Vector<String>& state)
898 HistoryItem* mainItem = frame()->loader().history().previousItem();
900 return Exception { INVALID_ACCESS_ERR };
901 String uniqueName = frame()->tree().uniqueName();
902 if (mainItem->target() == uniqueName)
903 mainItem->setDocumentState(state);
904 else if (HistoryItem* subItem = mainItem->childItemWithTarget(uniqueName))
905 subItem->setDocumentState(state);
907 return Exception { INVALID_ACCESS_ERR };
911 #if ENABLE(SPEECH_SYNTHESIS)
913 void Internals::enableMockSpeechSynthesizer()
915 Document* document = contextDocument();
916 if (!document || !document->domWindow())
918 SpeechSynthesis* synthesis = DOMWindowSpeechSynthesis::speechSynthesis(*document->domWindow());
922 synthesis->setPlatformSynthesizer(std::make_unique<PlatformSpeechSynthesizerMock>(synthesis));
929 void Internals::enableMockMediaEndpoint()
931 MediaEndpoint::create = MockMediaEndpoint::create;
934 void Internals::enableMockRTCPeerConnectionHandler()
936 RTCPeerConnectionHandler::create = RTCPeerConnectionHandlerMock::create;
939 void Internals::emulateRTCPeerConnectionPlatformEvent(RTCPeerConnection& connection, const String& action)
941 connection.emulatePlatformEvent(action);
946 #if ENABLE(MEDIA_STREAM)
948 void Internals::setMockMediaCaptureDevicesEnabled(bool enabled)
950 WebCore::Settings::setMockCaptureDevicesEnabled(enabled);
955 ExceptionOr<Ref<ClientRect>> Internals::absoluteCaretBounds()
957 Document* document = contextDocument();
958 if (!document || !document->frame())
959 return Exception { INVALID_ACCESS_ERR };
961 return ClientRect::create(document->frame()->selection().absoluteCaretBounds());
964 Ref<ClientRect> Internals::boundingBox(Element& element)
966 element.document().updateLayoutIgnorePendingStylesheets();
967 auto renderer = element.renderer();
969 return ClientRect::create();
970 return ClientRect::create(renderer->absoluteBoundingBoxRectIgnoringTransforms());
973 ExceptionOr<Ref<ClientRectList>> Internals::inspectorHighlightRects()
975 Document* document = contextDocument();
976 if (!document || !document->page())
977 return Exception { INVALID_ACCESS_ERR };
980 document->page()->inspectorController().getHighlight(highlight, InspectorOverlay::CoordinateSystem::View);
981 return ClientRectList::create(highlight.quads);
984 ExceptionOr<String> Internals::inspectorHighlightObject()
986 Document* document = contextDocument();
987 if (!document || !document->page())
988 return Exception { INVALID_ACCESS_ERR };
990 return document->page()->inspectorController().buildObjectForHighlightedNodes()->toJSONString();
993 ExceptionOr<unsigned> Internals::markerCountForNode(Node& node, const String& markerType)
995 DocumentMarker::MarkerTypes markerTypes = 0;
996 if (!markerTypesFrom(markerType, markerTypes))
997 return Exception { SYNTAX_ERR };
999 node.document().frame()->editor().updateEditorUINowIfScheduled();
1000 return node.document().markers().markersFor(&node, markerTypes).size();
1003 ExceptionOr<RenderedDocumentMarker*> Internals::markerAt(Node& node, const String& markerType, unsigned index)
1005 node.document().updateLayoutIgnorePendingStylesheets();
1007 DocumentMarker::MarkerTypes markerTypes = 0;
1008 if (!markerTypesFrom(markerType, markerTypes))
1009 return Exception { SYNTAX_ERR };
1011 node.document().frame()->editor().updateEditorUINowIfScheduled();
1013 Vector<RenderedDocumentMarker*> markers = node.document().markers().markersFor(&node, markerTypes);
1014 if (markers.size() <= index)
1016 return markers[index];
1019 ExceptionOr<RefPtr<Range>> Internals::markerRangeForNode(Node& node, const String& markerType, unsigned index)
1021 auto result = markerAt(node, markerType, index);
1022 if (result.hasException())
1023 return result.releaseException();
1024 auto marker = result.releaseReturnValue();
1027 return RefPtr<Range> { Range::create(node.document(), &node, marker->startOffset(), &node, marker->endOffset()) };
1030 ExceptionOr<String> Internals::markerDescriptionForNode(Node& node, const String& markerType, unsigned index)
1032 auto result = markerAt(node, markerType, index);
1033 if (result.hasException())
1034 return result.releaseException();
1035 auto marker = result.releaseReturnValue();
1038 return String { marker->description() };
1041 ExceptionOr<String> Internals::dumpMarkerRects(const String& markerTypeString)
1043 DocumentMarker::MarkerType markerType;
1044 if (!markerTypeFrom(markerTypeString, markerType))
1045 return Exception { SYNTAX_ERR };
1047 contextDocument()->markers().updateRectsForInvalidatedMarkersOfType(markerType);
1048 auto rects = contextDocument()->markers().renderedRectsForMarkers(markerType);
1050 StringBuilder rectString;
1051 rectString.appendLiteral("marker rects: ");
1052 for (const auto& rect : rects) {
1053 rectString.append('(');
1054 rectString.appendNumber(rect.x());
1055 rectString.appendLiteral(", ");
1056 rectString.appendNumber(rect.y());
1057 rectString.appendLiteral(", ");
1058 rectString.appendNumber(rect.width());
1059 rectString.appendLiteral(", ");
1060 rectString.appendNumber(rect.height());
1061 rectString.appendLiteral(") ");
1063 return rectString.toString();
1066 void Internals::addTextMatchMarker(const Range& range, bool isActive)
1068 range.ownerDocument().updateLayoutIgnorePendingStylesheets();
1069 range.ownerDocument().markers().addTextMatchMarker(&range, isActive);
1072 ExceptionOr<void> Internals::setMarkedTextMatchesAreHighlighted(bool flag)
1074 Document* document = contextDocument();
1075 if (!document || !document->frame())
1076 return Exception { INVALID_ACCESS_ERR };
1077 document->frame()->editor().setMarkedTextMatchesAreHighlighted(flag);
1081 void Internals::invalidateFontCache()
1083 FontCache::singleton().invalidate();
1086 ExceptionOr<void> Internals::setScrollViewPosition(int x, int y)
1088 Document* document = contextDocument();
1089 if (!document || !document->view())
1090 return Exception { INVALID_ACCESS_ERR };
1092 auto& frameView = *document->view();
1093 bool constrainsScrollingToContentEdgeOldValue = frameView.constrainsScrollingToContentEdge();
1094 bool scrollbarsSuppressedOldValue = frameView.scrollbarsSuppressed();
1096 frameView.setConstrainsScrollingToContentEdge(false);
1097 frameView.setScrollbarsSuppressed(false);
1098 frameView.setScrollOffsetFromInternals({ x, y });
1099 frameView.setScrollbarsSuppressed(scrollbarsSuppressedOldValue);
1100 frameView.setConstrainsScrollingToContentEdge(constrainsScrollingToContentEdgeOldValue);
1105 ExceptionOr<void> Internals::setViewBaseBackgroundColor(const String& colorValue)
1107 Document* document = contextDocument();
1108 if (!document || !document->view())
1109 return Exception { INVALID_ACCESS_ERR };
1111 document->view()->setBaseBackgroundColor(Color(colorValue));
1115 ExceptionOr<void> Internals::setPagination(const String& mode, int gap, int pageLength)
1117 Document* document = contextDocument();
1118 if (!document || !document->page())
1119 return Exception { INVALID_ACCESS_ERR };
1121 Pagination pagination;
1122 if (mode == "Unpaginated")
1123 pagination.mode = Pagination::Unpaginated;
1124 else if (mode == "LeftToRightPaginated")
1125 pagination.mode = Pagination::LeftToRightPaginated;
1126 else if (mode == "RightToLeftPaginated")
1127 pagination.mode = Pagination::RightToLeftPaginated;
1128 else if (mode == "TopToBottomPaginated")
1129 pagination.mode = Pagination::TopToBottomPaginated;
1130 else if (mode == "BottomToTopPaginated")
1131 pagination.mode = Pagination::BottomToTopPaginated;
1133 return Exception { SYNTAX_ERR };
1135 pagination.gap = gap;
1136 pagination.pageLength = pageLength;
1137 document->page()->setPagination(pagination);
1142 ExceptionOr<void> Internals::setPaginationLineGridEnabled(bool enabled)
1144 Document* document = contextDocument();
1145 if (!document || !document->page())
1146 return Exception { INVALID_ACCESS_ERR };
1147 document->page()->setPaginationLineGridEnabled(enabled);
1151 ExceptionOr<String> Internals::configurationForViewport(float devicePixelRatio, int deviceWidth, int deviceHeight, int availableWidth, int availableHeight)
1153 Document* document = contextDocument();
1154 if (!document || !document->page())
1155 return Exception { INVALID_ACCESS_ERR };
1157 const int defaultLayoutWidthForNonMobilePages = 980;
1159 ViewportArguments arguments = document->page()->viewportArguments();
1160 ViewportAttributes attributes = computeViewportAttributes(arguments, defaultLayoutWidthForNonMobilePages, deviceWidth, deviceHeight, devicePixelRatio, IntSize(availableWidth, availableHeight));
1161 restrictMinimumScaleFactorToViewportSize(attributes, IntSize(availableWidth, availableHeight), devicePixelRatio);
1162 restrictScaleFactorToInitialScaleIfNotUserScalable(attributes);
1164 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") };
1167 ExceptionOr<bool> Internals::wasLastChangeUserEdit(Element& textField)
1169 if (is<HTMLInputElement>(textField))
1170 return downcast<HTMLInputElement>(textField).lastChangeWasUserEdit();
1172 if (is<HTMLTextAreaElement>(textField))
1173 return downcast<HTMLTextAreaElement>(textField).lastChangeWasUserEdit();
1175 return Exception { INVALID_NODE_TYPE_ERR };
1178 bool Internals::elementShouldAutoComplete(HTMLInputElement& element)
1180 return element.shouldAutocomplete();
1183 void Internals::setEditingValue(HTMLInputElement& element, const String& value)
1185 element.setEditingValue(value);
1188 void Internals::setAutofilled(HTMLInputElement& element, bool enabled)
1190 element.setAutoFilled(enabled);
1193 static AutoFillButtonType toAutoFillButtonType(Internals::AutoFillButtonType type)
1196 case Internals::AutoFillButtonType::AutoFillButtonTypeNone:
1197 return AutoFillButtonType::None;
1198 case Internals::AutoFillButtonType::AutoFillButtonTypeCredentials:
1199 return AutoFillButtonType::Credentials;
1200 case Internals::AutoFillButtonType::AutoFillButtonTypeContacts:
1201 return AutoFillButtonType::Contacts;
1203 ASSERT_NOT_REACHED();
1204 return AutoFillButtonType::None;
1207 void Internals::setShowAutoFillButton(HTMLInputElement& element, AutoFillButtonType type)
1209 element.setShowAutoFillButton(toAutoFillButtonType(type));
1212 ExceptionOr<void> Internals::scrollElementToRect(Element& element, int x, int y, int w, int h)
1214 FrameView* frameView = element.document().view();
1216 return Exception { INVALID_ACCESS_ERR };
1217 frameView->scrollElementToRect(element, { x, y, w, h });
1221 ExceptionOr<String> Internals::autofillFieldName(Element& element)
1223 if (!is<HTMLFormControlElement>(element))
1224 return Exception { INVALID_NODE_TYPE_ERR };
1226 return String { downcast<HTMLFormControlElement>(element).autofillData().fieldName };
1229 ExceptionOr<void> Internals::paintControlTints()
1231 Document* document = contextDocument();
1232 if (!document || !document->view())
1233 return Exception { INVALID_ACCESS_ERR };
1235 document->view()->paintControlTints();
1239 RefPtr<Range> Internals::rangeFromLocationAndLength(Element& scope, int rangeLocation, int rangeLength)
1241 return TextIterator::rangeFromLocationAndLength(&scope, rangeLocation, rangeLength);
1244 unsigned Internals::locationFromRange(Element& scope, const Range& range)
1246 size_t location = 0;
1247 size_t unusedLength = 0;
1248 TextIterator::getLocationAndLengthFromRange(&scope, &range, location, unusedLength);
1252 unsigned Internals::lengthFromRange(Element& scope, const Range& range)
1254 size_t unusedLocation = 0;
1256 TextIterator::getLocationAndLengthFromRange(&scope, &range, unusedLocation, length);
1260 String Internals::rangeAsText(const Range& range)
1262 return range.text();
1265 RefPtr<Range> Internals::subrange(Range& range, int rangeLocation, int rangeLength)
1267 return TextIterator::subrange(&range, rangeLocation, rangeLength);
1270 ExceptionOr<RefPtr<Range>> Internals::rangeForDictionaryLookupAtLocation(int x, int y)
1273 Document* document = contextDocument();
1274 if (!document || !document->frame())
1275 return Exception { INVALID_ACCESS_ERR };
1277 document->updateLayoutIgnorePendingStylesheets();
1279 HitTestResult result = document->frame()->mainFrame().eventHandler().hitTestResultAtPoint(IntPoint(x, y));
1280 NSDictionary *options = nullptr;
1281 return DictionaryLookup::rangeAtHitTestResult(result, &options);
1285 return Exception { INVALID_ACCESS_ERR };
1289 ExceptionOr<void> Internals::setDelegatesScrolling(bool enabled)
1291 Document* document = contextDocument();
1292 // Delegate scrolling is valid only on mainframe's view.
1293 if (!document || !document->view() || !document->page() || &document->page()->mainFrame() != document->frame())
1294 return Exception { INVALID_ACCESS_ERR };
1296 document->view()->setDelegatesScrolling(enabled);
1300 ExceptionOr<int> Internals::lastSpellCheckRequestSequence()
1302 Document* document = contextDocument();
1303 if (!document || !document->frame())
1304 return Exception { INVALID_ACCESS_ERR };
1306 return document->frame()->editor().spellChecker().lastRequestSequence();
1309 ExceptionOr<int> Internals::lastSpellCheckProcessedSequence()
1311 Document* document = contextDocument();
1312 if (!document || !document->frame())
1313 return Exception { INVALID_ACCESS_ERR };
1315 return document->frame()->editor().spellChecker().lastProcessedSequence();
1318 Vector<String> Internals::userPreferredLanguages() const
1320 return WebCore::userPreferredLanguages();
1323 void Internals::setUserPreferredLanguages(const Vector<String>& languages)
1325 WebCore::overrideUserPreferredLanguages(languages);
1328 Vector<String> Internals::userPreferredAudioCharacteristics() const
1330 Document* document = contextDocument();
1331 if (!document || !document->page())
1332 return Vector<String>();
1333 #if ENABLE(VIDEO_TRACK)
1334 return document->page()->group().captionPreferences().preferredAudioCharacteristics();
1336 return Vector<String>();
1340 void Internals::setUserPreferredAudioCharacteristic(const String& characteristic)
1342 Document* document = contextDocument();
1343 if (!document || !document->page())
1345 #if ENABLE(VIDEO_TRACK)
1346 document->page()->group().captionPreferences().setPreferredAudioCharacteristic(characteristic);
1348 UNUSED_PARAM(characteristic);
1352 ExceptionOr<unsigned> Internals::wheelEventHandlerCount()
1354 Document* document = contextDocument();
1356 return Exception { INVALID_ACCESS_ERR };
1358 return document->wheelEventHandlerCount();
1361 ExceptionOr<unsigned> Internals::touchEventHandlerCount()
1363 Document* document = contextDocument();
1365 return Exception { INVALID_ACCESS_ERR };
1367 return document->touchEventHandlerCount();
1370 // FIXME: Remove the document argument. It is almost always the same as
1371 // contextDocument(), with the exception of a few tests that pass a
1372 // different document, and could just make the call through another Internals
1373 // instance instead.
1374 ExceptionOr<RefPtr<NodeList>> Internals::nodesFromRect(Document& document, int centerX, int centerY, unsigned topPadding, unsigned rightPadding, unsigned bottomPadding, unsigned leftPadding, bool ignoreClipping, bool allowShadowContent, bool allowChildFrameContent) const
1376 if (!document.frame() || !document.frame()->view())
1377 return Exception { INVALID_ACCESS_ERR };
1379 Frame* frame = document.frame();
1380 FrameView* frameView = document.view();
1381 RenderView* renderView = document.renderView();
1385 document.updateLayoutIgnorePendingStylesheets();
1387 float zoomFactor = frame->pageZoomFactor();
1388 LayoutPoint point(centerX * zoomFactor + frameView->scrollX(), centerY * zoomFactor + frameView->scrollY());
1390 HitTestRequest::HitTestRequestType hitType = HitTestRequest::ReadOnly | HitTestRequest::Active;
1392 hitType |= HitTestRequest::IgnoreClipping;
1393 if (!allowShadowContent)
1394 hitType |= HitTestRequest::DisallowUserAgentShadowContent;
1395 if (allowChildFrameContent)
1396 hitType |= HitTestRequest::AllowChildFrameContent;
1398 HitTestRequest request(hitType);
1400 // When ignoreClipping is false, this method returns null for coordinates outside of the viewport.
1401 if (!request.ignoreClipping() && !frameView->visibleContentRect().intersects(HitTestLocation::rectForPoint(point, topPadding, rightPadding, bottomPadding, leftPadding)))
1404 Vector<Ref<Node>> matches;
1406 // Need padding to trigger a rect based hit test, but we want to return a NodeList
1407 // so we special case this.
1408 if (!topPadding && !rightPadding && !bottomPadding && !leftPadding) {
1409 HitTestResult result(point);
1410 renderView->hitTest(request, result);
1411 if (result.innerNode())
1412 matches.append(*result.innerNode()->deprecatedShadowAncestorNode());
1414 HitTestResult result(point, topPadding, rightPadding, bottomPadding, leftPadding);
1415 renderView->hitTest(request, result);
1417 const HitTestResult::NodeSet& nodeSet = result.rectBasedTestResult();
1418 matches.reserveInitialCapacity(nodeSet.size());
1419 for (auto& node : nodeSet)
1420 matches.uncheckedAppend(*node);
1423 return RefPtr<NodeList> { StaticNodeList::create(WTFMove(matches)) };
1426 class GetCallerCodeBlockFunctor {
1428 GetCallerCodeBlockFunctor()
1434 StackVisitor::Status operator()(StackVisitor& visitor) const
1437 if (m_iterations < 2)
1438 return StackVisitor::Continue;
1440 m_codeBlock = visitor->codeBlock();
1441 return StackVisitor::Done;
1444 CodeBlock* codeBlock() const { return m_codeBlock; }
1447 mutable int m_iterations;
1448 mutable CodeBlock* m_codeBlock;
1451 String Internals::parserMetaData(JSC::JSValue code)
1453 JSC::VM& vm = contextDocument()->vm();
1454 JSC::ExecState* exec = vm.topCallFrame;
1455 ScriptExecutable* executable;
1457 if (!code || code.isNull() || code.isUndefined()) {
1458 GetCallerCodeBlockFunctor iter;
1459 exec->iterate(iter);
1460 CodeBlock* codeBlock = iter.codeBlock();
1461 executable = codeBlock->ownerScriptExecutable();
1462 } else if (code.isFunction()) {
1463 JSFunction* funcObj = JSC::jsCast<JSFunction*>(code.toObject(exec));
1464 executable = funcObj->jsExecutable();
1468 unsigned startLine = executable->firstLine();
1469 unsigned startColumn = executable->startColumn();
1470 unsigned endLine = executable->lastLine();
1471 unsigned endColumn = executable->endColumn();
1473 StringBuilder result;
1475 if (executable->isFunctionExecutable()) {
1476 FunctionExecutable* funcExecutable = reinterpret_cast<FunctionExecutable*>(executable);
1477 String inferredName = funcExecutable->inferredName().string();
1478 result.appendLiteral("function \"");
1479 result.append(inferredName);
1481 } else if (executable->isEvalExecutable())
1482 result.appendLiteral("eval");
1483 else if (executable->isModuleProgramExecutable())
1484 result.appendLiteral("module");
1485 else if (executable->isProgramExecutable())
1486 result.appendLiteral("program");
1487 #if ENABLE(WEBASSEMBLY)
1488 else if (executable->isWebAssemblyExecutable())
1489 result.appendLiteral("WebAssembly");
1492 ASSERT_NOT_REACHED();
1494 result.appendLiteral(" { ");
1495 result.appendNumber(startLine);
1497 result.appendNumber(startColumn);
1498 result.appendLiteral(" - ");
1499 result.appendNumber(endLine);
1501 result.appendNumber(endColumn);
1502 result.appendLiteral(" }");
1504 return result.toString();
1507 ExceptionOr<void> Internals::setBatteryStatus(const String& eventType, bool charging, double chargingTime, double dischargingTime, double level)
1509 Document* document = contextDocument();
1510 if (!document || !document->page())
1511 return Exception { INVALID_ACCESS_ERR };
1513 #if ENABLE(BATTERY_STATUS)
1514 BatteryController::from(document->page())->didChangeBatteryStatus(eventType, BatteryStatus::create(charging, chargingTime, dischargingTime, level));
1516 UNUSED_PARAM(eventType);
1517 UNUSED_PARAM(charging);
1518 UNUSED_PARAM(chargingTime);
1519 UNUSED_PARAM(dischargingTime);
1520 UNUSED_PARAM(level);
1525 ExceptionOr<void> Internals::setDeviceProximity(const String&, double value, double min, double max)
1527 Document* document = contextDocument();
1528 if (!document || !document->page())
1529 return Exception { INVALID_ACCESS_ERR };
1531 #if ENABLE(PROXIMITY_EVENTS)
1532 DeviceProximityController::from(document->page())->didChangeDeviceProximity(value, min, max);
1534 UNUSED_PARAM(value);
1541 void Internals::updateEditorUINowIfScheduled()
1543 if (Document* document = contextDocument()) {
1544 if (Frame* frame = document->frame())
1545 frame->editor().updateEditorUINowIfScheduled();
1549 bool Internals::hasSpellingMarker(int from, int length)
1551 Document* document = contextDocument();
1552 if (!document || !document->frame())
1555 updateEditorUINowIfScheduled();
1557 return document->frame()->editor().selectionStartHasMarkerFor(DocumentMarker::Spelling, from, length);
1560 bool Internals::hasAutocorrectedMarker(int from, int length)
1562 Document* document = contextDocument();
1563 if (!document || !document->frame())
1566 updateEditorUINowIfScheduled();
1568 return document->frame()->editor().selectionStartHasMarkerFor(DocumentMarker::Autocorrected, from, length);
1571 void Internals::setContinuousSpellCheckingEnabled(bool enabled)
1573 if (!contextDocument() || !contextDocument()->frame())
1576 if (enabled != contextDocument()->frame()->editor().isContinuousSpellCheckingEnabled())
1577 contextDocument()->frame()->editor().toggleContinuousSpellChecking();
1580 void Internals::setAutomaticQuoteSubstitutionEnabled(bool enabled)
1582 if (!contextDocument() || !contextDocument()->frame())
1585 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
1586 if (enabled != contextDocument()->frame()->editor().isAutomaticQuoteSubstitutionEnabled())
1587 contextDocument()->frame()->editor().toggleAutomaticQuoteSubstitution();
1589 UNUSED_PARAM(enabled);
1593 void Internals::setAutomaticLinkDetectionEnabled(bool enabled)
1595 if (!contextDocument() || !contextDocument()->frame())
1598 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
1599 if (enabled != contextDocument()->frame()->editor().isAutomaticLinkDetectionEnabled())
1600 contextDocument()->frame()->editor().toggleAutomaticLinkDetection();
1602 UNUSED_PARAM(enabled);
1606 void Internals::setAutomaticDashSubstitutionEnabled(bool enabled)
1608 if (!contextDocument() || !contextDocument()->frame())
1611 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
1612 if (enabled != contextDocument()->frame()->editor().isAutomaticDashSubstitutionEnabled())
1613 contextDocument()->frame()->editor().toggleAutomaticDashSubstitution();
1615 UNUSED_PARAM(enabled);
1619 void Internals::setAutomaticTextReplacementEnabled(bool enabled)
1621 if (!contextDocument() || !contextDocument()->frame())
1624 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
1625 if (enabled != contextDocument()->frame()->editor().isAutomaticTextReplacementEnabled())
1626 contextDocument()->frame()->editor().toggleAutomaticTextReplacement();
1628 UNUSED_PARAM(enabled);
1632 void Internals::setAutomaticSpellingCorrectionEnabled(bool enabled)
1634 if (!contextDocument() || !contextDocument()->frame())
1637 #if USE(AUTOMATIC_TEXT_REPLACEMENT)
1638 if (enabled != contextDocument()->frame()->editor().isAutomaticSpellingCorrectionEnabled())
1639 contextDocument()->frame()->editor().toggleAutomaticSpellingCorrection();
1641 UNUSED_PARAM(enabled);
1645 void Internals::handleAcceptedCandidate(const String& candidate, unsigned location, unsigned length)
1647 if (!contextDocument() || !contextDocument()->frame())
1650 TextCheckingResult result;
1651 result.type = TextCheckingTypeNone;
1652 result.location = location;
1653 result.length = length;
1654 result.replacement = candidate;
1655 contextDocument()->frame()->editor().handleAcceptedCandidate(result);
1658 bool Internals::isOverwriteModeEnabled()
1660 Document* document = contextDocument();
1661 if (!document || !document->frame())
1664 return document->frame()->editor().isOverwriteModeEnabled();
1667 void Internals::toggleOverwriteModeEnabled()
1669 Document* document = contextDocument();
1670 if (!document || !document->frame())
1673 document->frame()->editor().toggleOverwriteModeEnabled();
1676 unsigned Internals::countMatchesForText(const String& text, unsigned findOptions, const String& markMatches)
1678 Document* document = contextDocument();
1679 if (!document || !document->frame())
1682 bool mark = markMatches == "mark";
1683 return document->frame()->editor().countMatchesForText(text, nullptr, findOptions, 1000, mark, nullptr);
1686 unsigned Internals::countFindMatches(const String& text, unsigned findOptions)
1688 Document* document = contextDocument();
1689 if (!document || !document->page())
1692 return document->page()->countFindMatches(text, findOptions, 1000);
1695 unsigned Internals::numberOfLiveNodes() const
1697 unsigned nodeCount = 0;
1698 for (auto* document : Document::allDocuments())
1699 nodeCount += document->referencingNodeCount();
1703 unsigned Internals::numberOfLiveDocuments() const
1705 return Document::allDocuments().size();
1708 RefPtr<DOMWindow> Internals::openDummyInspectorFrontend(const String& url)
1710 Page* inspectedPage = contextDocument()->frame()->page();
1711 RefPtr<DOMWindow> window = inspectedPage->mainFrame().document()->domWindow();
1712 RefPtr<DOMWindow> frontendWindow = window->open(url, "", "", *window, *window);
1713 m_inspectorFrontend = std::make_unique<InspectorStubFrontend>(*inspectedPage, frontendWindow.copyRef());
1715 return frontendWindow;
1718 void Internals::closeDummyInspectorFrontend()
1720 m_inspectorFrontend = nullptr;
1723 ExceptionOr<void> Internals::setInspectorIsUnderTest(bool isUnderTest)
1725 Page* page = contextDocument()->frame()->page();
1727 return Exception { INVALID_ACCESS_ERR };
1729 page->inspectorController().setIsUnderTest(isUnderTest);
1733 bool Internals::hasGrammarMarker(int from, int length)
1735 Document* document = contextDocument();
1736 if (!document || !document->frame())
1739 return document->frame()->editor().selectionStartHasMarkerFor(DocumentMarker::Grammar, from, length);
1742 unsigned Internals::numberOfScrollableAreas()
1744 Document* document = contextDocument();
1745 if (!document || !document->frame())
1749 Frame* frame = document->frame();
1750 if (frame->view()->scrollableAreas())
1751 count += frame->view()->scrollableAreas()->size();
1753 for (Frame* child = frame->tree().firstChild(); child; child = child->tree().nextSibling()) {
1754 if (child->view() && child->view()->scrollableAreas())
1755 count += child->view()->scrollableAreas()->size();
1761 ExceptionOr<bool> Internals::isPageBoxVisible(int pageNumber)
1763 Document* document = contextDocument();
1765 return Exception { INVALID_ACCESS_ERR };
1767 return document->isPageBoxVisible(pageNumber);
1770 // FIXME: Remove the document argument. It is almost always the same as
1771 // contextDocument(), with the exception of a few tests that pass a
1772 // different document, and could just make the call through another Internals
1773 // instance instead.
1774 ExceptionOr<String> Internals::layerTreeAsText(Document& document, unsigned short flags) const
1776 if (!document.frame())
1777 return Exception { INVALID_ACCESS_ERR };
1779 LayerTreeFlags layerTreeFlags = 0;
1780 if (flags & LAYER_TREE_INCLUDES_VISIBLE_RECTS)
1781 layerTreeFlags |= LayerTreeFlagsIncludeVisibleRects;
1782 if (flags & LAYER_TREE_INCLUDES_TILE_CACHES)
1783 layerTreeFlags |= LayerTreeFlagsIncludeTileCaches;
1784 if (flags & LAYER_TREE_INCLUDES_REPAINT_RECTS)
1785 layerTreeFlags |= LayerTreeFlagsIncludeRepaintRects;
1786 if (flags & LAYER_TREE_INCLUDES_PAINTING_PHASES)
1787 layerTreeFlags |= LayerTreeFlagsIncludePaintingPhases;
1788 if (flags & LAYER_TREE_INCLUDES_CONTENT_LAYERS)
1789 layerTreeFlags |= LayerTreeFlagsIncludeContentLayers;
1791 return document.frame()->layerTreeAsText(layerTreeFlags);
1794 ExceptionOr<String> Internals::repaintRectsAsText() const
1796 Document* document = contextDocument();
1797 if (!document || !document->frame())
1798 return Exception { INVALID_ACCESS_ERR };
1800 return document->frame()->trackedRepaintRectsAsText();
1803 ExceptionOr<String> Internals::scrollingStateTreeAsText() const
1805 Document* document = contextDocument();
1806 if (!document || !document->frame())
1807 return Exception { INVALID_ACCESS_ERR };
1809 Page* page = document->page();
1813 return page->scrollingStateTreeAsText();
1816 ExceptionOr<String> Internals::mainThreadScrollingReasons() const
1818 Document* document = contextDocument();
1819 if (!document || !document->frame())
1820 return Exception { INVALID_ACCESS_ERR };
1822 Page* page = document->page();
1826 return page->synchronousScrollingReasonsAsText();
1829 ExceptionOr<RefPtr<ClientRectList>> Internals::nonFastScrollableRects() const
1831 Document* document = contextDocument();
1832 if (!document || !document->frame())
1833 return Exception { INVALID_ACCESS_ERR };
1835 Page* page = document->page();
1839 return RefPtr<ClientRectList> { page->nonFastScrollableRects() };
1842 ExceptionOr<void> Internals::setElementUsesDisplayListDrawing(Element& element, bool usesDisplayListDrawing)
1844 Document* document = contextDocument();
1845 if (!document || !document->renderView())
1846 return Exception { INVALID_ACCESS_ERR };
1848 if (!element.renderer())
1849 return Exception { INVALID_ACCESS_ERR };
1851 if (is<HTMLCanvasElement>(element)) {
1852 downcast<HTMLCanvasElement>(element).setUsesDisplayListDrawing(usesDisplayListDrawing);
1856 if (!element.renderer()->hasLayer())
1857 return Exception { INVALID_ACCESS_ERR };
1859 RenderLayer* layer = downcast<RenderLayerModelObject>(element.renderer())->layer();
1860 if (!layer->isComposited())
1861 return Exception { INVALID_ACCESS_ERR };
1863 layer->backing()->setUsesDisplayListDrawing(usesDisplayListDrawing);
1867 ExceptionOr<void> Internals::setElementTracksDisplayListReplay(Element& element, bool isTrackingReplay)
1869 Document* document = contextDocument();
1870 if (!document || !document->renderView())
1871 return Exception { INVALID_ACCESS_ERR };
1873 if (!element.renderer())
1874 return Exception { INVALID_ACCESS_ERR };
1876 if (is<HTMLCanvasElement>(element)) {
1877 downcast<HTMLCanvasElement>(element).setTracksDisplayListReplay(isTrackingReplay);
1881 if (!element.renderer()->hasLayer())
1882 return Exception { INVALID_ACCESS_ERR };
1884 RenderLayer* layer = downcast<RenderLayerModelObject>(element.renderer())->layer();
1885 if (!layer->isComposited())
1886 return Exception { INVALID_ACCESS_ERR };
1888 layer->backing()->setIsTrackingDisplayListReplay(isTrackingReplay);
1892 ExceptionOr<String> Internals::displayListForElement(Element& element, unsigned short flags)
1894 Document* document = contextDocument();
1895 if (!document || !document->renderView())
1896 return Exception { INVALID_ACCESS_ERR };
1898 if (!element.renderer())
1899 return Exception { INVALID_ACCESS_ERR };
1901 DisplayList::AsTextFlags displayListFlags = 0;
1902 if (flags & DISPLAY_LIST_INCLUDES_PLATFORM_OPERATIONS)
1903 displayListFlags |= DisplayList::AsTextFlag::IncludesPlatformOperations;
1905 if (is<HTMLCanvasElement>(element))
1906 return downcast<HTMLCanvasElement>(element).displayListAsText(displayListFlags);
1908 if (!element.renderer()->hasLayer())
1909 return Exception { INVALID_ACCESS_ERR };
1911 RenderLayer* layer = downcast<RenderLayerModelObject>(element.renderer())->layer();
1912 if (!layer->isComposited())
1913 return Exception { INVALID_ACCESS_ERR };
1915 return layer->backing()->displayListAsText(displayListFlags);
1918 ExceptionOr<String> Internals::replayDisplayListForElement(Element& element, unsigned short flags)
1920 Document* document = contextDocument();
1921 if (!document || !document->renderView())
1922 return Exception { INVALID_ACCESS_ERR };
1924 if (!element.renderer())
1925 return Exception { INVALID_ACCESS_ERR };
1927 DisplayList::AsTextFlags displayListFlags = 0;
1928 if (flags & DISPLAY_LIST_INCLUDES_PLATFORM_OPERATIONS)
1929 displayListFlags |= DisplayList::AsTextFlag::IncludesPlatformOperations;
1931 if (is<HTMLCanvasElement>(element))
1932 return downcast<HTMLCanvasElement>(element).replayDisplayListAsText(displayListFlags);
1934 if (!element.renderer()->hasLayer())
1935 return Exception { INVALID_ACCESS_ERR };
1937 RenderLayer* layer = downcast<RenderLayerModelObject>(element.renderer())->layer();
1938 if (!layer->isComposited())
1939 return Exception { INVALID_ACCESS_ERR };
1941 return layer->backing()->replayDisplayListAsText(displayListFlags);
1944 ExceptionOr<void> Internals::garbageCollectDocumentResources() const
1946 Document* document = contextDocument();
1948 return Exception { INVALID_ACCESS_ERR };
1949 document->cachedResourceLoader().garbageCollectDocumentResources();
1953 bool Internals::isUnderMemoryPressure()
1955 return MemoryPressureHandler::singleton().isUnderMemoryPressure();
1958 void Internals::beginSimulatedMemoryPressure()
1960 MemoryPressureHandler::singleton().beginSimulatedMemoryPressure();
1963 void Internals::endSimulatedMemoryPressure()
1965 MemoryPressureHandler::singleton().endSimulatedMemoryPressure();
1968 ExceptionOr<void> Internals::insertAuthorCSS(const String& css) const
1970 Document* document = contextDocument();
1972 return Exception { INVALID_ACCESS_ERR };
1974 auto parsedSheet = StyleSheetContents::create(*document);
1975 parsedSheet.get().setIsUserStyleSheet(false);
1976 parsedSheet.get().parseString(css);
1977 document->extensionStyleSheets().addAuthorStyleSheetForTesting(WTFMove(parsedSheet));
1981 ExceptionOr<void> Internals::insertUserCSS(const String& css) const
1983 Document* document = contextDocument();
1985 return Exception { INVALID_ACCESS_ERR };
1987 auto parsedSheet = StyleSheetContents::create(*document);
1988 parsedSheet.get().setIsUserStyleSheet(true);
1989 parsedSheet.get().parseString(css);
1990 document->extensionStyleSheets().addUserStyleSheet(WTFMove(parsedSheet));
1994 String Internals::counterValue(Element& element)
1996 return counterValueForElement(&element);
1999 int Internals::pageNumber(Element& element, float pageWidth, float pageHeight)
2001 return PrintContext::pageNumberForElement(&element, { pageWidth, pageHeight });
2004 Vector<String> Internals::shortcutIconURLs() const
2006 Vector<String> vector;
2011 auto string = frame()->loader().icon().url().string();
2012 if (!string.isNull())
2013 vector.append(string);
2017 int Internals::numberOfPages(float pageWidth, float pageHeight)
2022 return PrintContext::numberOfPages(*frame(), FloatSize(pageWidth, pageHeight));
2025 ExceptionOr<String> Internals::pageProperty(const String& propertyName, int pageNumber) const
2028 return Exception { INVALID_ACCESS_ERR };
2030 return PrintContext::pageProperty(frame(), propertyName.utf8().data(), pageNumber);
2033 ExceptionOr<String> Internals::pageSizeAndMarginsInPixels(int pageNumber, int width, int height, int marginTop, int marginRight, int marginBottom, int marginLeft) const
2036 return Exception { INVALID_ACCESS_ERR };
2038 return PrintContext::pageSizeAndMarginsInPixels(frame(), pageNumber, width, height, marginTop, marginRight, marginBottom, marginLeft);
2041 ExceptionOr<void> Internals::setPageScaleFactor(float scaleFactor, int x, int y)
2043 Document* document = contextDocument();
2044 if (!document || !document->page())
2045 return Exception { INVALID_ACCESS_ERR };
2047 document->page()->setPageScaleFactor(scaleFactor, IntPoint(x, y));
2051 ExceptionOr<void> Internals::setPageZoomFactor(float zoomFactor)
2053 Document* document = contextDocument();
2054 if (!document || !document->frame())
2055 return Exception { INVALID_ACCESS_ERR };
2057 document->frame()->setPageZoomFactor(zoomFactor);
2061 ExceptionOr<void> Internals::setTextZoomFactor(float zoomFactor)
2063 Document* document = contextDocument();
2064 if (!document || !document->frame())
2065 return Exception { INVALID_ACCESS_ERR };
2067 document->frame()->setTextZoomFactor(zoomFactor);
2071 ExceptionOr<void> Internals::setUseFixedLayout(bool useFixedLayout)
2073 Document* document = contextDocument();
2074 if (!document || !document->view())
2075 return Exception { INVALID_ACCESS_ERR };
2077 document->view()->setUseFixedLayout(useFixedLayout);
2081 ExceptionOr<void> Internals::setFixedLayoutSize(int width, int height)
2083 Document* document = contextDocument();
2084 if (!document || !document->view())
2085 return Exception { INVALID_ACCESS_ERR };
2087 document->view()->setFixedLayoutSize(IntSize(width, height));
2091 ExceptionOr<void> Internals::setViewExposedRect(float x, float y, float width, float height)
2093 Document* document = contextDocument();
2094 if (!document || !document->view())
2095 return Exception { INVALID_ACCESS_ERR };
2097 document->view()->setViewExposedRect(FloatRect(x, y, width, height));
2101 void Internals::setHeaderHeight(float height)
2103 Document* document = contextDocument();
2104 if (!document || !document->view())
2107 document->view()->setHeaderHeight(height);
2110 void Internals::setFooterHeight(float height)
2112 Document* document = contextDocument();
2113 if (!document || !document->view())
2116 document->view()->setFooterHeight(height);
2119 void Internals::setTopContentInset(float contentInset)
2121 Document* document = contextDocument();
2122 if (!document || !document->page())
2125 document->page()->setTopContentInset(contentInset);
2128 #if ENABLE(FULLSCREEN_API)
2130 void Internals::webkitWillEnterFullScreenForElement(Element& element)
2132 Document* document = contextDocument();
2135 document->webkitWillEnterFullScreenForElement(&element);
2138 void Internals::webkitDidEnterFullScreenForElement(Element& element)
2140 Document* document = contextDocument();
2143 document->webkitDidEnterFullScreenForElement(&element);
2146 void Internals::webkitWillExitFullScreenForElement(Element& element)
2148 Document* document = contextDocument();
2151 document->webkitWillExitFullScreenForElement(&element);
2154 void Internals::webkitDidExitFullScreenForElement(Element& element)
2156 Document* document = contextDocument();
2159 document->webkitDidExitFullScreenForElement(&element);
2164 void Internals::setApplicationCacheOriginQuota(unsigned long long quota)
2166 Document* document = contextDocument();
2167 if (!document || !document->page())
2169 document->page()->applicationCacheStorage().storeUpdatedQuotaForOrigin(document->securityOrigin(), quota);
2172 void Internals::registerURLSchemeAsBypassingContentSecurityPolicy(const String& scheme)
2174 SchemeRegistry::registerURLSchemeAsBypassingContentSecurityPolicy(scheme);
2177 void Internals::removeURLSchemeRegisteredAsBypassingContentSecurityPolicy(const String& scheme)
2179 SchemeRegistry::removeURLSchemeRegisteredAsBypassingContentSecurityPolicy(scheme);
2182 Ref<MallocStatistics> Internals::mallocStatistics() const
2184 return MallocStatistics::create();
2187 Ref<TypeConversions> Internals::typeConversions() const
2189 return TypeConversions::create();
2192 Ref<MemoryInfo> Internals::memoryInfo() const
2194 return MemoryInfo::create();
2197 Vector<String> Internals::getReferencedFilePaths() const
2199 frame()->loader().history().saveDocumentAndScrollState();
2200 return FormController::getReferencedFilePaths(frame()->loader().history().currentItem()->documentState());
2203 ExceptionOr<void> Internals::startTrackingRepaints()
2205 Document* document = contextDocument();
2206 if (!document || !document->view())
2207 return Exception { INVALID_ACCESS_ERR };
2209 document->view()->setTracksRepaints(true);
2213 ExceptionOr<void> Internals::stopTrackingRepaints()
2215 Document* document = contextDocument();
2216 if (!document || !document->view())
2217 return Exception { INVALID_ACCESS_ERR };
2219 document->view()->setTracksRepaints(false);
2223 ExceptionOr<void> Internals::startTrackingLayerFlushes()
2225 Document* document = contextDocument();
2226 if (!document || !document->renderView())
2227 return Exception { INVALID_ACCESS_ERR };
2229 document->renderView()->compositor().startTrackingLayerFlushes();
2233 ExceptionOr<unsigned> Internals::layerFlushCount()
2235 Document* document = contextDocument();
2236 if (!document || !document->renderView())
2237 return Exception { INVALID_ACCESS_ERR };
2239 return document->renderView()->compositor().layerFlushCount();
2242 ExceptionOr<void> Internals::startTrackingStyleRecalcs()
2244 Document* document = contextDocument();
2246 return Exception { INVALID_ACCESS_ERR };
2248 document->startTrackingStyleRecalcs();
2252 ExceptionOr<unsigned> Internals::styleRecalcCount()
2254 Document* document = contextDocument();
2256 return Exception { INVALID_ACCESS_ERR };
2258 return document->styleRecalcCount();
2261 unsigned Internals::lastStyleUpdateSize() const
2263 Document* document = contextDocument();
2266 return document->lastStyleUpdateSizeForTesting();
2269 ExceptionOr<void> Internals::startTrackingCompositingUpdates()
2271 Document* document = contextDocument();
2272 if (!document || !document->renderView())
2273 return Exception { INVALID_ACCESS_ERR };
2275 document->renderView()->compositor().startTrackingCompositingUpdates();
2279 ExceptionOr<unsigned> Internals::compositingUpdateCount()
2281 Document* document = contextDocument();
2282 if (!document || !document->renderView())
2283 return Exception { INVALID_ACCESS_ERR };
2285 return document->renderView()->compositor().compositingUpdateCount();
2288 ExceptionOr<void> Internals::updateLayoutIgnorePendingStylesheetsAndRunPostLayoutTasks(Node* node)
2292 document = contextDocument();
2293 else if (is<Document>(*node))
2294 document = downcast<Document>(node);
2295 else if (is<HTMLIFrameElement>(*node))
2296 document = downcast<HTMLIFrameElement>(*node).contentDocument();
2298 return Exception { TypeError };
2300 document->updateLayoutIgnorePendingStylesheets(Document::RunPostLayoutTasks::Synchronously);
2304 unsigned Internals::layoutCount() const
2306 Document* document = contextDocument();
2307 if (!document || !document->view())
2309 return document->view()->layoutCount();
2313 static const char* cursorTypeToString(Cursor::Type cursorType)
2315 switch (cursorType) {
2316 case Cursor::Pointer: return "Pointer";
2317 case Cursor::Cross: return "Cross";
2318 case Cursor::Hand: return "Hand";
2319 case Cursor::IBeam: return "IBeam";
2320 case Cursor::Wait: return "Wait";
2321 case Cursor::Help: return "Help";
2322 case Cursor::EastResize: return "EastResize";
2323 case Cursor::NorthResize: return "NorthResize";
2324 case Cursor::NorthEastResize: return "NorthEastResize";
2325 case Cursor::NorthWestResize: return "NorthWestResize";
2326 case Cursor::SouthResize: return "SouthResize";
2327 case Cursor::SouthEastResize: return "SouthEastResize";
2328 case Cursor::SouthWestResize: return "SouthWestResize";
2329 case Cursor::WestResize: return "WestResize";
2330 case Cursor::NorthSouthResize: return "NorthSouthResize";
2331 case Cursor::EastWestResize: return "EastWestResize";
2332 case Cursor::NorthEastSouthWestResize: return "NorthEastSouthWestResize";
2333 case Cursor::NorthWestSouthEastResize: return "NorthWestSouthEastResize";
2334 case Cursor::ColumnResize: return "ColumnResize";
2335 case Cursor::RowResize: return "RowResize";
2336 case Cursor::MiddlePanning: return "MiddlePanning";
2337 case Cursor::EastPanning: return "EastPanning";
2338 case Cursor::NorthPanning: return "NorthPanning";
2339 case Cursor::NorthEastPanning: return "NorthEastPanning";
2340 case Cursor::NorthWestPanning: return "NorthWestPanning";
2341 case Cursor::SouthPanning: return "SouthPanning";
2342 case Cursor::SouthEastPanning: return "SouthEastPanning";
2343 case Cursor::SouthWestPanning: return "SouthWestPanning";
2344 case Cursor::WestPanning: return "WestPanning";
2345 case Cursor::Move: return "Move";
2346 case Cursor::VerticalText: return "VerticalText";
2347 case Cursor::Cell: return "Cell";
2348 case Cursor::ContextMenu: return "ContextMenu";
2349 case Cursor::Alias: return "Alias";
2350 case Cursor::Progress: return "Progress";
2351 case Cursor::NoDrop: return "NoDrop";
2352 case Cursor::Copy: return "Copy";
2353 case Cursor::None: return "None";
2354 case Cursor::NotAllowed: return "NotAllowed";
2355 case Cursor::ZoomIn: return "ZoomIn";
2356 case Cursor::ZoomOut: return "ZoomOut";
2357 case Cursor::Grab: return "Grab";
2358 case Cursor::Grabbing: return "Grabbing";
2359 case Cursor::Custom: return "Custom";
2362 ASSERT_NOT_REACHED();
2367 ExceptionOr<String> Internals::getCurrentCursorInfo()
2369 Document* document = contextDocument();
2370 if (!document || !document->frame())
2371 return Exception { INVALID_ACCESS_ERR };
2374 Cursor cursor = document->frame()->eventHandler().currentMouseCursor();
2376 StringBuilder result;
2377 result.appendLiteral("type=");
2378 result.append(cursorTypeToString(cursor.type()));
2379 result.appendLiteral(" hotSpot=");
2380 result.appendNumber(cursor.hotSpot().x());
2382 result.appendNumber(cursor.hotSpot().y());
2383 if (cursor.image()) {
2384 FloatSize size = cursor.image()->size();
2385 result.appendLiteral(" image=");
2386 result.appendNumber(size.width());
2388 result.appendNumber(size.height());
2390 #if ENABLE(MOUSE_CURSOR_SCALE)
2391 if (cursor.imageScaleFactor() != 1) {
2392 result.appendLiteral(" scale=");
2393 NumberToStringBuffer buffer;
2394 result.append(numberToFixedPrecisionString(cursor.imageScaleFactor(), 8, buffer, true));
2397 return result.toString();
2399 return String { "FAIL: Cursor details not available on this platform." };
2403 RefPtr<ArrayBuffer> Internals::serializeObject(PassRefPtr<SerializedScriptValue> value) const
2405 auto& bytes = value->data();
2406 return ArrayBuffer::create(bytes.data(), bytes.size());
2409 RefPtr<SerializedScriptValue> Internals::deserializeBuffer(ArrayBuffer& buffer) const
2411 Vector<uint8_t> bytes;
2412 bytes.append(static_cast<const uint8_t*>(buffer.data()), buffer.byteLength());
2413 return SerializedScriptValue::adopt(WTFMove(bytes));
2416 bool Internals::isFromCurrentWorld(JSC::JSValue value) const
2419 JSC::ExecState& state = *contextDocument()->vm().topCallFrame;
2420 return !value.isObject() || &worldForDOMObject(asObject(value)) == ¤tWorld(&state);
2423 void Internals::setUsesOverlayScrollbars(bool enabled)
2425 WebCore::Settings::setUsesOverlayScrollbars(enabled);
2428 void Internals::setUsesMockScrollAnimator(bool enabled)
2430 WebCore::Settings::setUsesMockScrollAnimator(enabled);
2433 void Internals::forceReload(bool endToEnd)
2435 frame()->loader().reload(endToEnd);
2438 void Internals::enableAutoSizeMode(bool enabled, int minimumWidth, int minimumHeight, int maximumWidth, int maximumHeight)
2440 Document* document = contextDocument();
2441 if (!document || !document->view())
2443 document->view()->enableAutoSizeMode(enabled, IntSize(minimumWidth, minimumHeight), IntSize(maximumWidth, maximumHeight));
2446 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
2447 void Internals::initializeMockCDM()
2449 CDM::registerCDMFactory([](CDM* cdm) { return std::make_unique<MockCDM>(cdm); },
2450 MockCDM::supportsKeySystem, MockCDM::supportsKeySystemAndMimeType);
2454 String Internals::markerTextForListItem(Element& element)
2456 return WebCore::markerTextForListItem(&element);
2459 String Internals::toolTipFromElement(Element& element) const
2461 HitTestResult result;
2462 result.setInnerNode(&element);
2463 TextDirection direction;
2464 return result.title(direction);
2467 String Internals::getImageSourceURL(Element& element)
2469 return element.imageSourceURL();
2474 void Internals::simulateAudioInterruption(HTMLMediaElement& element)
2477 element.player()->simulateAudioInterruption();
2479 UNUSED_PARAM(element);
2483 ExceptionOr<bool> Internals::mediaElementHasCharacteristic(HTMLMediaElement& element, const String& characteristic)
2485 if (equalLettersIgnoringASCIICase(characteristic, "audible"))
2486 return element.hasAudio();
2487 if (equalLettersIgnoringASCIICase(characteristic, "visual"))
2488 return element.hasVideo();
2489 if (equalLettersIgnoringASCIICase(characteristic, "legible"))
2490 return element.hasClosedCaptions();
2492 return Exception { SYNTAX_ERR };
2497 bool Internals::isSelectPopupVisible(HTMLSelectElement& element)
2499 auto* renderer = element.renderer();
2501 if (!is<RenderMenuList>(*renderer))
2505 return downcast<RenderMenuList>(*renderer).popupIsVisible();
2511 ExceptionOr<String> Internals::captionsStyleSheetOverride()
2513 Document* document = contextDocument();
2514 if (!document || !document->page())
2515 return Exception { INVALID_ACCESS_ERR };
2517 #if ENABLE(VIDEO_TRACK)
2518 return document->page()->group().captionPreferences().captionsStyleSheetOverride();
2520 return emptyString();
2524 ExceptionOr<void> Internals::setCaptionsStyleSheetOverride(const String& override)
2526 Document* document = contextDocument();
2527 if (!document || !document->page())
2528 return Exception { INVALID_ACCESS_ERR };
2530 #if ENABLE(VIDEO_TRACK)
2531 document->page()->group().captionPreferences().setCaptionsStyleSheetOverride(override);
2533 UNUSED_PARAM(override);
2538 ExceptionOr<void> Internals::setPrimaryAudioTrackLanguageOverride(const String& language)
2540 Document* document = contextDocument();
2541 if (!document || !document->page())
2542 return Exception { INVALID_ACCESS_ERR };
2544 #if ENABLE(VIDEO_TRACK)
2545 document->page()->group().captionPreferences().setPrimaryAudioTrackLanguageOverride(language);
2547 UNUSED_PARAM(language);
2552 ExceptionOr<void> Internals::setCaptionDisplayMode(const String& mode)
2554 Document* document = contextDocument();
2555 if (!document || !document->page())
2556 return Exception { INVALID_ACCESS_ERR };
2558 #if ENABLE(VIDEO_TRACK)
2559 auto& captionPreferences = document->page()->group().captionPreferences();
2561 if (equalLettersIgnoringASCIICase(mode, "automatic"))
2562 captionPreferences.setCaptionDisplayMode(CaptionUserPreferences::Automatic);
2563 else if (equalLettersIgnoringASCIICase(mode, "forcedonly"))
2564 captionPreferences.setCaptionDisplayMode(CaptionUserPreferences::ForcedOnly);
2565 else if (equalLettersIgnoringASCIICase(mode, "alwayson"))
2566 captionPreferences.setCaptionDisplayMode(CaptionUserPreferences::AlwaysOn);
2567 else if (equalLettersIgnoringASCIICase(mode, "manual"))
2568 captionPreferences.setCaptionDisplayMode(CaptionUserPreferences::Manual);
2570 return Exception { SYNTAX_ERR };
2579 Ref<TimeRanges> Internals::createTimeRanges(Float32Array& startTimes, Float32Array& endTimes)
2581 ASSERT(startTimes.length() == endTimes.length());
2582 Ref<TimeRanges> ranges = TimeRanges::create();
2584 unsigned count = std::min(startTimes.length(), endTimes.length());
2585 for (unsigned i = 0; i < count; ++i)
2586 ranges->add(startTimes.item(i), endTimes.item(i));
2590 double Internals::closestTimeToTimeRanges(double time, TimeRanges& ranges)
2592 return ranges.nearest(time);
2597 ExceptionOr<Ref<ClientRect>> Internals::selectionBounds()
2599 Document* document = contextDocument();
2600 if (!document || !document->frame())
2601 return Exception { INVALID_ACCESS_ERR };
2603 return ClientRect::create(document->frame()->selection().selectionBounds());
2606 #if ENABLE(VIBRATION)
2608 bool Internals::isVibrating()
2610 auto* document = contextDocument();
2611 auto* page = document ? document->page() : nullptr;
2612 return page && Vibration::from(page)->isVibrating();
2617 ExceptionOr<bool> Internals::isPluginUnavailabilityIndicatorObscured(Element& element)
2619 auto* renderer = element.renderer();
2620 if (!is<RenderEmbeddedObject>(renderer))
2621 return Exception { INVALID_ACCESS_ERR };
2623 return downcast<RenderEmbeddedObject>(*renderer).isReplacementObscured();
2626 bool Internals::isPluginSnapshotted(Element& element)
2628 return is<HTMLPlugInElement>(element) && downcast<HTMLPlugInElement>(element).displayState() <= HTMLPlugInElement::DisplayingSnapshot;
2631 #if ENABLE(MEDIA_SOURCE)
2633 void Internals::initializeMockMediaSource()
2635 #if USE(AVFOUNDATION)
2636 WebCore::Settings::setAVFoundationEnabled(false);
2638 MediaPlayerFactorySupport::callRegisterMediaEngine(MockMediaPlayerMediaSource::registerMediaEngine);
2641 Vector<String> Internals::bufferedSamplesForTrackID(SourceBuffer& buffer, const AtomicString& trackID)
2643 return buffer.bufferedSamplesForTrackID(trackID);
2646 Vector<String> Internals::enqueuedSamplesForTrackID(SourceBuffer& buffer, const AtomicString& trackID)
2648 return buffer.enqueuedSamplesForTrackID(trackID);
2651 void Internals::setShouldGenerateTimestamps(SourceBuffer& buffer, bool flag)
2653 buffer.setShouldGenerateTimestamps(flag);
2660 ExceptionOr<void> Internals::beginMediaSessionInterruption(const String& interruptionString)
2662 PlatformMediaSession::InterruptionType interruption = PlatformMediaSession::SystemInterruption;
2664 if (equalLettersIgnoringASCIICase(interruptionString, "system"))
2665 interruption = PlatformMediaSession::SystemInterruption;
2666 else if (equalLettersIgnoringASCIICase(interruptionString, "systemsleep"))
2667 interruption = PlatformMediaSession::SystemSleep;
2668 else if (equalLettersIgnoringASCIICase(interruptionString, "enteringbackground"))
2669 interruption = PlatformMediaSession::EnteringBackground;
2670 else if (equalLettersIgnoringASCIICase(interruptionString, "suspendedunderlock"))
2671 interruption = PlatformMediaSession::SuspendedUnderLock;
2673 return Exception { INVALID_ACCESS_ERR };
2675 PlatformMediaSessionManager::sharedManager().beginInterruption(interruption);
2679 void Internals::endMediaSessionInterruption(const String& flagsString)
2681 PlatformMediaSession::EndInterruptionFlags flags = PlatformMediaSession::NoFlags;
2683 if (equalLettersIgnoringASCIICase(flagsString, "mayresumeplaying"))
2684 flags = PlatformMediaSession::MayResumePlaying;
2686 PlatformMediaSessionManager::sharedManager().endInterruption(flags);
2689 void Internals::applicationDidEnterForeground() const
2691 PlatformMediaSessionManager::sharedManager().applicationDidEnterForeground();
2694 void Internals::applicationWillEnterBackground() const
2696 PlatformMediaSessionManager::sharedManager().applicationWillEnterBackground();
2699 ExceptionOr<void> Internals::setMediaSessionRestrictions(const String& mediaTypeString, const String& restrictionsString)
2701 PlatformMediaSession::MediaType mediaType = PlatformMediaSession::None;
2702 if (equalLettersIgnoringASCIICase(mediaTypeString, "video"))
2703 mediaType = PlatformMediaSession::Video;
2704 else if (equalLettersIgnoringASCIICase(mediaTypeString, "audio"))
2705 mediaType = PlatformMediaSession::Audio;
2706 else if (equalLettersIgnoringASCIICase(mediaTypeString, "webaudio"))
2707 mediaType = PlatformMediaSession::WebAudio;
2709 return Exception { INVALID_ACCESS_ERR };
2711 PlatformMediaSessionManager::SessionRestrictions restrictions = PlatformMediaSessionManager::sharedManager().restrictions(mediaType);
2712 PlatformMediaSessionManager::sharedManager().removeRestriction(mediaType, restrictions);
2714 restrictions = PlatformMediaSessionManager::NoRestrictions;
2716 Vector<String> restrictionsArray;
2717 restrictionsString.split(',', false, restrictionsArray);
2718 for (auto& restrictionString : restrictionsArray) {
2719 if (equalLettersIgnoringASCIICase(restrictionString, "concurrentplaybacknotpermitted"))
2720 restrictions |= PlatformMediaSessionManager::ConcurrentPlaybackNotPermitted;
2721 if (equalLettersIgnoringASCIICase(restrictionString, "backgroundprocessplaybackrestricted"))
2722 restrictions |= PlatformMediaSessionManager::BackgroundProcessPlaybackRestricted;
2723 if (equalLettersIgnoringASCIICase(restrictionString, "backgroundtabplaybackrestricted"))
2724 restrictions |= PlatformMediaSessionManager::BackgroundTabPlaybackRestricted;
2725 if (equalLettersIgnoringASCIICase(restrictionString, "interruptedplaybacknotpermitted"))
2726 restrictions |= PlatformMediaSessionManager::InterruptedPlaybackNotPermitted;
2728 PlatformMediaSessionManager::sharedManager().addRestriction(mediaType, restrictions);
2732 void Internals::setMediaElementRestrictions(HTMLMediaElement& element, const String& restrictionsString)
2734 MediaElementSession::BehaviorRestrictions restrictions = element.mediaSession().behaviorRestrictions();
2735 element.mediaSession().removeBehaviorRestriction(restrictions);
2737 restrictions = MediaElementSession::NoRestrictions;
2739 Vector<String> restrictionsArray;
2740 restrictionsString.split(',', false, restrictionsArray);
2741 for (auto& restrictionString : restrictionsArray) {
2742 if (equalLettersIgnoringASCIICase(restrictionString, "norestrictions"))
2743 restrictions |= MediaElementSession::NoRestrictions;
2744 if (equalLettersIgnoringASCIICase(restrictionString, "requireusergestureforload"))
2745 restrictions |= MediaElementSession::RequireUserGestureForLoad;
2746 if (equalLettersIgnoringASCIICase(restrictionString, "requireusergestureforvideoratechange"))
2747 restrictions |= MediaElementSession::RequireUserGestureForVideoRateChange;
2748 if (equalLettersIgnoringASCIICase(restrictionString, "requireusergestureforfullscreen"))
2749 restrictions |= MediaElementSession::RequireUserGestureForFullscreen;
2750 if (equalLettersIgnoringASCIICase(restrictionString, "requirepageconsenttoloadmedia"))
2751 restrictions |= MediaElementSession::RequirePageConsentToLoadMedia;
2752 if (equalLettersIgnoringASCIICase(restrictionString, "requirepageconsenttoresumemedia"))
2753 restrictions |= MediaElementSession::RequirePageConsentToResumeMedia;
2754 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2755 if (equalLettersIgnoringASCIICase(restrictionString, "requireusergesturetoshowplaybacktargetpicker"))
2756 restrictions |= MediaElementSession::RequireUserGestureToShowPlaybackTargetPicker;
2757 if (equalLettersIgnoringASCIICase(restrictionString, "wirelessvideoplaybackdisabled"))
2758 restrictions |= MediaElementSession::WirelessVideoPlaybackDisabled;
2760 if (equalLettersIgnoringASCIICase(restrictionString, "requireusergestureforaudioratechange"))
2761 restrictions |= MediaElementSession::RequireUserGestureForAudioRateChange;
2762 if (equalLettersIgnoringASCIICase(restrictionString, "metadatapreloadingnotpermitted"))
2763 restrictions |= MediaElementSession::MetadataPreloadingNotPermitted;
2764 if (equalLettersIgnoringASCIICase(restrictionString, "autopreloadingnotpermitted"))
2765 restrictions |= MediaElementSession::AutoPreloadingNotPermitted;
2766 if (equalLettersIgnoringASCIICase(restrictionString, "invisibleautoplaynotpermitted"))
2767 restrictions |= MediaElementSession::InvisibleAutoplayNotPermitted;
2768 if (equalLettersIgnoringASCIICase(restrictionString, "overrideusergesturerequirementformaincontent"))
2769 restrictions |= MediaElementSession::OverrideUserGestureRequirementForMainContent;
2771 element.mediaSession().addBehaviorRestriction(restrictions);
2774 ExceptionOr<void> Internals::postRemoteControlCommand(const String& commandString, float argument)
2776 PlatformMediaSession::RemoteControlCommandType command;
2777 PlatformMediaSession::RemoteCommandArgument parameter { argument };
2779 if (equalLettersIgnoringASCIICase(commandString, "play"))
2780 command = PlatformMediaSession::PlayCommand;
2781 else if (equalLettersIgnoringASCIICase(commandString, "pause"))
2782 command = PlatformMediaSession::PauseCommand;
2783 else if (equalLettersIgnoringASCIICase(commandString, "stop"))
2784 command = PlatformMediaSession::StopCommand;
2785 else if (equalLettersIgnoringASCIICase(commandString, "toggleplaypause"))
2786 command = PlatformMediaSession::TogglePlayPauseCommand;
2787 else if (equalLettersIgnoringASCIICase(commandString, "beginseekingbackward"))
2788 command = PlatformMediaSession::BeginSeekingBackwardCommand;
2789 else if (equalLettersIgnoringASCIICase(commandString, "endseekingbackward"))
2790 command = PlatformMediaSession::EndSeekingBackwardCommand;
2791 else if (equalLettersIgnoringASCIICase(commandString, "beginseekingforward"))
2792 command = PlatformMediaSession::BeginSeekingForwardCommand;
2793 else if (equalLettersIgnoringASCIICase(commandString, "endseekingforward"))
2794 command = PlatformMediaSession::EndSeekingForwardCommand;
2795 else if (equalLettersIgnoringASCIICase(commandString, "seektoplaybackposition"))
2796 command = PlatformMediaSession::SeekToPlaybackPositionCommand;
2798 return Exception { INVALID_ACCESS_ERR };
2800 PlatformMediaSessionManager::sharedManager().didReceiveRemoteControlCommand(command, ¶meter);
2804 bool Internals::elementIsBlockingDisplaySleep(HTMLMediaElement& element) const
2806 return element.isDisablingSleep();
2809 #endif // ENABLE(VIDEO)
2811 #if ENABLE(MEDIA_SESSION)
2813 void Internals::sendMediaSessionStartOfInterruptionNotification(MediaSessionInterruptingCategory category)
2815 MediaSessionManager::singleton().didReceiveStartOfInterruptionNotification(category);
2818 void Internals::sendMediaSessionEndOfInterruptionNotification(MediaSessionInterruptingCategory category)
2820 MediaSessionManager::singleton().didReceiveEndOfInterruptionNotification(category);
2823 String Internals::mediaSessionCurrentState(MediaSession* session) const
2825 switch (session->currentState()) {
2826 case MediaSession::State::Active:
2828 case MediaSession::State::Interrupted:
2829 return "interrupted";
2830 case MediaSession::State::Idle:
2835 double Internals::mediaElementPlayerVolume(HTMLMediaElement* element) const
2837 ASSERT_ARG(element, element);
2838 return element->playerVolume();
2841 void Internals::sendMediaControlEvent(MediaControlEvent event)
2843 // FIXME: No good reason to use a single function with an argument instead of three functions.
2845 case MediControlEvent::PlayPause:
2846 MediaSessionManager::singleton().togglePlayback();
2848 case MediControlEvent::NextTrack:
2849 MediaSessionManager::singleton().skipToNextTrack();
2851 case MediControlEvent::PreviousTrack:
2852 MediaSessionManager::singleton().skipToPreviousTrack();
2857 #endif // ENABLE(MEDIA_SESSION)
2859 #if ENABLE(WEB_AUDIO)
2861 void Internals::setAudioContextRestrictions(AudioContext& context, const String& restrictionsString)
2863 AudioContext::BehaviorRestrictions restrictions = context.behaviorRestrictions();
2864 context.removeBehaviorRestriction(restrictions);
2866 restrictions = AudioContext::NoRestrictions;
2868 Vector<String> restrictionsArray;
2869 restrictionsString.split(',', false, restrictionsArray);
2870 for (auto& restrictionString : restrictionsArray) {
2871 if (equalLettersIgnoringASCIICase(restrictionString, "norestrictions"))
2872 restrictions |= AudioContext::NoRestrictions;
2873 if (equalLettersIgnoringASCIICase(restrictionString, "requireusergestureforaudiostart"))
2874 restrictions |= AudioContext::RequireUserGestureForAudioStartRestriction;
2875 if (equalLettersIgnoringASCIICase(restrictionString, "requirepageconsentforaudiostart"))
2876 restrictions |= AudioContext::RequirePageConsentForAudioStartRestriction;
2878 context.addBehaviorRestriction(restrictions);
2883 void Internals::simulateSystemSleep() const
2886 PlatformMediaSessionManager::sharedManager().systemWillSleep();
2890 void Internals::simulateSystemWake() const
2893 PlatformMediaSessionManager::sharedManager().systemDidWake();
2897 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2899 void Internals::setMockMediaPlaybackTargetPickerEnabled(bool enabled)
2901 Page* page = contextDocument()->frame()->page();
2904 page->setMockMediaPlaybackTargetPickerEnabled(enabled);
2907 ExceptionOr<void> Internals::setMockMediaPlaybackTargetPickerState(const String& deviceName, const String& deviceState)
2909 Page* page = contextDocument()->frame()->page();
2912 MediaPlaybackTargetContext::State state = MediaPlaybackTargetContext::Unknown;
2914 if (equalLettersIgnoringASCIICase(deviceState, "deviceavailable"))
2915 state = MediaPlaybackTargetContext::OutputDeviceAvailable;
2916 else if (equalLettersIgnoringASCIICase(deviceState, "deviceunavailable"))
2917 state = MediaPlaybackTargetContext::OutputDeviceUnavailable;
2918 else if (equalLettersIgnoringASCIICase(deviceState, "unknown"))
2919 state = MediaPlaybackTargetContext::Unknown;
2921 return Exception { INVALID_ACCESS_ERR };
2923 page->setMockMediaPlaybackTargetPickerState(deviceName, state);
2929 ExceptionOr<Ref<MockPageOverlay>> Internals::installMockPageOverlay(PageOverlayType type)
2931 Document* document = contextDocument();
2932 if (!document || !document->frame())
2933 return Exception { INVALID_ACCESS_ERR };
2935 return MockPageOverlayClient::singleton().installOverlay(document->frame()->mainFrame(), type == PageOverlayType::View ? PageOverlay::OverlayType::View : PageOverlay::OverlayType::Document);
2938 ExceptionOr<String> Internals::pageOverlayLayerTreeAsText() const
2940 Document* document = contextDocument();
2941 if (!document || !document->frame())
2942 return Exception { INVALID_ACCESS_ERR };
2944 document->updateLayout();
2946 return MockPageOverlayClient::singleton().layerTreeAsText(document->frame()->mainFrame());
2949 void Internals::setPageMuted(const String& states)
2951 Document* document = contextDocument();
2955 WebCore::MediaProducer::MutedStateFlags state = MediaProducer::NoneMuted;
2956 Vector<String> stateString;
2957 states.split(',', false, stateString);
2958 for (auto& muteString : stateString) {
2959 if (equalLettersIgnoringASCIICase(muteString, "audio"))
2960 state |= MediaProducer::AudioIsMuted;
2961 if (equalLettersIgnoringASCIICase(muteString, "capturedevices"))
2962 state |= MediaProducer::CaptureDevicesAreMuted;
2965 if (Page* page = document->page())
2966 page->setMuted(state);
2969 String Internals::pageMediaState()
2971 Document* document = contextDocument();
2972 if (!document || !document->page())
2973 return emptyString();
2975 WebCore::MediaProducer::MediaStateFlags state = document->page()->mediaState();
2976 StringBuilder string;
2977 if (state & MediaProducer::IsPlayingAudio)
2978 string.append("IsPlayingAudio,");
2979 if (state & MediaProducer::IsPlayingVideo)
2980 string.append("IsPlayingVideo,");
2981 if (state & MediaProducer::IsPlayingToExternalDevice)
2982 string.append("IsPlayingToExternalDevice,");
2983 if (state & MediaProducer::RequiresPlaybackTargetMonitoring)
2984 string.append("RequiresPlaybackTargetMonitoring,");
2985 if (state & MediaProducer::ExternalDeviceAutoPlayCandidate)
2986 string.append("ExternalDeviceAutoPlayCandidate,");
2987 if (state & MediaProducer::DidPlayToEnd)
2988 string.append("DidPlayToEnd,");
2989 if (state & MediaProducer::IsSourceElementPlaying)
2990 string.append("IsSourceElementPlaying,");
2992 if (state & MediaProducer::IsNextTrackControlEnabled)
2993 string.append("IsNextTrackControlEnabled,");
2994 if (state & MediaProducer::IsPreviousTrackControlEnabled)
2995 string.append("IsPreviousTrackControlEnabled,");
2997 if (state & MediaProducer::HasPlaybackTargetAvailabilityListener)
2998 string.append("HasPlaybackTargetAvailabilityListener,");
2999 if (state & MediaProducer::HasAudioOrVideo)
3000 string.append("HasAudioOrVideo,");
3001 if (state & MediaProducer::HasActiveMediaCaptureDevice)
3002 string.append("HasActiveMediaCaptureDevice,");
3003 if (state & MediaProducer::HasMediaCaptureDevice)
3004 string.append("HasMediaCaptureDevice,");
3006 if (string.isEmpty())
3007 string.append("IsNotPlaying");
3009 string.resize(string.length() - 1);
3011 return string.toString();
3014 void Internals::setPageDefersLoading(bool defersLoading)
3016 Document* document = contextDocument();
3019 if (Page* page = document->page())
3020 page->setDefersLoading(defersLoading);
3023 RefPtr<File> Internals::createFile(const String& path)
3025 Document* document = contextDocument();
3029 URL url = document->completeURL(path);
3030 if (!url.isLocalFile())
3033 return File::create(url.fileSystemPath());
3036 void Internals::queueMicroTask(int testNumber)
3038 Document* document = contextDocument();
3042 auto microtask = std::make_unique<ActiveDOMCallbackMicrotask>(MicrotaskQueue::mainThreadQueue(), *document, [document, testNumber]() {
3043 document->addConsoleMessage(MessageSource::JS, MessageLevel::Debug, makeString("MicroTask #", String::number(testNumber), " has run."));
3046 MicrotaskQueue::mainThreadQueue().append(WTFMove(microtask));
3049 #if ENABLE(CONTENT_FILTERING)
3051 MockContentFilterSettings& Internals::mockContentFilterSettings()
3053 return MockContentFilterSettings::singleton();
3058 #if ENABLE(CSS_SCROLL_SNAP)
3060 static void appendOffsets(StringBuilder& builder, const Vector<LayoutUnit>& snapOffsets)
3062 bool justStarting = true;
3064 builder.appendLiteral("{ ");
3065 for (auto& coordinate : snapOffsets) {
3067 builder.appendLiteral(", ");
3069 justStarting = false;
3071 builder.append(String::number(coordinate.toUnsigned()));
3073 builder.appendLiteral(" }");
3076 ExceptionOr<String> Internals::scrollSnapOffsets(Element& element)
3078 if (!element.renderBox())
3081 RenderBox& box = *element.renderBox();
3082 ScrollableArea* scrollableArea;
3085 FrameView* frameView = box.frame().mainFrame().view();
3086 if (!frameView || !frameView->isScrollable())
3087 return Exception { INVALID_ACCESS_ERR };
3088 scrollableArea = frameView;
3091 if (!box.canBeScrolledAndHasScrollableArea())
3092 return Exception { INVALID_ACCESS_ERR };
3093 scrollableArea = box.layer();
3096 if (!scrollableArea)
3099 StringBuilder result;
3101 if (scrollableArea->horizontalSnapOffsets()) {
3102 result.appendLiteral("horizontal = ");
3103 appendOffsets(result, *scrollableArea->horizontalSnapOffsets());
3106 if (scrollableArea->verticalSnapOffsets()) {
3107 if (result.length())
3108 result.appendLiteral(", ");
3110 result.appendLiteral("vertical = ");
3111 appendOffsets(result, *scrollableArea->verticalSnapOffsets());
3114 return result.toString();
3119 bool Internals::testPreloaderSettingViewport()
3121 return testPreloadScannerViewportSupport(contextDocument());
3124 ExceptionOr<String> Internals::pathStringWithShrinkWrappedRects(const Vector<double>& rectComponents, double radius)
3126 if (rectComponents.size() % 4)
3127 return Exception { INVALID_ACCESS_ERR };
3129 Vector<FloatRect> rects;
3130 for (unsigned i = 0; i < rectComponents.size(); i += 4)
3131 rects.append(FloatRect(rectComponents[i], rectComponents[i + 1], rectComponents[i + 2], rectComponents[i + 3]));
3133 SVGPathStringBuilder builder;
3134 PathUtilities::pathWithShrinkWrappedRects(rects, radius).apply([&builder](const PathElement& element) {
3135 switch (element.type) {
3136 case PathElementMoveToPoint:
3137 builder.moveTo(element.points[0], false, AbsoluteCoordinates);
3139 case PathElementAddLineToPoint:
3140 builder.lineTo(element.points[0], AbsoluteCoordinates);
3142 case PathElementAddQuadCurveToPoint:
3143 builder.curveToQuadratic(element.points[0], element.points[1], AbsoluteCoordinates);
3145 case PathElementAddCurveToPoint:
3146 builder.curveToCubic(element.points[0], element.points[1], element.points[2], AbsoluteCoordinates);
3148 case PathElementCloseSubpath:
3149 builder.closePath();
3152 ASSERT_NOT_REACHED();
3154 return builder.result();
3158 String Internals::getCurrentMediaControlsStatusForElement(HTMLMediaElement& mediaElement)
3160 #if !ENABLE(MEDIA_CONTROLS_SCRIPT)
3161 UNUSED_PARAM(mediaElement);
3164 return mediaElement.getCurrentMediaControlsStatus();
3168 #if !PLATFORM(COCOA)
3170 String Internals::userVisibleString(const DOMURL&)
3172 // Cocoa-specific function. Could ASSERT_NOT_REACHED, but that's probably overkill.
3178 void Internals::setShowAllPlugins(bool show)
3180 Document* document = contextDocument();
3184 Page* page = document->page();
3188 page->setShowAllPlugins(show);
3191 #if ENABLE(READABLE_STREAM_API)
3193 bool Internals::isReadableStreamDisturbed(JSC::ExecState& state, JSValue stream)
3195 JSGlobalObject* globalObject = state.vmEntryGlobalObject();
3196 JSVMClientData* clientData = static_cast<JSVMClientData*>(state.vm().clientData);
3197 const Identifier& privateName = clientData->builtinFunctions().readableStreamInternalsBuiltins().isReadableStreamDisturbedPrivateName();
3199 PropertySlot propertySlot(value, PropertySlot::InternalMethodType::Get);
3200 globalObject->methodTable()->getOwnPropertySlot(globalObject, &state, privateName, propertySlot);
3201 value = propertySlot.getValue(&state, privateName);
3202 ASSERT(value.isFunction());
3204 JSObject* function = value.getObject();
3206 CallType callType = JSC::getCallData(function, callData);
3207 ASSERT(callType != JSC::CallType::None);
3208 MarkedArgumentBuffer arguments;
3209 arguments.append(stream);
3210 JSValue returnedValue = JSC::call(&state, function, callType, callData, JSC::jsUndefined(), arguments);
3211 ASSERT(returnedValue.isBoolean());
3213 return returnedValue.asBoolean();
3218 String Internals::resourceLoadStatisticsForOrigin(const String& origin)
3220 return ResourceLoadObserver::sharedObserver().statisticsForOrigin(origin);
3223 void Internals::setResourceLoadStatisticsEnabled(bool enable)
3225 Settings::setResourceLoadStatisticsEnabled(enable);
3228 String Internals::composedTreeAsText(Node& node)
3230 if (!is<ContainerNode>(node))
3231 return emptyString();
3232 return WebCore::composedTreeAsText(downcast<ContainerNode>(node));
3235 void Internals::setLinkPreloadSupport(bool enable)
3237 RuntimeEnabledFeatures::sharedFeatures().setLinkPreloadEnabled(enable);
3240 #if ENABLE(CSS_GRID_LAYOUT)
3242 void Internals::setCSSGridLayoutEnabled(bool enable)
3244 RuntimeEnabledFeatures::sharedFeatures().setCSSGridLayoutEnabled(enable);
3251 bool Internals::webGL2Enabled() const
3253 return RuntimeEnabledFeatures::sharedFeatures().webGL2Enabled();
3256 void Internals::setWebGL2Enabled(bool enable)
3258 RuntimeEnabledFeatures::sharedFeatures().setWebGL2Enabled(enable);
3263 void Internals::setResourceTimingSupport(bool enable)
3265 RuntimeEnabledFeatures::sharedFeatures().setResourceTimingEnabled(enable);
3268 bool Internals::isProcessingUserGesture()
3270 return UserGestureIndicator::processingUserGesture();
3273 RefPtr<GCObservation> Internals::observeGC(JSC::JSValue value)
3275 if (!value || value.isNull() || value.isUndefined() || !value.getObject())
3278 return GCObservation::create(value.getObject());
3281 void Internals::setUserInterfaceLayoutDirection(UserInterfaceLayoutDirection userInterfaceLayoutDirection)
3283 Document* document = contextDocument();
3287 Page* page = document->page();
3291 page->setUserInterfaceLayoutDirection(userInterfaceLayoutDirection == UserInterfaceLayoutDirection::LTR ? WebCore::UserInterfaceLayoutDirection::LTR : WebCore::UserInterfaceLayoutDirection::RTL);
3294 #if !PLATFORM(COCOA)
3296 bool Internals::userPrefersReducedMotion() const
3303 } // namespace WebCore