5870de463220fe9828ef4bb176b6e0f972310e80
[WebKit-https.git] / Source / WebCore / testing / Internals.h
1 /*
2  * Copyright (C) 2012 Google Inc. All rights reserved.
3  * Copyright (C) 2013-2019 Apple Inc. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1.  Redistributions of source code must retain the above copyright
10  *     notice, this list of conditions and the following disclaimer.
11  * 2.  Redistributions in binary form must reproduce the above copyright
12  *     notice, this list of conditions and the following disclaimer in the
13  *     documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
16  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
17  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
19  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
20  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
21  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
22  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #pragma once
28
29 #include "CSSComputedStyleDeclaration.h"
30 #include "ContextDestructionObserver.h"
31 #include "Cookie.h"
32 #include "ExceptionOr.h"
33 #include "HEVCUtilities.h"
34 #include "JSDOMPromiseDeferred.h"
35 #include "OrientationNotifier.h"
36 #include "PageConsoleClient.h"
37 #include "RealtimeMediaSource.h"
38 #include "TextIndicator.h"
39 #include <JavaScriptCore/Float32Array.h>
40 #include <wtf/Optional.h>
41
42 #if ENABLE(MEDIA_SESSION)
43 #include "MediaSessionInterruptionProvider.h"
44 #endif
45
46 #if ENABLE(VIDEO)
47 #include "MediaElementSession.h"
48 #endif
49
50 namespace WebCore {
51
52 class AnimationTimeline;
53 class AudioContext;
54 class CacheStorageConnection;
55 class DOMRect;
56 class DOMRectList;
57 class DOMRectReadOnly;
58 class DOMURL;
59 class DOMWindow;
60 class Document;
61 class Element;
62 class EventListener;
63 class ExtendableEvent;
64 class FetchResponse;
65 class File;
66 class Frame;
67 class GCObservation;
68 class HTMLAnchorElement;
69 class HTMLImageElement;
70 class HTMLInputElement;
71 class HTMLLinkElement;
72 class HTMLMediaElement;
73 class HTMLPictureElement;
74 class HTMLSelectElement;
75 class ImageData;
76 class InspectorStubFrontend;
77 class InternalSettings;
78 class MallocStatistics;
79 class MediaSession;
80 class MediaStream;
81 class MediaStreamTrack;
82 class MemoryInfo;
83 class MockCDMFactory;
84 class MockContentFilterSettings;
85 class MockPageOverlay;
86 class MockPaymentCoordinator;
87 class NodeList;
88 class Page;
89 class RTCPeerConnection;
90 class Range;
91 class RenderedDocumentMarker;
92 class SVGSVGElement;
93 class SerializedScriptValue;
94 class SourceBuffer;
95 class StringCallback;
96 class StyleSheet;
97 class TimeRanges;
98 class TypeConversions;
99 class VoidCallback;
100 class WebGLRenderingContext;
101 class XMLHttpRequest;
102
103 #if ENABLE(VIDEO_TRACK)
104 class TextTrackCueGeneric;
105 #endif
106
107 #if ENABLE(SERVICE_WORKER)
108 class ServiceWorker;
109 #endif
110
111 class UnsuspendableActiveDOMObject;
112
113 class Internals final : public RefCounted<Internals>, private ContextDestructionObserver
114 #if ENABLE(MEDIA_STREAM)
115     , private RealtimeMediaSource::Observer
116 #endif
117     {
118 public:
119     static Ref<Internals> create(Document&);
120     virtual ~Internals();
121
122     static void resetToConsistentState(Page&);
123
124     ExceptionOr<String> elementRenderTreeAsText(Element&);
125     bool hasPausedImageAnimations(Element&);
126
127     bool isPaintingFrequently(Element&);
128     void incrementFrequentPaintCounter(Element&);
129
130     String address(Node&);
131     bool nodeNeedsStyleRecalc(Node&);
132     String styleChangeType(Node&);
133     String description(JSC::JSValue);
134
135     bool isPreloaded(const String& url);
136     bool isLoadingFromMemoryCache(const String& url);
137     String fetchResponseSource(FetchResponse&);
138     String xhrResponseSource(XMLHttpRequest&);
139     bool isSharingStyleSheetContents(HTMLLinkElement&, HTMLLinkElement&);
140     bool isStyleSheetLoadingSubresources(HTMLLinkElement&);
141     enum class CachePolicy { UseProtocolCachePolicy, ReloadIgnoringCacheData, ReturnCacheDataElseLoad, ReturnCacheDataDontLoad };
142     void setOverrideCachePolicy(CachePolicy);
143     ExceptionOr<void> setCanShowModalDialogOverride(bool allow);
144     enum class ResourceLoadPriority { ResourceLoadPriorityVeryLow, ResourceLoadPriorityLow, ResourceLoadPriorityMedium, ResourceLoadPriorityHigh, ResourceLoadPriorityVeryHigh };
145     void setOverrideResourceLoadPriority(ResourceLoadPriority);
146     void setStrictRawResourceValidationPolicyDisabled(bool);
147
148     void clearMemoryCache();
149     void pruneMemoryCacheToSize(unsigned size);
150     void destroyDecodedDataForAllImages();
151     unsigned memoryCacheSize() const;
152
153     unsigned imageFrameIndex(HTMLImageElement&);
154     unsigned imageFrameCount(HTMLImageElement&);
155     float imageFrameDurationAtIndex(HTMLImageElement&, unsigned index);
156     void setImageFrameDecodingDuration(HTMLImageElement&, float duration);
157     void resetImageAnimation(HTMLImageElement&);
158     bool isImageAnimating(HTMLImageElement&);
159     unsigned imagePendingDecodePromisesCountForTesting(HTMLImageElement&);
160     void setClearDecoderAfterAsyncFrameRequestForTesting(HTMLImageElement&, bool enabled);
161     unsigned imageDecodeCount(HTMLImageElement&);
162     unsigned pdfDocumentCachingCount(HTMLImageElement&);
163     void setLargeImageAsyncDecodingEnabledForTesting(HTMLImageElement&, bool enabled);
164     void setForceUpdateImageDataEnabledForTesting(HTMLImageElement&, bool enabled);
165
166     void setGridMaxTracksLimit(unsigned);
167
168     void clearPageCache();
169     unsigned pageCacheSize() const;
170     void preventDocumentForEnteringPageCache();
171
172     void disableTileSizeUpdateDelay();
173
174     void setSpeculativeTilingDelayDisabledForTesting(bool);
175
176     Ref<CSSComputedStyleDeclaration> computedStyleIncludingVisitedInfo(Element&) const;
177
178     Node* ensureUserAgentShadowRoot(Element& host);
179     Node* shadowRoot(Element& host);
180     ExceptionOr<String> shadowRootType(const Node&) const;
181     String shadowPseudoId(Element&);
182     void setShadowPseudoId(Element&, const String&);
183
184     // CSS Deferred Parsing Testing
185     unsigned deferredStyleRulesCount(StyleSheet&);
186     unsigned deferredGroupRulesCount(StyleSheet&);
187     unsigned deferredKeyframesRulesCount(StyleSheet&);
188
189     // DOMTimers throttling testing.
190     ExceptionOr<bool> isTimerThrottled(int timeoutId);
191     bool isRequestAnimationFrameThrottled() const;
192     double requestAnimationFrameInterval() const;
193     bool scriptedAnimationsAreSuspended() const;
194     bool areTimersThrottled() const;
195
196     enum EventThrottlingBehavior { Responsive, Unresponsive };
197     void setEventThrottlingBehaviorOverride(Optional<EventThrottlingBehavior>);
198     Optional<EventThrottlingBehavior> eventThrottlingBehaviorOverride() const;
199
200     // Spatial Navigation testing.
201     ExceptionOr<unsigned> lastSpatialNavigationCandidateCount() const;
202
203     // CSS Animation testing.
204     unsigned numberOfActiveAnimations() const;
205     ExceptionOr<bool> animationsAreSuspended() const;
206     ExceptionOr<void> suspendAnimations() const;
207     ExceptionOr<void> resumeAnimations() const;
208     ExceptionOr<bool> pauseAnimationAtTimeOnElement(const String& animationName, double pauseTime, Element&);
209     ExceptionOr<bool> pauseAnimationAtTimeOnPseudoElement(const String& animationName, double pauseTime, Element&, const String& pseudoId);
210     double animationsInterval() const;
211
212     // CSS Transition testing.
213     ExceptionOr<bool> pauseTransitionAtTimeOnElement(const String& propertyName, double pauseTime, Element&);
214     ExceptionOr<bool> pauseTransitionAtTimeOnPseudoElement(const String& property, double pauseTime, Element&, const String& pseudoId);
215
216     // Web Animations testing.
217     struct AcceleratedAnimation {
218         String property;
219         double speed;
220     };
221     Vector<AcceleratedAnimation> acceleratedAnimationsForElement(Element&);
222     unsigned numberOfAnimationTimelineInvalidations() const;
223
224     // For animations testing, we need a way to get at pseudo elements.
225     ExceptionOr<RefPtr<Element>> pseudoElement(Element&, const String&);
226
227     Node* treeScopeRootNode(Node&);
228     Node* parentTreeScope(Node&);
229
230     String visiblePlaceholder(Element&);
231     void selectColorInColorChooser(HTMLInputElement&, const String& colorValue);
232     ExceptionOr<Vector<String>> formControlStateOfPreviousHistoryItem();
233     ExceptionOr<void> setFormControlStateOfPreviousHistoryItem(const Vector<String>&);
234
235     ExceptionOr<Ref<DOMRect>> absoluteCaretBounds();
236     ExceptionOr<bool> isCaretBlinkingSuspended();
237
238     Ref<DOMRect> boundingBox(Element&);
239
240     ExceptionOr<Ref<DOMRectList>> inspectorHighlightRects();
241
242     ExceptionOr<unsigned> markerCountForNode(Node&, const String&);
243     ExceptionOr<RefPtr<Range>> markerRangeForNode(Node&, const String& markerType, unsigned index);
244     ExceptionOr<String> markerDescriptionForNode(Node&, const String& markerType, unsigned index);
245     ExceptionOr<String> dumpMarkerRects(const String& markerType);
246     void addTextMatchMarker(const Range&, bool isActive);
247     ExceptionOr<void> setMarkedTextMatchesAreHighlighted(bool);
248
249     void invalidateFontCache();
250     void setFontSmoothingEnabled(bool);
251
252     ExceptionOr<void> setLowPowerModeEnabled(bool);
253
254     ExceptionOr<void> setScrollViewPosition(int x, int y);
255     ExceptionOr<void> unconstrainedScrollTo(Element&, double x, double y);
256
257     ExceptionOr<Ref<DOMRect>> layoutViewportRect();
258     ExceptionOr<Ref<DOMRect>> visualViewportRect();
259
260     ExceptionOr<void> setViewIsTransparent(bool);
261
262     ExceptionOr<String> viewBaseBackgroundColor();
263     ExceptionOr<void> setViewBaseBackgroundColor(const String& colorValue);
264
265     ExceptionOr<void> setPagination(const String& mode, int gap, int pageLength);
266     ExceptionOr<void> setPaginationLineGridEnabled(bool);
267     ExceptionOr<String> configurationForViewport(float devicePixelRatio, int deviceWidth, int deviceHeight, int availableWidth, int availableHeight);
268
269     ExceptionOr<bool> wasLastChangeUserEdit(Element& textField);
270     bool elementShouldAutoComplete(HTMLInputElement&);
271     void setAutofilled(HTMLInputElement&, bool enabled);
272     void setAutoFilledAndViewable(HTMLInputElement&, bool enabled);
273     enum class AutoFillButtonType { None, Contacts, Credentials, StrongPassword, CreditCard };
274     void setShowAutoFillButton(HTMLInputElement&, AutoFillButtonType);
275     AutoFillButtonType autoFillButtonType(const HTMLInputElement&);
276     AutoFillButtonType lastAutoFillButtonType(const HTMLInputElement&);
277     ExceptionOr<void> scrollElementToRect(Element&, int x, int y, int w, int h);
278
279     ExceptionOr<String> autofillFieldName(Element&);
280
281     ExceptionOr<void> invalidateControlTints();
282
283     RefPtr<Range> rangeFromLocationAndLength(Element& scope, int rangeLocation, int rangeLength);
284     unsigned locationFromRange(Element& scope, const Range&);
285     unsigned lengthFromRange(Element& scope, const Range&);
286     String rangeAsText(const Range&);
287     String rangeAsTextUsingBackwardsTextIterator(const Range&);
288     Ref<Range> subrange(Range&, int rangeLocation, int rangeLength);
289     ExceptionOr<RefPtr<Range>> rangeForDictionaryLookupAtLocation(int x, int y);
290     RefPtr<Range> rangeOfStringNearLocation(const Range&, const String&, unsigned);
291
292     ExceptionOr<void> setDelegatesScrolling(bool enabled);
293
294     ExceptionOr<int> lastSpellCheckRequestSequence();
295     ExceptionOr<int> lastSpellCheckProcessedSequence();
296
297     Vector<String> userPreferredLanguages() const;
298     void setUserPreferredLanguages(const Vector<String>&);
299
300     Vector<String> userPreferredAudioCharacteristics() const;
301     void setUserPreferredAudioCharacteristic(const String&);
302
303     ExceptionOr<unsigned> wheelEventHandlerCount();
304     ExceptionOr<unsigned> touchEventHandlerCount();
305
306     ExceptionOr<Ref<DOMRectList>> touchEventRectsForEvent(const String&);
307     ExceptionOr<Ref<DOMRectList>> passiveTouchEventListenerRects();
308
309     ExceptionOr<RefPtr<NodeList>> nodesFromRect(Document&, int x, int y, unsigned topPadding, unsigned rightPadding, unsigned bottomPadding, unsigned leftPadding, bool ignoreClipping, bool allowUserAgentShadowContent, bool allowChildFrameContent) const;
310
311     String parserMetaData(JSC::JSValue = JSC::JSValue::JSUndefined);
312
313     void updateEditorUINowIfScheduled();
314
315     bool sentenceRetroCorrectionEnabled() const
316     {
317 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101400
318         return true;
319 #else
320         return false;
321 #endif
322     }
323     bool hasSpellingMarker(int from, int length);
324     bool hasGrammarMarker(int from, int length);
325     bool hasAutocorrectedMarker(int from, int length);
326     void setContinuousSpellCheckingEnabled(bool);
327     void setAutomaticQuoteSubstitutionEnabled(bool);
328     void setAutomaticLinkDetectionEnabled(bool);
329     void setAutomaticDashSubstitutionEnabled(bool);
330     void setAutomaticTextReplacementEnabled(bool);
331     void setAutomaticSpellingCorrectionEnabled(bool);
332
333     void handleAcceptedCandidate(const String& candidate, unsigned location, unsigned length);
334     void changeSelectionListType();
335
336     bool isOverwriteModeEnabled();
337     void toggleOverwriteModeEnabled();
338
339     bool testProcessIncomingSyncMessagesWhenWaitingForSyncReply();
340
341     ExceptionOr<RefPtr<Range>> rangeOfString(const String&, RefPtr<Range>&&, const Vector<String>& findOptions);
342     ExceptionOr<unsigned> countMatchesForText(const String&, const Vector<String>& findOptions, const String& markMatches);
343     ExceptionOr<unsigned> countFindMatches(const String&, const Vector<String>& findOptions);
344
345     unsigned numberOfScrollableAreas();
346
347     ExceptionOr<bool> isPageBoxVisible(int pageNumber);
348
349     static const char* internalsId;
350
351     InternalSettings* settings() const;
352     unsigned workerThreadCount() const;
353     ExceptionOr<bool> areSVGAnimationsPaused() const;
354     ExceptionOr<double> svgAnimationsInterval(SVGSVGElement&) const;
355
356     enum {
357         // Values need to be kept in sync with Internals.idl.
358         LAYER_TREE_INCLUDES_VISIBLE_RECTS = 1,
359         LAYER_TREE_INCLUDES_TILE_CACHES = 2,
360         LAYER_TREE_INCLUDES_REPAINT_RECTS = 4,
361         LAYER_TREE_INCLUDES_PAINTING_PHASES = 8,
362         LAYER_TREE_INCLUDES_CONTENT_LAYERS = 16,
363         LAYER_TREE_INCLUDES_ACCELERATES_DRAWING = 32,
364         LAYER_TREE_INCLUDES_CLIPPING = 64,
365         LAYER_TREE_INCLUDES_BACKING_STORE_ATTACHED = 128,
366         LAYER_TREE_INCLUDES_ROOT_LAYER_PROPERTIES = 256,
367         LAYER_TREE_INCLUDES_EVENT_REGION = 512,
368     };
369     ExceptionOr<String> layerTreeAsText(Document&, unsigned short flags) const;
370     ExceptionOr<uint64_t> layerIDForElement(Element&);
371     ExceptionOr<String> repaintRectsAsText() const;
372
373     ExceptionOr<String> scrollbarOverlayStyle(Node*) const;
374     ExceptionOr<bool> scrollbarUsingDarkAppearance(Node*) const;
375
376     ExceptionOr<String> scrollingStateTreeAsText() const;
377     ExceptionOr<String> mainThreadScrollingReasons() const;
378     ExceptionOr<Ref<DOMRectList>> nonFastScrollableRects() const;
379
380     ExceptionOr<void> setElementUsesDisplayListDrawing(Element&, bool usesDisplayListDrawing);
381     ExceptionOr<void> setElementTracksDisplayListReplay(Element&, bool isTrackingReplay);
382
383     enum {
384         // Values need to be kept in sync with Internals.idl.
385         DISPLAY_LIST_INCLUDES_PLATFORM_OPERATIONS = 1,
386     };
387     ExceptionOr<String> displayListForElement(Element&, unsigned short flags);
388     ExceptionOr<String> replayDisplayListForElement(Element&, unsigned short flags);
389
390     ExceptionOr<void> garbageCollectDocumentResources() const;
391
392     void beginSimulatedMemoryPressure();
393     void endSimulatedMemoryPressure();
394     bool isUnderMemoryPressure();
395
396     ExceptionOr<void> insertAuthorCSS(const String&) const;
397     ExceptionOr<void> insertUserCSS(const String&) const;
398
399 #if ENABLE(INDEXED_DATABASE)
400     unsigned numberOfIDBTransactions() const;
401 #endif
402
403     unsigned numberOfLiveNodes() const;
404     unsigned numberOfLiveDocuments() const;
405     unsigned referencingNodeCount(const Document&) const;
406
407 #if ENABLE(INTERSECTION_OBSERVER)
408     unsigned numberOfIntersectionObservers(const Document&) const;
409 #endif
410
411     uint64_t documentIdentifier(const Document&) const;
412     bool isDocumentAlive(uint64_t documentIdentifier) const;
413
414     uint64_t frameIdentifier(const Document&) const;
415     uint64_t pageIdentifier(const Document&) const;
416
417     bool isAnyWorkletGlobalScopeAlive() const;
418
419     String serviceWorkerClientIdentifier(const Document&) const;
420
421     RefPtr<WindowProxy> openDummyInspectorFrontend(const String& url);
422     void closeDummyInspectorFrontend();
423     ExceptionOr<void> setInspectorIsUnderTest(bool);
424
425     String counterValue(Element&);
426
427     int pageNumber(Element&, float pageWidth = 800, float pageHeight = 600);
428     Vector<String> shortcutIconURLs() const;
429
430     int numberOfPages(float pageWidthInPixels = 800, float pageHeightInPixels = 600);
431     ExceptionOr<String> pageProperty(const String& propertyName, int pageNumber) const;
432     ExceptionOr<String> pageSizeAndMarginsInPixels(int pageNumber, int width, int height, int marginTop, int marginRight, int marginBottom, int marginLeft) const;
433
434     ExceptionOr<float> pageScaleFactor() const;
435
436     ExceptionOr<void> setPageScaleFactor(float scaleFactor, int x, int y);
437     ExceptionOr<void> setPageZoomFactor(float);
438     ExceptionOr<void> setTextZoomFactor(float);
439
440     ExceptionOr<void> setUseFixedLayout(bool);
441     ExceptionOr<void> setFixedLayoutSize(int width, int height);
442     ExceptionOr<void> setViewExposedRect(float left, float top, float width, float height);
443     void setPrinting(int width, int height);
444
445     void setHeaderHeight(float);
446     void setFooterHeight(float);
447
448     void setTopContentInset(float);
449
450 #if ENABLE(FULLSCREEN_API)
451     void webkitWillEnterFullScreenForElement(Element&);
452     void webkitDidEnterFullScreenForElement(Element&);
453     void webkitWillExitFullScreenForElement(Element&);
454     void webkitDidExitFullScreenForElement(Element&);
455     bool isAnimatingFullScreen() const;
456 #endif
457
458     struct FullscreenInsets {
459         float top { 0 };
460         float left { 0 };
461         float bottom { 0 };
462         float right { 0 };
463     };
464     void setFullscreenInsets(FullscreenInsets);
465     void setFullscreenAutoHideDuration(double);
466     void setFullscreenControlsHidden(bool);
467
468     WEBCORE_TESTSUPPORT_EXPORT void setApplicationCacheOriginQuota(unsigned long long);
469
470     void registerURLSchemeAsBypassingContentSecurityPolicy(const String& scheme);
471     void removeURLSchemeRegisteredAsBypassingContentSecurityPolicy(const String& scheme);
472
473     void registerDefaultPortForProtocol(unsigned short port, const String& protocol);
474
475     Ref<MallocStatistics> mallocStatistics() const;
476     Ref<TypeConversions> typeConversions() const;
477     Ref<MemoryInfo> memoryInfo() const;
478
479     Vector<String> getReferencedFilePaths() const;
480
481     ExceptionOr<void> startTrackingRepaints();
482     ExceptionOr<void> stopTrackingRepaints();
483
484     ExceptionOr<void> startTrackingLayerFlushes();
485     ExceptionOr<unsigned> layerFlushCount();
486
487     ExceptionOr<void> startTrackingStyleRecalcs();
488     ExceptionOr<unsigned> styleRecalcCount();
489     unsigned lastStyleUpdateSize() const;
490
491     ExceptionOr<void> startTrackingCompositingUpdates();
492     ExceptionOr<unsigned> compositingUpdateCount();
493
494     enum CompositingPolicy { Normal, Conservative };
495     ExceptionOr<void> setCompositingPolicyOverride(Optional<CompositingPolicy>);
496     ExceptionOr<Optional<CompositingPolicy>> compositingPolicyOverride() const;
497
498     ExceptionOr<void> updateLayoutIgnorePendingStylesheetsAndRunPostLayoutTasks(Node*);
499     unsigned layoutCount() const;
500
501     Ref<ArrayBuffer> serializeObject(const RefPtr<SerializedScriptValue>&) const;
502     Ref<SerializedScriptValue> deserializeBuffer(ArrayBuffer&) const;
503
504     bool isFromCurrentWorld(JSC::JSValue) const;
505
506     void setUsesOverlayScrollbars(bool);
507     void setUsesMockScrollAnimator(bool);
508
509     ExceptionOr<String> getCurrentCursorInfo();
510
511     String markerTextForListItem(Element&);
512
513     String toolTipFromElement(Element&) const;
514
515     void forceReload(bool endToEnd);
516     void reloadExpiredOnly();
517
518     void enableAutoSizeMode(bool enabled, int width, int height);
519
520 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
521     void initializeMockCDM();
522 #endif
523
524 #if ENABLE(ENCRYPTED_MEDIA)
525     Ref<MockCDMFactory> registerMockCDM();
526 #endif
527
528     void enableMockMediaCapabilities();
529
530 #if ENABLE(SPEECH_SYNTHESIS)
531     void enableMockSpeechSynthesizer();
532 #endif
533
534 #if ENABLE(MEDIA_STREAM)
535     void setShouldInterruptAudioOnPageVisibilityChange(bool);
536     void setMockMediaCaptureDevicesEnabled(bool);
537     void setMediaCaptureRequiresSecureConnection(bool);
538     void setCustomPrivateRecorderCreator();
539 #endif
540
541 #if ENABLE(WEB_RTC)
542     void emulateRTCPeerConnectionPlatformEvent(RTCPeerConnection&, const String& action);
543     void useMockRTCPeerConnectionFactory(const String&);
544     void setICECandidateFiltering(bool);
545     void setEnumeratingAllNetworkInterfacesEnabled(bool);
546     void stopPeerConnection(RTCPeerConnection&);
547     void clearPeerConnectionFactory();
548     void applyRotationForOutgoingVideoSources(RTCPeerConnection&);
549     void setEnableWebRTCEncryption(bool);
550     void setUseDTLS10(bool);
551 #endif
552
553     String getImageSourceURL(Element&);
554
555 #if ENABLE(VIDEO)
556     Vector<String> mediaResponseSources(HTMLMediaElement&);
557     Vector<String> mediaResponseContentRanges(HTMLMediaElement&);
558     void simulateAudioInterruption(HTMLMediaElement&);
559     ExceptionOr<bool> mediaElementHasCharacteristic(HTMLMediaElement&, const String&);
560     void beginSimulatedHDCPError(HTMLMediaElement&);
561     void endSimulatedHDCPError(HTMLMediaElement&);
562
563     bool elementShouldBufferData(HTMLMediaElement&);
564     String elementBufferingPolicy(HTMLMediaElement&);
565     double privatePlayerVolume(const HTMLMediaElement&);
566 #endif
567
568     bool isSelectPopupVisible(HTMLSelectElement&);
569
570     ExceptionOr<String> captionsStyleSheetOverride();
571     ExceptionOr<void> setCaptionsStyleSheetOverride(const String&);
572     ExceptionOr<void> setPrimaryAudioTrackLanguageOverride(const String&);
573     ExceptionOr<void> setCaptionDisplayMode(const String&);
574 #if ENABLE(VIDEO_TRACK)
575     RefPtr<TextTrackCueGeneric> createGenericCue(double startTime, double endTime, String text);
576 #endif
577
578 #if ENABLE(VIDEO)
579     Ref<TimeRanges> createTimeRanges(Float32Array& startTimes, Float32Array& endTimes);
580     double closestTimeToTimeRanges(double time, TimeRanges&);
581 #endif
582
583     ExceptionOr<Ref<DOMRect>> selectionBounds();
584     void setSelectionWithoutValidation(Ref<Node> baseNode, unsigned baseOffset, RefPtr<Node> extentNode, unsigned extentOffset);
585
586     ExceptionOr<bool> isPluginUnavailabilityIndicatorObscured(Element&);
587     ExceptionOr<String> unavailablePluginReplacementText(Element&);
588     bool isPluginSnapshotted(Element&);
589     bool pluginIsBelowSizeThreshold(Element&);
590
591 #if ENABLE(MEDIA_SOURCE)
592     WEBCORE_TESTSUPPORT_EXPORT void initializeMockMediaSource();
593     Vector<String> bufferedSamplesForTrackID(SourceBuffer&, const AtomString&);
594     Vector<String> enqueuedSamplesForTrackID(SourceBuffer&, const AtomString&);
595     double minimumUpcomingPresentationTimeForTrackID(SourceBuffer&, const AtomString&);
596     void setShouldGenerateTimestamps(SourceBuffer&, bool);
597     void setMaximumQueueDepthForTrackID(SourceBuffer&, const AtomString&, size_t);
598 #endif
599
600 #if ENABLE(VIDEO)
601     ExceptionOr<void> beginMediaSessionInterruption(const String&);
602     void endMediaSessionInterruption(const String&);
603     void applicationWillBecomeInactive();
604     void applicationDidBecomeActive();
605     void applicationWillEnterForeground(bool suspendedUnderLock) const;
606     void applicationDidEnterBackground(bool suspendedUnderLock) const;
607     ExceptionOr<void> setMediaSessionRestrictions(const String& mediaType, StringView restrictionsString);
608     ExceptionOr<String> mediaSessionRestrictions(const String& mediaType) const;
609     void setMediaElementRestrictions(HTMLMediaElement&, StringView restrictionsString);
610     ExceptionOr<void> postRemoteControlCommand(const String&, float argument);
611     bool elementIsBlockingDisplaySleep(HTMLMediaElement&) const;
612 #endif
613
614 #if ENABLE(MEDIA_SESSION)
615     void sendMediaSessionStartOfInterruptionNotification(MediaSessionInterruptingCategory);
616     void sendMediaSessionEndOfInterruptionNotification(MediaSessionInterruptingCategory);
617     String mediaSessionCurrentState(MediaSession&) const;
618     double mediaElementPlayerVolume(HTMLMediaElement&) const;
619     enum class MediaControlEvent { PlayPause, NextTrack, PreviousTrack };
620     void sendMediaControlEvent(MediaControlEvent);
621 #endif
622
623 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
624     void setMockMediaPlaybackTargetPickerEnabled(bool);
625     ExceptionOr<void> setMockMediaPlaybackTargetPickerState(const String& deviceName, const String& deviceState);
626 #endif
627
628 #if ENABLE(WEB_AUDIO)
629     void setAudioContextRestrictions(AudioContext&, StringView restrictionsString);
630 #endif
631
632     void simulateSystemSleep() const;
633     void simulateSystemWake() const;
634
635     enum class PageOverlayType { View, Document };
636     ExceptionOr<Ref<MockPageOverlay>> installMockPageOverlay(PageOverlayType);
637     ExceptionOr<String> pageOverlayLayerTreeAsText(unsigned short flags) const;
638
639     void setPageMuted(StringView);
640     String pageMediaState();
641
642     void setPageDefersLoading(bool);
643     ExceptionOr<bool> pageDefersLoading();
644
645     RefPtr<File> createFile(const String&);
646     void queueMicroTask(int);
647     bool testPreloaderSettingViewport();
648
649 #if ENABLE(CONTENT_FILTERING)
650     MockContentFilterSettings& mockContentFilterSettings();
651 #endif
652
653 #if ENABLE(CSS_SCROLL_SNAP)
654     ExceptionOr<String> scrollSnapOffsets(Element&);
655     void setPlatformMomentumScrollingPredictionEnabled(bool);
656 #endif
657
658     ExceptionOr<String> pathStringWithShrinkWrappedRects(const Vector<double>& rectComponents, double radius);
659
660     String getCurrentMediaControlsStatusForElement(HTMLMediaElement&);
661
662     String userVisibleString(const DOMURL&);
663     void setShowAllPlugins(bool);
664
665     String resourceLoadStatisticsForURL(const DOMURL&);
666     void setResourceLoadStatisticsEnabled(bool);
667
668 #if ENABLE(STREAMS_API)
669     bool isReadableStreamDisturbed(JSC::ExecState&, JSC::JSValue);
670     JSC::JSValue cloneArrayBuffer(JSC::ExecState&, JSC::JSValue, JSC::JSValue, JSC::JSValue);
671 #endif
672
673     String composedTreeAsText(Node&);
674
675     bool isProcessingUserGesture();
676     double lastHandledUserGestureTimestamp();
677
678     void withUserGesture(RefPtr<VoidCallback>&&);
679
680     bool userIsInteracting();
681
682     RefPtr<GCObservation> observeGC(JSC::JSValue);
683
684     enum class UserInterfaceLayoutDirection : uint8_t { LTR, RTL };
685     void setUserInterfaceLayoutDirection(UserInterfaceLayoutDirection);
686
687     bool userPrefersReducedMotion() const;
688
689     void reportBacktrace();
690
691     enum class BaseWritingDirection { Natural, Ltr, Rtl };
692     void setBaseWritingDirection(BaseWritingDirection);
693
694 #if ENABLE(POINTER_LOCK)
695     bool pageHasPendingPointerLock() const;
696     bool pageHasPointerLock() const;
697 #endif
698
699     Vector<String> accessKeyModifiers() const;
700
701     void setQuickLookPassword(const String&);
702
703     void setAsRunningUserScripts(Document&);
704 #if ENABLE(APPLE_PAY)
705     void setApplePayIsActive(Document&);
706 #endif
707
708 #if ENABLE(WEBGL)
709     void simulateWebGLContextChanged(WebGLRenderingContext&);
710     void failNextGPUStatusCheck(WebGLRenderingContext&);
711     bool hasLowAndHighPowerGPUs();
712 #endif
713
714     void setPageVisibility(bool isVisible);
715     void setPageIsFocusedAndActive(bool);
716
717
718 #if ENABLE(WEB_RTC)
719     void setH264HardwareEncoderAllowed(bool allowed);
720 #endif
721
722 #if ENABLE(MEDIA_STREAM)
723     void setMockAudioTrackChannelNumber(MediaStreamTrack&, unsigned short);
724     void setCameraMediaStreamTrackOrientation(MediaStreamTrack&, int orientation);
725     unsigned long trackAudioSampleCount() const { return m_trackAudioSampleCount; }
726     unsigned long trackVideoSampleCount() const { return m_trackVideoSampleCount; }
727     void observeMediaStreamTrack(MediaStreamTrack&);
728     using TrackFramePromise = DOMPromiseDeferred<IDLInterface<ImageData>>;
729     void grabNextMediaStreamTrackFrame(TrackFramePromise&&);
730     void delayMediaStreamTrackSamples(MediaStreamTrack&, float);
731     void setMediaStreamTrackMuted(MediaStreamTrack&, bool);
732     void removeMediaStreamTrack(MediaStream&, MediaStreamTrack&);
733     void simulateMediaStreamTrackCaptureSourceFailure(MediaStreamTrack&);
734     void setMediaStreamTrackIdentifier(MediaStreamTrack&, String&& id);
735     void setMediaStreamSourceInterrupted(MediaStreamTrack&, bool);
736     void setDisableGetDisplayMediaUserGestureConstraint(bool);
737 #endif
738
739     bool supportsAudioSession() const;
740     String audioSessionCategory() const;
741     double preferredAudioBufferSize() const;
742     bool audioSessionActive() const;
743
744     void storeRegistrationsOnDisk(DOMPromiseDeferred<void>&&);
745
746     void clearCacheStorageMemoryRepresentation(DOMPromiseDeferred<void>&&);
747     void cacheStorageEngineRepresentation(DOMPromiseDeferred<IDLDOMString>&&);
748     void setResponseSizeWithPadding(FetchResponse&, uint64_t size);
749     uint64_t responseSizeWithPadding(FetchResponse&) const;
750
751     void updateQuotaBasedOnSpaceUsage();
752
753     void setConsoleMessageListener(RefPtr<StringCallback>&&);
754
755 #if ENABLE(SERVICE_WORKER)
756     using HasRegistrationPromise = DOMPromiseDeferred<IDLBoolean>;
757     void hasServiceWorkerRegistration(const String& clientURL, HasRegistrationPromise&&);
758     void terminateServiceWorker(ServiceWorker&);
759     bool hasServiceWorkerConnection();
760 #endif
761
762 #if ENABLE(APPLE_PAY)
763     MockPaymentCoordinator& mockPaymentCoordinator(Document&);
764 #endif
765
766     bool isSystemPreviewLink(Element&) const;
767     bool isSystemPreviewImage(Element&) const;
768
769     void postTask(RefPtr<VoidCallback>&&);
770     void markContextAsInsecure();
771
772     bool usingAppleInternalSDK() const;
773
774     struct NowPlayingState {
775         String title;
776         double duration;
777         double elapsedTime;
778         uint64_t uniqueIdentifier;
779         bool hasActiveSession;
780         bool registeredAsNowPlayingApplication;
781     };
782     ExceptionOr<NowPlayingState> nowPlayingState() const;
783
784 #if ENABLE(VIDEO)
785     using PlaybackControlsPurpose = MediaElementSession::PlaybackControlsPurpose;
786     RefPtr<HTMLMediaElement> bestMediaElementForShowingPlaybackControlsManager(PlaybackControlsPurpose);
787
788     using MediaSessionState = PlatformMediaSession::State;
789     MediaSessionState mediaSessionState(HTMLMediaElement&);
790 #endif
791
792     void setCaptureExtraNetworkLoadMetricsEnabled(bool);
793     String ongoingLoadsDescriptions() const;
794
795     void reloadWithoutContentExtensions();
796
797     void setUseSystemAppearance(bool);
798
799     size_t pluginCount();
800
801     void notifyResourceLoadObserver();
802
803     unsigned primaryScreenDisplayID();
804
805     bool capsLockIsOn();
806         
807     bool supportsVCPEncoder();
808         
809     using HEVCParameterSet = WebCore::HEVCParameterSet;
810     Optional<HEVCParameterSet> parseHEVCCodecParameters(const String& codecString);
811
812     struct CookieData {
813         String name;
814         String value;
815         String domain;
816         // Expiration dates are expressed as milliseconds since the UNIX epoch.
817         double expires { 0 };
818         bool isHttpOnly { false };
819         bool isSecure { false };
820         bool isSession { false };
821         bool isSameSiteLax { false };
822         bool isSameSiteStrict { false };
823
824         CookieData(Cookie cookie)
825             : name(cookie.name)
826             , value(cookie.value)
827             , domain(cookie.domain)
828             , expires(cookie.expires)
829             , isHttpOnly(cookie.httpOnly)
830             , isSecure(cookie.secure)
831             , isSession(cookie.session)
832             , isSameSiteLax(cookie.sameSite == Cookie::SameSitePolicy::Lax)
833             , isSameSiteStrict(cookie.sameSite == Cookie::SameSitePolicy::Strict)
834         {
835             ASSERT(!(isSameSiteLax && isSameSiteStrict));
836         }
837
838         CookieData()
839         {
840         }
841     };
842     Vector<CookieData> getCookies() const;
843
844     void setAlwaysAllowLocalWebarchive(bool);
845     void processWillSuspend();
846     void processDidResume();
847
848     void testDictionaryLogging();
849
850     void setXHRMaximumIntervalForUserGestureForwarding(XMLHttpRequest&, double);
851
852     void setIsPlayingToAutomotiveHeadUnit(bool);
853     
854     struct TextIndicatorInfo {
855         RefPtr<DOMRectReadOnly> textBoundingRectInRootViewCoordinates;
856         RefPtr<DOMRectList> textRectsInBoundingRectCoordinates;
857         
858         TextIndicatorInfo();
859         TextIndicatorInfo(const WebCore::TextIndicatorData&);
860         ~TextIndicatorInfo();
861     };
862         
863     struct TextIndicatorOptions {
864         bool useBoundingRectAndPaintAllContentForComplexRanges { false };
865         bool computeEstimatedBackgroundColor { false };
866         bool respectTextColor { false };
867         
868         WebCore::TextIndicatorOptions core()
869         {
870             WebCore::TextIndicatorOptions options = 0;
871             if (useBoundingRectAndPaintAllContentForComplexRanges)
872                 options = options | TextIndicatorOptionUseBoundingRectAndPaintAllContentForComplexRanges;
873             if (computeEstimatedBackgroundColor)
874                 options = options | TextIndicatorOptionComputeEstimatedBackgroundColor;
875             if (respectTextColor)
876                 options = options | TextIndicatorOptionRespectTextColor;
877             return options;
878         }
879     };
880
881     TextIndicatorInfo textIndicatorForRange(const Range&, TextIndicatorOptions);
882
883     void addPrefetchLoadEventListener(HTMLLinkElement&, RefPtr<EventListener>&&);
884
885 private:
886     explicit Internals(Document&);
887     Document* contextDocument() const;
888     Frame* frame() const;
889
890     ExceptionOr<RenderedDocumentMarker*> markerAt(Node&, const String& markerType, unsigned index);
891
892     // RealtimeMediaSource::Observer API
893 #if ENABLE(MEDIA_STREAM)
894     void videoSampleAvailable(MediaSample&) final;
895     void audioSamplesAvailable(const MediaTime&, const PlatformAudioData&, const AudioStreamDescription&, size_t) final { m_trackAudioSampleCount++; }
896
897     OrientationNotifier m_orientationNotifier;
898     unsigned long m_trackVideoSampleCount { 0 };
899     unsigned long m_trackAudioSampleCount { 0 };
900     RefPtr<MediaStreamTrack> m_track;
901     Optional<TrackFramePromise> m_nextTrackFramePromise;
902 #endif
903
904     std::unique_ptr<InspectorStubFrontend> m_inspectorFrontend;
905     RefPtr<CacheStorageConnection> m_cacheStorageConnection;
906
907     RefPtr<UnsuspendableActiveDOMObject> m_unsuspendableActiveDOMObject;
908 };
909
910 } // namespace WebCore