Deprecate all WKCookieManagerRef functions
[WebKit-https.git] / Tools / WebKitTestRunner / TestController.cpp
1 /*
2  * Copyright (C) 2010-2019 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "TestController.h"
28
29 #include "EventSenderProxy.h"
30 #include "Options.h"
31 #include "PlatformWebView.h"
32 #include "StringFunctions.h"
33 #include "TestInvocation.h"
34 #include "WebCoreTestSupport.h"
35 #include <JavaScriptCore/InitializeThreading.h>
36 #include <WebKit/WKArray.h>
37 #include <WebKit/WKAuthenticationChallenge.h>
38 #include <WebKit/WKAuthenticationDecisionListener.h>
39 #include <WebKit/WKContextConfigurationRef.h>
40 #include <WebKit/WKContextPrivate.h>
41 #include <WebKit/WKCredential.h>
42 #include <WebKit/WKFrameHandleRef.h>
43 #include <WebKit/WKFrameInfoRef.h>
44 #include <WebKit/WKHTTPCookieStoreRef.h>
45 #include <WebKit/WKIconDatabase.h>
46 #include <WebKit/WKMessageListener.h>
47 #include <WebKit/WKMockDisplay.h>
48 #include <WebKit/WKMockMediaDevice.h>
49 #include <WebKit/WKNavigationActionRef.h>
50 #include <WebKit/WKNavigationResponseRef.h>
51 #include <WebKit/WKNotification.h>
52 #include <WebKit/WKNotificationManager.h>
53 #include <WebKit/WKNotificationPermissionRequest.h>
54 #include <WebKit/WKNumber.h>
55 #include <WebKit/WKOpenPanelResultListener.h>
56 #include <WebKit/WKPageGroup.h>
57 #include <WebKit/WKPageInjectedBundleClient.h>
58 #include <WebKit/WKPagePrivate.h>
59 #include <WebKit/WKPluginInformation.h>
60 #include <WebKit/WKPreferencesRefPrivate.h>
61 #include <WebKit/WKProtectionSpace.h>
62 #include <WebKit/WKRetainPtr.h>
63 #include <WebKit/WKSecurityOriginRef.h>
64 #include <WebKit/WKTextChecker.h>
65 #include <WebKit/WKURL.h>
66 #include <WebKit/WKUserContentControllerRef.h>
67 #include <WebKit/WKUserContentExtensionStoreRef.h>
68 #include <WebKit/WKUserMediaPermissionCheck.h>
69 #include <WebKit/WKWebsiteDataStoreRef.h>
70 #include <algorithm>
71 #include <cstdio>
72 #include <ctype.h>
73 #include <fstream>
74 #include <stdlib.h>
75 #include <string>
76 #include <wtf/AutodrainedPool.h>
77 #include <wtf/CompletionHandler.h>
78 #include <wtf/CryptographicallyRandomNumber.h>
79 #include <wtf/MainThread.h>
80 #include <wtf/ProcessPrivilege.h>
81 #include <wtf/RefCounted.h>
82 #include <wtf/RunLoop.h>
83 #include <wtf/SetForScope.h>
84 #include <wtf/UUID.h>
85 #include <wtf/UniqueArray.h>
86 #include <wtf/text/CString.h>
87 #include <wtf/text/StringConcatenateNumbers.h>
88
89 #if PLATFORM(COCOA)
90 #include <WebKit/WKContextPrivateMac.h>
91 #include <WebKit/WKPagePrivateMac.h>
92 #endif
93
94 #if PLATFORM(WIN)
95 #include <direct.h>
96 #define getcwd _getcwd
97 #define PATH_MAX _MAX_PATH
98 #else
99 #include <unistd.h>
100 #endif
101
102 namespace WTR {
103
104 #if OS(WINDOWS)
105 static constexpr auto pathSeparator = '\\';
106 #else
107 static constexpr auto pathSeparator = '/';
108 #endif
109
110 const unsigned TestController::viewWidth = 800;
111 const unsigned TestController::viewHeight = 600;
112
113 const unsigned TestController::w3cSVGViewWidth = 480;
114 const unsigned TestController::w3cSVGViewHeight = 360;
115
116 const WTF::Seconds TestController::defaultShortTimeout = 5_s;
117 const WTF::Seconds TestController::noTimeout = -1_s;
118
119 static WKURLRef blankURL()
120 {
121     static WKURLRef staticBlankURL = WKURLCreateWithUTF8CString("about:blank");
122     return staticBlankURL;
123 }
124
125 static WKDataRef copyWebCryptoMasterKey(WKPageRef, const void*)
126 {
127     // Any 128 bit key would do, all we need for testing is to implement the callback.
128     return WKDataCreate((const uint8_t*)"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f", 16);
129 }
130
131 static WKStringRef copySignedPublicKeyAndChallengeString(WKPageRef, const void*)
132 {
133     // Any fake response would do, all we need for testing is to implement the callback.
134     return WKStringCreateWithUTF8CString("MIHFMHEwXDANBgkqhkiG9w0BAQEFAANLADBIAkEAnX0TILJrOMUue%2BPtwBRE6XfV%0AWtKQbsshxk5ZhcUwcwyvcnIq9b82QhJdoACdD34rqfCAIND46fXKQUnb0mvKzQID%0AAQABFhFNb3ppbGxhSXNNeUZyaWVuZDANBgkqhkiG9w0BAQQFAANBAAKv2Eex2n%2FS%0Ar%2F7iJNroWlSzSMtTiQTEB%2BADWHGj9u1xrUrOilq%2Fo2cuQxIfZcNZkYAkWP4DubqW%0Ai0%2F%2FrgBvmco%3D");
135 }
136
137 AsyncTask* AsyncTask::m_currentTask;
138
139 bool AsyncTask::run()
140 {
141     m_currentTask = this;
142     m_task();
143     TestController::singleton().runUntil(m_taskDone, m_timeout);
144     m_currentTask = nullptr;
145     return m_taskDone;
146 }
147
148 AsyncTask* AsyncTask::currentTask()
149 {
150     return m_currentTask;
151 }
152
153 static TestController* controller;
154
155 TestController& TestController::singleton()
156 {
157     ASSERT(controller);
158     return *controller;
159 }
160
161 TestController::TestController(int argc, const char* argv[])
162 {
163     initialize(argc, argv);
164     controller = this;
165     run();
166     controller = nullptr;
167 }
168
169 TestController::~TestController()
170 {
171     // The context will be null if WebKitTestRunner was in server mode, but ran no tests.
172     if (m_context)
173         WKIconDatabaseClose(WKContextGetIconDatabase(m_context.get()));
174
175     platformDestroy();
176 }
177
178 static WKRect getWindowFrame(WKPageRef page, const void* clientInfo)
179 {
180     PlatformWebView* view = static_cast<PlatformWebView*>(const_cast<void*>(clientInfo));
181     return view->windowFrame();
182 }
183
184 static void setWindowFrame(WKPageRef page, WKRect frame, const void* clientInfo)
185 {
186     PlatformWebView* view = static_cast<PlatformWebView*>(const_cast<void*>(clientInfo));
187     view->setWindowFrame(frame);
188 }
189
190 static bool runBeforeUnloadConfirmPanel(WKPageRef page, WKStringRef message, WKFrameRef frame, const void*)
191 {
192     printf("CONFIRM NAVIGATION: %s\n", toSTD(message).c_str());
193     return TestController::singleton().beforeUnloadReturnValue();
194 }
195
196 static void runOpenPanel(WKPageRef page, WKFrameRef frame, WKOpenPanelParametersRef parameters, WKOpenPanelResultListenerRef resultListenerRef, const void*)
197 {
198     printf("OPEN FILE PANEL\n");
199     if (WKOpenPanelParametersGetAllowsDirectories(parameters))
200         printf("-> DIRECTORIES ARE ALLOWED\n");
201     WKArrayRef fileURLs = TestController::singleton().openPanelFileURLs();
202     if (!fileURLs || !WKArrayGetSize(fileURLs)) {
203         WKOpenPanelResultListenerCancel(resultListenerRef);
204         return;
205     }
206     
207     WKTypeRef firstItem = WKArrayGetItemAtIndex(fileURLs, 0);
208     
209 #if PLATFORM(IOS_FAMILY)
210     auto displayString = adoptWK(WKURLCopyLastPathComponent(static_cast<WKURLRef>(firstItem)));
211     WKDataRef mediaIcon = TestController::singleton().openPanelFileURLsMediaIcon();
212     
213     if (mediaIcon) {
214         if (WKOpenPanelParametersGetAllowsMultipleFiles(parameters)) {
215             WKOpenPanelResultListenerChooseMediaFiles(resultListenerRef, fileURLs, displayString.get(), mediaIcon);
216             return;
217         }
218         
219         WKOpenPanelResultListenerChooseMediaFiles(resultListenerRef, adoptWK(WKArrayCreate(&firstItem, 1)).get(), displayString.get(), mediaIcon);
220         return;
221     }
222 #endif
223
224     if (WKOpenPanelParametersGetAllowsMultipleFiles(parameters)) {
225         WKOpenPanelResultListenerChooseFiles(resultListenerRef, fileURLs);
226         return;
227     }
228
229     WKOpenPanelResultListenerChooseFiles(resultListenerRef, adoptWK(WKArrayCreate(&firstItem, 1)).get());
230 }
231
232 void TestController::runModal(WKPageRef page, const void* clientInfo)
233 {
234     PlatformWebView* view = static_cast<PlatformWebView*>(const_cast<void*>(clientInfo));
235     TestController::singleton().mainWebView()->setWindowIsKey(false);
236     runModal(view);
237     TestController::singleton().mainWebView()->setWindowIsKey(true);
238 }
239
240 static void closeOtherPage(WKPageRef page, const void* clientInfo)
241 {
242     WKPageClose(page);
243     PlatformWebView* view = static_cast<PlatformWebView*>(const_cast<void*>(clientInfo));
244     delete view;
245 }
246
247 static void focus(WKPageRef page, const void* clientInfo)
248 {
249     PlatformWebView* view = static_cast<PlatformWebView*>(const_cast<void*>(clientInfo));
250     view->focus();
251     view->setWindowIsKey(true);
252 }
253
254 static void unfocus(WKPageRef page, const void* clientInfo)
255 {
256     PlatformWebView* view = static_cast<PlatformWebView*>(const_cast<void*>(clientInfo));
257     view->setWindowIsKey(false);
258 }
259
260 static void decidePolicyForGeolocationPermissionRequest(WKPageRef, WKFrameRef, WKSecurityOriginRef, WKGeolocationPermissionRequestRef permissionRequest, const void* clientInfo)
261 {
262     TestController::singleton().handleGeolocationPermissionRequest(permissionRequest);
263 }
264
265 static void decidePolicyForUserMediaPermissionRequest(WKPageRef, WKFrameRef frame, WKSecurityOriginRef userMediaDocumentOrigin, WKSecurityOriginRef topLevelDocumentOrigin, WKUserMediaPermissionRequestRef permissionRequest, const void* clientInfo)
266 {
267     TestController::singleton().handleUserMediaPermissionRequest(frame, userMediaDocumentOrigin, topLevelDocumentOrigin, permissionRequest);
268 }
269
270 static void runJavaScriptAlert(WKPageRef page, WKStringRef alertText, WKFrameRef frame, WKSecurityOriginRef securityOrigin, WKPageRunJavaScriptAlertResultListenerRef listener, const void *clientInfo)
271 {
272     TestController::singleton().handleJavaScriptAlert(listener);
273 }
274
275 static void checkUserMediaPermissionForOrigin(WKPageRef, WKFrameRef frame, WKSecurityOriginRef userMediaDocumentOrigin, WKSecurityOriginRef topLevelDocumentOrigin, WKUserMediaPermissionCheckRef checkRequest, const void*)
276 {
277     TestController::singleton().handleCheckOfUserMediaPermissionForOrigin(frame, userMediaDocumentOrigin, topLevelDocumentOrigin, checkRequest);
278 }
279
280 static void requestPointerLock(WKPageRef page, const void*)
281 {
282     WKPageDidAllowPointerLock(page);
283 }
284
285 static void printFrame(WKPageRef page, WKFrameRef frame, const void*)
286 {
287     WKPageBeginPrinting(page, frame, WKPrintInfo { 1, 21, 29.7f });
288     WKPageEndPrinting(page);
289 }
290
291 static bool shouldAllowDeviceOrientationAndMotionAccess(WKPageRef, WKSecurityOriginRef origin, const void*)
292 {
293     return TestController::singleton().handleDeviceOrientationAndMotionAccessRequest(origin);
294 }
295
296 WKPageRef TestController::createOtherPage(WKPageRef, WKPageConfigurationRef configuration, WKNavigationActionRef navigationAction, WKWindowFeaturesRef windowFeatures, const void *clientInfo)
297 {
298     PlatformWebView* parentView = static_cast<PlatformWebView*>(const_cast<void*>(clientInfo));
299     return TestController::singleton().createOtherPage(parentView, configuration, navigationAction, windowFeatures);
300 }
301
302 WKPageRef TestController::createOtherPage(PlatformWebView* parentView, WKPageConfigurationRef configuration, WKNavigationActionRef navigationAction, WKWindowFeaturesRef windowFeatures)
303 {
304     m_currentInvocation->willCreateNewPage();
305
306     // The test needs to call testRunner.setCanOpenWindows() to open new windows.
307     if (!m_currentInvocation->canOpenWindows())
308         return nullptr;
309
310     PlatformWebView* view = platformCreateOtherPage(parentView, configuration, parentView->options());
311     WKPageRef newPage = view->page();
312
313     view->resizeTo(800, 600);
314
315     WKPageUIClientV8 otherPageUIClient = {
316         { 8, view },
317         0, // createNewPage_deprecatedForUseWithV0
318         0, // showPage
319         closeOtherPage,
320         0, // takeFocus
321         focus,
322         unfocus,
323         0, // runJavaScriptAlert_deprecatedForUseWithV0
324         0, // runJavaScriptAlert_deprecatedForUseWithV0
325         0, // runJavaScriptAlert_deprecatedForUseWithV0
326         0, // setStatusText
327         0, // mouseDidMoveOverElement_deprecatedForUseWithV0
328         0, // missingPluginButtonClicked
329         0, // didNotHandleKeyEvent
330         0, // didNotHandleWheelEvent
331         0, // toolbarsAreVisible
332         0, // setToolbarsAreVisible
333         0, // menuBarIsVisible
334         0, // setMenuBarIsVisible
335         0, // statusBarIsVisible
336         0, // setStatusBarIsVisible
337         0, // isResizable
338         0, // setIsResizable
339         getWindowFrame,
340         setWindowFrame,
341         runBeforeUnloadConfirmPanel,
342         0, // didDraw
343         0, // pageDidScroll
344         0, // exceededDatabaseQuota
345         runOpenPanel,
346         decidePolicyForGeolocationPermissionRequest,
347         0, // headerHeight
348         0, // footerHeight
349         0, // drawHeader
350         0, // drawFooter
351         printFrame,
352         runModal,
353         0, // didCompleteRubberBandForMainFrame
354         0, // saveDataToFileInDownloadsFolder
355         0, // shouldInterruptJavaScript
356         0, // createNewPage_deprecatedForUseWithV1
357         0, // mouseDidMoveOverElement
358         0, // decidePolicyForNotificationPermissionRequest
359         0, // unavailablePluginButtonClicked_deprecatedForUseWithV1
360         0, // showColorPicker
361         0, // hideColorPicker
362         0, // unavailablePluginButtonClicked
363         0, // pinnedStateDidChange
364         0, // didBeginTrackingPotentialLongMousePress
365         0, // didRecognizeLongMousePress
366         0, // didCancelTrackingPotentialLongMousePress
367         0, // isPlayingAudioDidChange
368         decidePolicyForUserMediaPermissionRequest,
369         0, // didClickAutofillButton
370         0, // runJavaScriptAlert
371         0, // runJavaScriptConfirm
372         0, // runJavaScriptPrompt
373         0, // mediaSessionMetadataDidChange
374         createOtherPage,
375         runJavaScriptAlert,
376         0, // runJavaScriptConfirm
377         0, // runJavaScriptPrompt
378         checkUserMediaPermissionForOrigin,
379         0, // runBeforeUnloadConfirmPanel
380         0, // fullscreenMayReturnToInline
381         requestPointerLock,
382         0,
383     };
384     WKPageSetPageUIClient(newPage, &otherPageUIClient.base);
385     
386     WKPageNavigationClientV3 pageNavigationClient = {
387         { 3, &TestController::singleton() },
388         decidePolicyForNavigationAction,
389         decidePolicyForNavigationResponse,
390         decidePolicyForPluginLoad,
391         0, // didStartProvisionalNavigation
392         didReceiveServerRedirectForProvisionalNavigation,
393         0, // didFailProvisionalNavigation
394         0, // didCommitNavigation
395         0, // didFinishNavigation
396         0, // didFailNavigation
397         0, // didFailProvisionalLoadInSubframe
398         0, // didFinishDocumentLoad
399         0, // didSameDocumentNavigation
400         0, // renderingProgressDidChange
401         canAuthenticateAgainstProtectionSpace,
402         didReceiveAuthenticationChallenge,
403         processDidCrash,
404         copyWebCryptoMasterKey,
405         didBeginNavigationGesture,
406         willEndNavigationGesture,
407         didEndNavigationGesture,
408         didRemoveNavigationGestureSnapshot,
409         0, // webProcessDidTerminate
410         0, // contentRuleListNotification
411         copySignedPublicKeyAndChallengeString
412     };
413     WKPageSetPageNavigationClient(newPage, &pageNavigationClient.base);
414
415     view->didInitializeClients();
416
417     TestController::singleton().updateWindowScaleForTest(view, *TestController::singleton().m_currentInvocation);
418
419     WKRetain(newPage);
420     return newPage;
421 }
422
423 const char* TestController::libraryPathForTesting()
424 {
425     // FIXME: This may not be sufficient to prevent interactions/crashes
426     // when running more than one copy of DumpRenderTree.
427     // See https://bugs.webkit.org/show_bug.cgi?id=10906
428     char* dumpRenderTreeTemp = getenv("DUMPRENDERTREE_TEMP");
429     if (dumpRenderTreeTemp)
430         return dumpRenderTreeTemp;
431     return platformLibraryPathForTesting();
432 }
433
434 void TestController::initialize(int argc, const char* argv[])
435 {
436     JSC::initializeThreading();
437     RunLoop::initializeMainRunLoop();
438     WTF::setProcessPrivileges(allPrivileges());
439
440     platformInitialize();
441
442     Options options;
443     OptionsHandler optionsHandler(options);
444
445     if (argc < 2) {
446         optionsHandler.printHelp();
447         exit(1);
448     }
449     if (!optionsHandler.parse(argc, argv))
450         exit(1);
451
452     m_useWaitToDumpWatchdogTimer = options.useWaitToDumpWatchdogTimer;
453     m_forceNoTimeout = options.forceNoTimeout;
454     m_verbose = options.verbose;
455     m_gcBetweenTests = options.gcBetweenTests;
456     m_shouldDumpPixelsForAllTests = options.shouldDumpPixelsForAllTests;
457     m_forceComplexText = options.forceComplexText;
458     m_shouldUseAcceleratedDrawing = options.shouldUseAcceleratedDrawing;
459     m_shouldUseRemoteLayerTree = options.shouldUseRemoteLayerTree;
460     m_paths = options.paths;
461     m_allowedHosts = options.allowedHosts;
462     m_shouldShowWebView = options.shouldShowWebView;
463     m_shouldShowTouches = options.shouldShowTouches;
464     m_checkForWorldLeaks = options.checkForWorldLeaks;
465     m_allowAnyHTTPSCertificateForAllowedHosts = options.allowAnyHTTPSCertificateForAllowedHosts;
466
467     m_usingServerMode = (m_paths.size() == 1 && m_paths[0] == "-");
468     if (m_usingServerMode)
469         m_printSeparators = true;
470     else
471         m_printSeparators = m_paths.size() > 1;
472
473     initializeInjectedBundlePath();
474     initializeTestPluginDirectory();
475
476 #if PLATFORM(MAC)
477     WebCoreTestSupport::installMockGamepadProvider();
478 #endif
479
480     WKRetainPtr<WKStringRef> pageGroupIdentifier = adoptWK(WKStringCreateWithUTF8CString("WebKitTestRunnerPageGroup"));
481     m_pageGroup.adopt(WKPageGroupCreateWithIdentifier(pageGroupIdentifier.get()));
482
483     m_eventSenderProxy = makeUnique<EventSenderProxy>(this);
484 }
485
486 WKRetainPtr<WKContextConfigurationRef> TestController::generateContextConfiguration(const TestOptions::ContextOptions& options) const
487 {
488     auto configuration = adoptWK(WKContextConfigurationCreate());
489     WKContextConfigurationSetInjectedBundlePath(configuration.get(), injectedBundlePath());
490     WKContextConfigurationSetFullySynchronousModeIsAllowedForTesting(configuration.get(), true);
491     WKContextConfigurationSetIgnoreSynchronousMessagingTimeoutsForTesting(configuration.get(), options.ignoreSynchronousMessagingTimeouts);
492
493     WKRetainPtr<WKMutableArrayRef> overrideLanguages = adoptWK(WKMutableArrayCreate());
494     for (auto& language : options.overrideLanguages)
495         WKArrayAppendItem(overrideLanguages.get(), adoptWK(WKStringCreateWithUTF8CString(language.utf8().data())).get());
496     WKContextConfigurationSetOverrideLanguages(configuration.get(), overrideLanguages.get());
497
498     if (options.shouldEnableProcessSwapOnNavigation()) {
499         WKContextConfigurationSetProcessSwapsOnNavigation(configuration.get(), true);
500         if (options.enableProcessSwapOnWindowOpen)
501             WKContextConfigurationSetProcessSwapsOnWindowOpenWithOpener(configuration.get(), true);
502     }
503
504     if (const char* dumpRenderTreeTemp = libraryPathForTesting()) {
505         String temporaryFolder = String::fromUTF8(dumpRenderTreeTemp);
506
507         WKContextConfigurationSetApplicationCacheDirectory(configuration.get(), toWK(temporaryFolder + pathSeparator + "ApplicationCache").get());
508         WKContextConfigurationSetDiskCacheDirectory(configuration.get(), toWK(temporaryFolder + pathSeparator + "Cache").get());
509         WKContextConfigurationSetIndexedDBDatabaseDirectory(configuration.get(), toWK(temporaryFolder + pathSeparator + "Databases" + pathSeparator + "IndexedDB").get());
510         WKContextConfigurationSetLocalStorageDirectory(configuration.get(), toWK(temporaryFolder + pathSeparator + "LocalStorage").get());
511         WKContextConfigurationSetWebSQLDatabaseDirectory(configuration.get(), toWK(temporaryFolder + pathSeparator + "Databases" + pathSeparator + "WebSQL").get());
512         WKContextConfigurationSetMediaKeysStorageDirectory(configuration.get(), toWK(temporaryFolder + pathSeparator + "MediaKeys").get());
513         WKContextConfigurationSetResourceLoadStatisticsDirectory(configuration.get(), toWK(temporaryFolder + pathSeparator + "ResourceLoadStatistics").get());
514     }
515     return configuration;
516 }
517
518 WKRetainPtr<WKPageConfigurationRef> TestController::generatePageConfiguration(const TestOptions& options)
519 {
520     if (!m_context || !m_contextOptions->hasSameInitializationOptions(options.contextOptions)) {
521         auto contextConfiguration = generateContextConfiguration(options.contextOptions);
522         m_context = platformAdjustContext(adoptWK(WKContextCreateWithConfiguration(contextConfiguration.get())).get(), contextConfiguration.get());
523         m_contextOptions = options.contextOptions;
524
525         m_geolocationProvider = makeUnique<GeolocationProviderMock>(m_context.get());
526
527         if (const char* dumpRenderTreeTemp = libraryPathForTesting()) {
528             String temporaryFolder = String::fromUTF8(dumpRenderTreeTemp);
529
530             // FIXME: This should be migrated to WKContextConfigurationRef.
531             // Disable icon database to avoid fetching <http://127.0.0.1:8000/favicon.ico> and making tests flaky.
532             // Invividual tests can enable it using testRunner.setIconDatabaseEnabled, although it's not currently supported in WebKitTestRunner.
533             WKContextSetIconDatabasePath(m_context.get(), toWK(emptyString()).get());
534         }
535
536         WKContextSetDiskCacheSpeculativeValidationEnabled(m_context.get(), true);
537         WKContextUseTestingNetworkSession(m_context.get());
538         WKContextSetCacheModel(m_context.get(), kWKCacheModelDocumentBrowser);
539
540         auto* websiteDataStore = WKContextGetWebsiteDataStore(m_context.get());
541         WKWebsiteDataStoreSetPerOriginStorageQuota(websiteDataStore, 400 * 1024);
542
543         platformInitializeContext();
544     }
545
546     WKContextInjectedBundleClientV2 injectedBundleClient = {
547         { 2, this },
548         didReceiveMessageFromInjectedBundle,
549         nullptr,
550         getInjectedBundleInitializationUserData,
551         didReceiveSynchronousMessageFromInjectedBundleWithListener,
552     };
553     WKContextSetInjectedBundleClient(m_context.get(), &injectedBundleClient.base);
554
555     WKContextClientV2 contextClient = {
556         { 2, this },
557         0, // plugInAutoStartOriginHashesChanged
558         networkProcessDidCrash,
559         0, // plugInInformationBecameAvailable
560         0, // copyWebCryptoMasterKey
561     };
562     WKContextSetClient(m_context.get(), &contextClient.base);
563
564     WKContextHistoryClientV0 historyClient = {
565         { 0, this },
566         didNavigateWithNavigationData,
567         didPerformClientRedirect,
568         didPerformServerRedirect,
569         didUpdateHistoryTitle,
570         0, // populateVisitedLinks
571     };
572     WKContextSetHistoryClient(m_context.get(), &historyClient.base);
573
574     WKNotificationManagerRef notificationManager = WKContextGetNotificationManager(m_context.get());
575     WKNotificationProviderV0 notificationKit = m_webNotificationProvider.provider();
576     WKNotificationManagerSetProvider(notificationManager, &notificationKit.base);
577
578     if (testPluginDirectory())
579         WKContextSetAdditionalPluginsDirectory(m_context.get(), testPluginDirectory());
580
581     if (m_forceComplexText)
582         WKContextSetAlwaysUsesComplexTextCodePath(m_context.get(), true);
583
584     auto pageConfiguration = adoptWK(WKPageConfigurationCreate());
585     WKPageConfigurationSetContext(pageConfiguration.get(), m_context.get());
586     WKPageConfigurationSetPageGroup(pageConfiguration.get(), m_pageGroup.get());
587     
588     if (options.useEphemeralSession) {
589         auto ephemeralDataStore = adoptWK(WKWebsiteDataStoreCreateNonPersistentDataStore());
590         WKPageConfigurationSetWebsiteDataStore(pageConfiguration.get(), ephemeralDataStore.get());
591     }
592
593     m_userContentController = adoptWK(WKUserContentControllerCreate());
594     WKPageConfigurationSetUserContentController(pageConfiguration.get(), userContentController());
595     return pageConfiguration;
596 }
597
598 void TestController::createWebViewWithOptions(const TestOptions& options)
599 {
600     auto configuration = generatePageConfiguration(options);
601
602     // Some preferences (notably mock scroll bars setting) currently cannot be re-applied to an existing view, so we need to set them now.
603     // FIXME: Migrate these preferences to WKContextConfigurationRef.
604     resetPreferencesToConsistentValues(options);
605
606     platformCreateWebView(configuration.get(), options);
607     WKPageUIClientV13 pageUIClient = {
608         { 13, m_mainWebView.get() },
609         0, // createNewPage_deprecatedForUseWithV0
610         0, // showPage
611         0, // close
612         0, // takeFocus
613         focus,
614         unfocus,
615         0, // runJavaScriptAlert_deprecatedForUseWithV0
616         0, // runJavaScriptAlert_deprecatedForUseWithV0
617         0, // runJavaScriptAlert_deprecatedForUseWithV0
618         0, // setStatusText
619         0, // mouseDidMoveOverElement_deprecatedForUseWithV0
620         0, // missingPluginButtonClicked
621         0, // didNotHandleKeyEvent
622         0, // didNotHandleWheelEvent
623         0, // toolbarsAreVisible
624         0, // setToolbarsAreVisible
625         0, // menuBarIsVisible
626         0, // setMenuBarIsVisible
627         0, // statusBarIsVisible
628         0, // setStatusBarIsVisible
629         0, // isResizable
630         0, // setIsResizable
631         getWindowFrame,
632         setWindowFrame,
633         runBeforeUnloadConfirmPanel,
634         0, // didDraw
635         0, // pageDidScroll
636         0, // exceededDatabaseQuota,
637         options.shouldHandleRunOpenPanel ? runOpenPanel : 0,
638         decidePolicyForGeolocationPermissionRequest,
639         0, // headerHeight
640         0, // footerHeight
641         0, // drawHeader
642         0, // drawFooter
643         printFrame,
644         runModal,
645         0, // didCompleteRubberBandForMainFrame
646         0, // saveDataToFileInDownloadsFolder
647         0, // shouldInterruptJavaScript
648         0, // createNewPage_deprecatedForUseWithV1
649         0, // mouseDidMoveOverElement
650         decidePolicyForNotificationPermissionRequest, // decidePolicyForNotificationPermissionRequest
651         0, // unavailablePluginButtonClicked_deprecatedForUseWithV1
652         0, // showColorPicker
653         0, // hideColorPicker
654         unavailablePluginButtonClicked,
655         0, // pinnedStateDidChange
656         0, // didBeginTrackingPotentialLongMousePress
657         0, // didRecognizeLongMousePress
658         0, // didCancelTrackingPotentialLongMousePress
659         0, // isPlayingAudioDidChange
660         decidePolicyForUserMediaPermissionRequest,
661         0, // didClickAutofillButton
662         0, // runJavaScriptAlert
663         0, // runJavaScriptConfirm
664         0, // runJavaScriptPrompt
665         0, // mediaSessionMetadataDidChange
666         createOtherPage,
667         runJavaScriptAlert,
668         0, // runJavaScriptConfirm
669         0, // runJavaScriptPrompt
670         checkUserMediaPermissionForOrigin,
671         0, // runBeforeUnloadConfirmPanel
672         0, // fullscreenMayReturnToInline
673         requestPointerLock,
674         0, // didLosePointerLock
675         0, // handleAutoplayEvent
676         0, // hasVideoInPictureInPictureDidChange
677         0, // didExceedBackgroundResourceLimitWhileInForeground
678         0, // didResignInputElementStrongPasswordAppearance
679         0, // requestStorageAccessConfirm
680         shouldAllowDeviceOrientationAndMotionAccess
681     };
682     WKPageSetPageUIClient(m_mainWebView->page(), &pageUIClient.base);
683
684     WKPageNavigationClientV3 pageNavigationClient = {
685         { 3, this },
686         decidePolicyForNavigationAction,
687         decidePolicyForNavigationResponse,
688         decidePolicyForPluginLoad,
689         0, // didStartProvisionalNavigation
690         didReceiveServerRedirectForProvisionalNavigation,
691         0, // didFailProvisionalNavigation
692         didCommitNavigation,
693         didFinishNavigation,
694         0, // didFailNavigation
695         0, // didFailProvisionalLoadInSubframe
696         0, // didFinishDocumentLoad
697         0, // didSameDocumentNavigation
698         0, // renderingProgressDidChange
699         canAuthenticateAgainstProtectionSpace,
700         didReceiveAuthenticationChallenge,
701         processDidCrash,
702         copyWebCryptoMasterKey,
703         didBeginNavigationGesture,
704         willEndNavigationGesture,
705         didEndNavigationGesture,
706         didRemoveNavigationGestureSnapshot,
707         0, // webProcessDidTerminate
708         0, // contentRuleListNotification
709         copySignedPublicKeyAndChallengeString
710     };
711     WKPageSetPageNavigationClient(m_mainWebView->page(), &pageNavigationClient.base);
712
713     WKContextDownloadClientV1 downloadClient = {
714         { 1, this },
715         downloadDidStart,
716         0, // didReceiveAuthenticationChallenge
717         0, // didReceiveResponse
718         0, // didReceiveData
719         0, // shouldDecodeSourceDataOfMIMEType
720         decideDestinationWithSuggestedFilename,
721         0, // didCreateDestination
722         downloadDidFinish,
723         downloadDidFail,
724         downloadDidCancel,
725         0, // processDidCrash;
726         downloadDidReceiveServerRedirectToURL
727     };
728     WKContextSetDownloadClient(context(), &downloadClient.base);
729     
730     // this should just be done on the page?
731     WKPageInjectedBundleClientV1 injectedBundleClient = {
732         { 1, this },
733         didReceivePageMessageFromInjectedBundle,
734         nullptr,
735         didReceiveSynchronousPageMessageFromInjectedBundleWithListener,
736     };
737     WKPageSetPageInjectedBundleClient(m_mainWebView->page(), &injectedBundleClient.base);
738
739     m_mainWebView->didInitializeClients();
740
741     // Generally, the tests should default to running at 1x. updateWindowScaleForTest() will adjust the scale to
742     // something else for specific tests that need to run at a different window scale.
743     m_mainWebView->changeWindowScaleIfNeeded(1);
744 }
745
746 void TestController::ensureViewSupportsOptionsForTest(const TestInvocation& test)
747 {
748     auto options = test.options();
749
750     if (m_mainWebView) {
751         if (m_mainWebView->viewSupportsOptions(options))
752             return;
753
754         willDestroyWebView();
755
756         WKPageSetPageUIClient(m_mainWebView->page(), nullptr);
757         WKPageSetPageNavigationClient(m_mainWebView->page(), nullptr);
758         WKPageClose(m_mainWebView->page());
759
760         m_mainWebView = nullptr;
761     }
762
763     createWebViewWithOptions(options);
764
765     if (!resetStateToConsistentValues(options, ResetStage::BeforeTest))
766         TestInvocation::dumpWebProcessUnresponsiveness("<unknown> - TestController::run - Failed to reset state to consistent values\n");
767 }
768
769 void TestController::resetPreferencesToConsistentValues(const TestOptions& options)
770 {
771     // Reset preferences
772     WKPreferencesRef preferences = platformPreferences();
773     WKPreferencesResetTestRunnerOverrides(preferences);
774
775     WKPreferencesEnableAllExperimentalFeatures(preferences);
776     for (const auto& experimentalFeature : options.experimentalFeatures)
777         WKPreferencesSetExperimentalFeatureForKey(preferences, experimentalFeature.value, toWK(experimentalFeature.key).get());
778
779     WKPreferencesResetAllInternalDebugFeatures(preferences);
780
781     // Set internal features that have different default values for testing.
782     static WKStringRef asyncOverflowScrollingFeature = WKStringCreateWithUTF8CString("AsyncOverflowScrollingEnabled");
783     WKPreferencesSetInternalDebugFeatureForKey(preferences, false, asyncOverflowScrollingFeature);
784
785     static WKStringRef asyncFrameScrollingFeature = WKStringCreateWithUTF8CString("AsyncFrameScrollingEnabled");
786     WKPreferencesSetInternalDebugFeatureForKey(preferences, false, asyncFrameScrollingFeature);
787
788     for (const auto& internalDebugFeature : options.internalDebugFeatures)
789         WKPreferencesSetInternalDebugFeatureForKey(preferences, internalDebugFeature.value, toWK(internalDebugFeature.key).get());
790
791     WKPreferencesSetProcessSwapOnNavigationEnabled(preferences, options.contextOptions.shouldEnableProcessSwapOnNavigation());
792     WKPreferencesSetPageVisibilityBasedProcessSuppressionEnabled(preferences, options.enableAppNap);
793     WKPreferencesSetOfflineWebApplicationCacheEnabled(preferences, true);
794     WKPreferencesSetSubpixelAntialiasedLayerTextEnabled(preferences, false);
795     WKPreferencesSetXSSAuditorEnabled(preferences, false);
796     WKPreferencesSetWebAudioEnabled(preferences, true);
797     WKPreferencesSetMediaDevicesEnabled(preferences, true);
798     WKPreferencesSetWebRTCMDNSICECandidatesEnabled(preferences, false);
799     WKPreferencesSetDeveloperExtrasEnabled(preferences, true);
800     WKPreferencesSetJavaScriptRuntimeFlags(preferences, kWKJavaScriptRuntimeFlagsAllEnabled);
801     WKPreferencesSetJavaScriptCanOpenWindowsAutomatically(preferences, true);
802     WKPreferencesSetJavaScriptCanAccessClipboard(preferences, true);
803     WKPreferencesSetDOMPasteAllowed(preferences, options.domPasteAllowed);
804     WKPreferencesSetUniversalAccessFromFileURLsAllowed(preferences, true);
805     WKPreferencesSetFileAccessFromFileURLsAllowed(preferences, true);
806 #if ENABLE(FULLSCREEN_API)
807     WKPreferencesSetFullScreenEnabled(preferences, true);
808 #endif
809     WKPreferencesSetAsynchronousPluginInitializationEnabled(preferences, false);
810     WKPreferencesSetAsynchronousPluginInitializationEnabledForAllPlugins(preferences, false);
811     WKPreferencesSetArtificialPluginInitializationDelayEnabled(preferences, false);
812     WKPreferencesSetTabToLinksEnabled(preferences, false);
813     WKPreferencesSetInteractiveFormValidationEnabled(preferences, true);
814     WKPreferencesSetDataTransferItemsEnabled(preferences, true);
815     WKPreferencesSetCustomPasteboardDataEnabled(preferences, true);
816     WKPreferencesSetDialogElementEnabled(preferences, true);
817
818     WKPreferencesSetMockScrollbarsEnabled(preferences, options.useMockScrollbars);
819     WKPreferencesSetNeedsSiteSpecificQuirks(preferences, options.needsSiteSpecificQuirks);
820     WKPreferencesSetAttachmentElementEnabled(preferences, options.enableAttachmentElement);
821     WKPreferencesSetMenuItemElementEnabled(preferences, options.enableMenuItemElement);
822     WKPreferencesSetKeygenElementEnabled(preferences, options.enableKeygenElement);
823     WKPreferencesSetModernMediaControlsEnabled(preferences, options.enableModernMediaControls);
824     WKPreferencesSetWebAuthenticationEnabled(preferences, options.enableWebAuthentication);
825     WKPreferencesSetWebAuthenticationLocalAuthenticatorEnabled(preferences, options.enableWebAuthenticationLocalAuthenticator);
826     WKPreferencesSetIsSecureContextAttributeEnabled(preferences, options.enableIsSecureContextAttribute);
827     WKPreferencesSetAllowCrossOriginSubresourcesToAskForCredentials(preferences, options.allowCrossOriginSubresourcesToAskForCredentials);
828     WKPreferencesSetColorFilterEnabled(preferences, options.enableColorFilter);
829     WKPreferencesSetPunchOutWhiteBackgroundsInDarkMode(preferences, options.punchOutWhiteBackgroundsInDarkMode);
830     WKPreferencesSetPageCacheEnabled(preferences, options.enablePageCache);
831     WKPreferencesSetLazyImageLoadingEnabled(preferences, options.enableLazyImageLoading);
832
833     static WKStringRef defaultTextEncoding = WKStringCreateWithUTF8CString("ISO-8859-1");
834     WKPreferencesSetDefaultTextEncodingName(preferences, defaultTextEncoding);
835
836     static WKStringRef standardFontFamily = WKStringCreateWithUTF8CString("Times");
837     static WKStringRef cursiveFontFamily = WKStringCreateWithUTF8CString("Apple Chancery");
838     static WKStringRef fantasyFontFamily = WKStringCreateWithUTF8CString("Papyrus");
839     static WKStringRef fixedFontFamily = WKStringCreateWithUTF8CString("Courier");
840     static WKStringRef pictographFontFamily = WKStringCreateWithUTF8CString("Apple Color Emoji");
841     static WKStringRef sansSerifFontFamily = WKStringCreateWithUTF8CString("Helvetica");
842     static WKStringRef serifFontFamily = WKStringCreateWithUTF8CString("Times");
843
844     WKPreferencesSetMinimumFontSize(preferences, 0);
845     WKPreferencesSetStandardFontFamily(preferences, standardFontFamily);
846     WKPreferencesSetCursiveFontFamily(preferences, cursiveFontFamily);
847     WKPreferencesSetFantasyFontFamily(preferences, fantasyFontFamily);
848     WKPreferencesSetFixedFontFamily(preferences, fixedFontFamily);
849     WKPreferencesSetPictographFontFamily(preferences, pictographFontFamily);
850     WKPreferencesSetSansSerifFontFamily(preferences, sansSerifFontFamily);
851     WKPreferencesSetSerifFontFamily(preferences, serifFontFamily);
852     WKPreferencesSetAsynchronousSpellCheckingEnabled(preferences, false);
853 #if ENABLE(MEDIA_SOURCE)
854     WKPreferencesSetMediaSourceEnabled(preferences, true);
855     WKPreferencesSetSourceBufferChangeTypeEnabled(preferences, true);
856 #endif
857
858     WKPreferencesSetHiddenPageDOMTimerThrottlingEnabled(preferences, false);
859     WKPreferencesSetHiddenPageCSSAnimationSuspensionEnabled(preferences, false);
860
861     WKPreferencesSetAcceleratedDrawingEnabled(preferences, m_shouldUseAcceleratedDrawing || options.useAcceleratedDrawing);
862     // FIXME: We should be testing the default.
863     WKPreferencesSetStorageBlockingPolicy(preferences, kWKAllowAllStorage);
864
865     WKPreferencesSetFetchAPIKeepAliveEnabled(preferences, true);
866     WKPreferencesSetResourceTimingEnabled(preferences, true);
867     WKPreferencesSetUserTimingEnabled(preferences, true);
868     WKPreferencesSetMediaPreloadingEnabled(preferences, true);
869     WKPreferencesSetMediaPlaybackAllowsInline(preferences, true);
870     WKPreferencesSetInlineMediaPlaybackRequiresPlaysInlineAttribute(preferences, false);
871     WKPreferencesSetBeaconAPIEnabled(preferences, true);
872     WKPreferencesSetDirectoryUploadEnabled(preferences, true);
873
874     WKHTTPCookieStoreDeleteAllCookies(WKWebsiteDataStoreGetHTTPCookieStore(WKContextGetWebsiteDataStore(m_context.get())), nullptr, nullptr);
875
876     WKPreferencesSetMockCaptureDevicesEnabled(preferences, true);
877     
878     WKPreferencesSetLargeImageAsyncDecodingEnabled(preferences, false);
879
880     WKPreferencesSetInspectorAdditionsEnabled(preferences, options.enableInspectorAdditions);
881
882     WKPreferencesSetStorageAccessAPIEnabled(preferences, true);
883     
884     WKPreferencesSetAccessibilityObjectModelEnabled(preferences, true);
885     WKPreferencesSetCSSOMViewScrollingAPIEnabled(preferences, true);
886     WKPreferencesSetMediaCapabilitiesEnabled(preferences, true);
887
888     WKPreferencesSetRestrictedHTTPResponseAccess(preferences, true);
889
890     WKPreferencesSetServerTimingEnabled(preferences, true);
891
892     WKPreferencesSetWebSQLDisabled(preferences, false);
893
894     WKPreferencesSetMediaPlaybackRequiresUserGesture(preferences, false);
895     WKPreferencesSetVideoPlaybackRequiresUserGesture(preferences, false);
896     WKPreferencesSetAudioPlaybackRequiresUserGesture(preferences, false);
897
898     platformResetPreferencesToConsistentValues();
899 }
900
901 bool TestController::resetStateToConsistentValues(const TestOptions& options, ResetStage resetStage)
902 {
903     SetForScope<State> changeState(m_state, Resetting);
904     m_beforeUnloadReturnValue = true;
905
906     // This setting differs between the antique and modern Mac WebKit2 API.
907     // For now, maintain the antique behavior, because some tests depend on it!
908     // FIXME: We should be testing the default.
909     WKPageSetBackgroundExtendsBeyondPage(m_mainWebView->page(), false);
910
911     WKPageSetCustomUserAgent(m_mainWebView->page(), nullptr);
912
913     WKRetainPtr<WKStringRef> messageName = adoptWK(WKStringCreateWithUTF8CString("Reset"));
914     WKRetainPtr<WKMutableDictionaryRef> resetMessageBody = adoptWK(WKMutableDictionaryCreate());
915
916     WKRetainPtr<WKStringRef> shouldGCKey = adoptWK(WKStringCreateWithUTF8CString("ShouldGC"));
917     WKRetainPtr<WKBooleanRef> shouldGCValue = adoptWK(WKBooleanCreate(m_gcBetweenTests));
918     WKDictionarySetItem(resetMessageBody.get(), shouldGCKey.get(), shouldGCValue.get());
919
920     WKRetainPtr<WKStringRef> allowedHostsKey = adoptWK(WKStringCreateWithUTF8CString("AllowedHosts"));
921     WKRetainPtr<WKMutableArrayRef> allowedHostsValue = adoptWK(WKMutableArrayCreate());
922     for (auto& host : m_allowedHosts) {
923         WKRetainPtr<WKStringRef> wkHost = adoptWK(WKStringCreateWithUTF8CString(host.c_str()));
924         WKArrayAppendItem(allowedHostsValue.get(), wkHost.get());
925     }
926     WKDictionarySetItem(resetMessageBody.get(), allowedHostsKey.get(), allowedHostsValue.get());
927
928     if (options.jscOptions.length()) {
929         WKRetainPtr<WKStringRef> jscOptionsKey = adoptWK(WKStringCreateWithUTF8CString("JSCOptions"));
930         WKRetainPtr<WKStringRef> jscOptionsValue = adoptWK(WKStringCreateWithUTF8CString(options.jscOptions.c_str()));
931         WKDictionarySetItem(resetMessageBody.get(), jscOptionsKey.get(), jscOptionsValue.get());
932     }
933
934 #if PLATFORM(COCOA)
935     WebCoreTestSupport::setAdditionalSupportedImageTypesForTesting(options.additionalSupportedImageTypes.c_str());
936 #endif
937
938     WKPagePostMessageToInjectedBundle(TestController::singleton().mainWebView()->page(), messageName.get(), resetMessageBody.get());
939
940     WKContextSetShouldUseFontSmoothing(TestController::singleton().context(), false);
941
942     WKContextSetCacheModel(TestController::singleton().context(), kWKCacheModelDocumentBrowser);
943
944     WKContextClearCachedCredentials(TestController::singleton().context());
945
946     auto websiteDataStore = WKContextGetWebsiteDataStore(TestController::singleton().context());
947     WKWebsiteDataStoreClearAllDeviceOrientationPermissions(websiteDataStore);
948
949     clearIndexedDatabases();
950     clearLocalStorage();
951
952     clearServiceWorkerRegistrations();
953     clearDOMCaches();
954
955     WKContextSetAllowsAnySSLCertificateForServiceWorkerTesting(platformContext(), true);
956
957     WKContextClearCurrentModifierStateForTesting(TestController::singleton().context());
958
959     // FIXME: This function should also ensure that there is only one page open.
960
961     // Reset the EventSender for each test.
962     m_eventSenderProxy = makeUnique<EventSenderProxy>(this);
963
964     // FIXME: Is this needed? Nothing in TestController changes preferences during tests, and if there is
965     // some other code doing this, it should probably be responsible for cleanup too.
966     resetPreferencesToConsistentValues(options);
967
968 #if PLATFORM(GTK)
969     WKTextCheckerContinuousSpellCheckingEnabledStateChanged(true);
970 #endif
971
972     // Make sure the view is in the window (a test can unparent it).
973     m_mainWebView->addToWindow();
974
975     // In the case that a test using the chrome input field failed, be sure to clean up for the next test.
976     m_mainWebView->removeChromeInputField();
977     m_mainWebView->focus();
978
979     // Re-set to the default backing scale factor by setting the custom scale factor to 0.
980     WKPageSetCustomBackingScaleFactor(m_mainWebView->page(), 0);
981
982     WKPageClearWheelEventTestTrigger(m_mainWebView->page());
983
984     WKPageSetMuted(m_mainWebView->page(), true);
985
986     WKPageClearUserMediaState(m_mainWebView->page());
987
988     // Reset notification permissions
989     m_webNotificationProvider.reset();
990
991     // Reset Geolocation permissions.
992     m_geolocationPermissionRequests.clear();
993     m_isGeolocationPermissionSet = false;
994     m_isGeolocationPermissionAllowed = false;
995
996     // Reset UserMedia permissions.
997     m_userMediaPermissionRequests.clear();
998     m_cachedUserMediaPermissions.clear();
999     setUserMediaPermission(true);
1000
1001     // Reset Custom Policy Delegate.
1002     setCustomPolicyDelegate(false, false);
1003
1004     // Reset Content Extensions.
1005     resetContentExtensions();
1006
1007     m_shouldDownloadUndisplayableMIMETypes = false;
1008
1009     m_shouldAllowDeviceOrientationAndMotionAccess = false;
1010
1011     m_workQueueManager.clearWorkQueue();
1012
1013     m_rejectsProtectionSpaceAndContinueForAuthenticationChallenges = false;
1014     m_handlesAuthenticationChallenges = false;
1015     m_authenticationUsername = String();
1016     m_authenticationPassword = String();
1017
1018     setBlockAllPlugins(false);
1019     setPluginSupportedMode({ });
1020
1021     m_shouldLogDownloadCallbacks = false;
1022     m_shouldLogHistoryClientCallbacks = false;
1023     m_shouldLogCanAuthenticateAgainstProtectionSpace = false;
1024
1025     setHidden(false);
1026
1027     platformResetStateToConsistentValues(options);
1028
1029     m_shouldDecideNavigationPolicyAfterDelay = false;
1030     m_shouldDecideResponsePolicyAfterDelay = false;
1031
1032     setNavigationGesturesEnabled(false);
1033     
1034     setIgnoresViewportScaleLimits(options.ignoresViewportScaleLimits);
1035
1036     m_openPanelFileURLs = nullptr;
1037 #if PLATFORM(IOS_FAMILY)
1038     m_openPanelFileURLsMediaIcon = nullptr;
1039 #endif
1040
1041     setAllowsAnySSLCertificate(true);
1042
1043     statisticsResetToConsistentState();
1044     
1045     clearAdClickAttribution();
1046
1047     m_didReceiveServerRedirectForProvisionalNavigation = false;
1048     m_serverTrustEvaluationCallbackCallsCount = 0;
1049     m_shouldDismissJavaScriptAlertsAsynchronously = false;
1050
1051     // Reset main page back to about:blank
1052     m_doneResetting = false;
1053     WKPageLoadURL(m_mainWebView->page(), blankURL());
1054     runUntil(m_doneResetting, m_currentInvocation->shortTimeout());
1055     if (!m_doneResetting)
1056         return false;
1057     
1058     if (resetStage == ResetStage::AfterTest)
1059         updateLiveDocumentsAfterTest();
1060
1061     return m_doneResetting;
1062 }
1063
1064 void TestController::updateLiveDocumentsAfterTest()
1065 {
1066     if (!m_checkForWorldLeaks)
1067         return;
1068
1069     AsyncTask([]() {
1070         // After each test, we update the list of live documents so that we can detect when an abandoned document first showed up.
1071         WKRetainPtr<WKStringRef> messageName = adoptWK(WKStringCreateWithUTF8CString("GetLiveDocuments"));
1072         WKPagePostMessageToInjectedBundle(TestController::singleton().mainWebView()->page(), messageName.get(), nullptr);
1073     }, 5_s).run();
1074 }
1075
1076 void TestController::checkForWorldLeaks()
1077 {
1078     if (!m_checkForWorldLeaks || !TestController::singleton().mainWebView())
1079         return;
1080
1081     AsyncTask([]() {
1082         // This runs at the end of a series of tests. It clears caches, runs a GC and then fetches the list of documents.
1083         WKRetainPtr<WKStringRef> messageName = adoptWK(WKStringCreateWithUTF8CString("CheckForWorldLeaks"));
1084         WKPagePostMessageToInjectedBundle(TestController::singleton().mainWebView()->page(), messageName.get(), nullptr);
1085     }, 20_s).run();
1086 }
1087
1088 void TestController::dumpResponse(const String& result)
1089 {
1090     unsigned resultLength = result.length();
1091     printf("Content-Type: text/plain\n");
1092     printf("Content-Length: %u\n", resultLength);
1093     fwrite(result.utf8().data(), 1, resultLength, stdout);
1094     printf("#EOF\n");
1095     fprintf(stderr, "#EOF\n");
1096     fflush(stdout);
1097     fflush(stderr);
1098 }
1099
1100 void TestController::findAndDumpWebKitProcessIdentifiers()
1101 {
1102 #if PLATFORM(COCOA)
1103     dumpResponse(makeString(TestController::webProcessName(), ": ",
1104         WKPageGetProcessIdentifier(TestController::singleton().mainWebView()->page()), '\n',
1105         TestController::networkProcessName(), ": ",
1106         WKContextGetNetworkProcessIdentifier(m_context.get()), '\n'));
1107 #else
1108     dumpResponse("\n"_s);
1109 #endif
1110 }
1111
1112 void TestController::findAndDumpWorldLeaks()
1113 {
1114     if (!m_checkForWorldLeaks)
1115         return;
1116
1117     checkForWorldLeaks();
1118
1119     StringBuilder builder;
1120     
1121     if (m_abandonedDocumentInfo.size()) {
1122         for (const auto& it : m_abandonedDocumentInfo) {
1123             auto documentURL = it.value.abandonedDocumentURL;
1124             if (documentURL.isEmpty())
1125                 documentURL = "(no url)";
1126             builder.append("TEST: ");
1127             builder.append(it.value.testURL);
1128             builder.append('\n');
1129             builder.append("ABANDONED DOCUMENT: ");
1130             builder.append(documentURL);
1131             builder.append('\n');
1132         }
1133     } else
1134         builder.append("no abandoned documents\n");
1135
1136     dumpResponse(builder.toString());
1137 }
1138
1139 void TestController::willDestroyWebView()
1140 {
1141     // Before we kill the web view, look for abandoned documents before that web process goes away.
1142     checkForWorldLeaks();
1143 }
1144
1145 void TestController::terminateWebContentProcess()
1146 {
1147     WKPageTerminate(m_mainWebView->page());
1148 }
1149
1150 void TestController::reattachPageToWebProcess()
1151 {
1152     // Loading a web page is the only way to reattach an existing page to a process.
1153     SetForScope<State> changeState(m_state, Resetting);
1154     m_doneResetting = false;
1155     WKPageLoadURL(m_mainWebView->page(), blankURL());
1156     runUntil(m_doneResetting, noTimeout);
1157 }
1158
1159 const char* TestController::webProcessName()
1160 {
1161     // FIXME: Find a way to not hardcode the process name.
1162 #if PLATFORM(IOS_FAMILY) && !PLATFORM(IOS_FAMILY_SIMULATOR)
1163     return "com.apple.WebKit.WebContent";
1164 #elif PLATFORM(COCOA)
1165     return "com.apple.WebKit.WebContent.Development";
1166 #elif PLATFORM(GTK)
1167     return "WebKitWebProcess";
1168 #elif PLATFORM(WPE)
1169     return "WPEWebProcess";
1170 #else
1171     return "WebProcess";
1172 #endif
1173 }
1174
1175 const char* TestController::networkProcessName()
1176 {
1177     // FIXME: Find a way to not hardcode the process name.
1178 #if PLATFORM(IOS_FAMILY) && !PLATFORM(IOS_FAMILY_SIMULATOR)
1179     return "com.apple.WebKit.Networking";
1180 #elif PLATFORM(COCOA)
1181     return "com.apple.WebKit.Networking.Development";
1182 #elif PLATFORM(GTK)
1183     return "WebKitNetworkProcess";
1184 #elif PLATFORM(WPE)
1185     return "WPENetworkProcess";
1186 #else
1187     return "NetworkProcess";
1188 #endif
1189 }
1190
1191 #if !PLATFORM(COCOA)
1192 void TestController::setAllowsAnySSLCertificate(bool allows)
1193 {
1194     m_allowsAnySSLCertificate = allows;
1195     WKContextSetAllowsAnySSLCertificateForWebSocketTesting(platformContext(), allows);
1196 }
1197 #endif
1198
1199 static std::string testPath(WKURLRef url)
1200 {
1201     auto scheme = adoptWK(WKURLCopyScheme(url));
1202     if (WKStringIsEqualToUTF8CStringIgnoringCase(scheme.get(), "file")) {
1203         auto path = adoptWK(WKURLCopyPath(url));
1204         auto buffer = std::vector<char>(WKStringGetMaximumUTF8CStringSize(path.get()));
1205         auto length = WKStringGetUTF8CString(path.get(), buffer.data(), buffer.size());
1206         RELEASE_ASSERT(length > 0);
1207 #if OS(WINDOWS)
1208         // Remove the first '/' if it starts with something like "/C:/".
1209         if (length >= 4 && buffer[0] == '/' && buffer[2] == ':' && buffer[3] == '/')
1210             return std::string(buffer.data() + 1, length - 1);
1211 #endif
1212         return std::string(buffer.data(), length - 1);
1213     }
1214     return std::string();
1215 }
1216
1217 static WKURLRef createTestURL(const char* pathOrURL)
1218 {
1219     if (strstr(pathOrURL, "http://") || strstr(pathOrURL, "https://") || strstr(pathOrURL, "file://"))
1220         return WKURLCreateWithUTF8CString(pathOrURL);
1221
1222     // Creating from filesytem path.
1223     size_t length = strlen(pathOrURL);
1224     if (!length)
1225         return 0;
1226
1227 #if PLATFORM(WIN)
1228     bool isAbsolutePath = false;
1229     if (strlen(pathOrURL) >= 3 && pathOrURL[1] == ':' && pathOrURL[2] == pathSeparator)
1230         isAbsolutePath = true;
1231 #else
1232     bool isAbsolutePath = pathOrURL[0] == pathSeparator;
1233 #endif
1234     const char* filePrefix = "file://";
1235     static const size_t prefixLength = strlen(filePrefix);
1236
1237     UniqueArray<char> buffer;
1238     if (isAbsolutePath) {
1239         buffer = makeUniqueArray<char>(prefixLength + length + 1);
1240         strcpy(buffer.get(), filePrefix);
1241         strcpy(buffer.get() + prefixLength, pathOrURL);
1242     } else {
1243         buffer = makeUniqueArray<char>(prefixLength + PATH_MAX + length + 2); // 1 for the pathSeparator
1244         strcpy(buffer.get(), filePrefix);
1245         if (!getcwd(buffer.get() + prefixLength, PATH_MAX))
1246             return 0;
1247         size_t numCharacters = strlen(buffer.get());
1248         buffer[numCharacters] = pathSeparator;
1249         strcpy(buffer.get() + numCharacters + 1, pathOrURL);
1250     }
1251
1252     return WKURLCreateWithUTF8CString(buffer.get());
1253 }
1254
1255 static bool parseBooleanTestHeaderValue(const std::string& value)
1256 {
1257     if (value == "true")
1258         return true;
1259     if (value == "false")
1260         return false;
1261
1262     LOG_ERROR("Found unexpected value '%s' for boolean option. Expected 'true' or 'false'.", value.c_str());
1263     return false;
1264 }
1265
1266 static std::string parseStringTestHeaderValueAsRelativePath(const std::string& value, const std::string& pathOrURL)
1267 {
1268     WKRetainPtr<WKURLRef> baseURL = adoptWK(createTestURL(pathOrURL.c_str()));
1269     WKRetainPtr<WKURLRef> relativeURL = adoptWK(WKURLCreateWithBaseURL(baseURL.get(), value.c_str()));
1270     return toSTD(adoptWK(WKURLCopyPath(relativeURL.get())));
1271 }
1272
1273 static void updateTestOptionsFromTestHeader(TestOptions& testOptions, const std::string& pathOrURL, const std::string& absolutePath)
1274 {
1275     std::string filename = absolutePath;
1276     if (filename.empty()) {
1277         // Gross. Need to reduce conversions between all the string types and URLs.
1278         WKRetainPtr<WKURLRef> wkURL = adoptWK(createTestURL(pathOrURL.c_str()));
1279         filename = testPath(wkURL.get());
1280     }
1281
1282     if (filename.empty())
1283         return;
1284
1285     std::string options;
1286     std::ifstream testFile(filename.data());
1287     if (!testFile.good())
1288         return;
1289     getline(testFile, options);
1290     std::string beginString("webkit-test-runner [ ");
1291     std::string endString(" ]");
1292     size_t beginLocation = options.find(beginString);
1293     if (beginLocation == std::string::npos)
1294         return;
1295     size_t endLocation = options.find(endString, beginLocation);
1296     if (endLocation == std::string::npos) {
1297         LOG_ERROR("Could not find end of test header in %s", filename.c_str());
1298         return;
1299     }
1300     std::string pairString = options.substr(beginLocation + beginString.size(), endLocation - (beginLocation + beginString.size()));
1301     size_t pairStart = 0;
1302     while (pairStart < pairString.size()) {
1303         size_t pairEnd = pairString.find(" ", pairStart);
1304         if (pairEnd == std::string::npos)
1305             pairEnd = pairString.size();
1306         size_t equalsLocation = pairString.find("=", pairStart);
1307         if (equalsLocation == std::string::npos) {
1308             LOG_ERROR("Malformed option in test header (could not find '=' character) in %s", filename.c_str());
1309             break;
1310         }
1311         auto key = pairString.substr(pairStart, equalsLocation - pairStart);
1312         auto value = pairString.substr(equalsLocation + 1, pairEnd - (equalsLocation + 1));
1313
1314         if (!key.rfind("experimental:")) {
1315             key = key.substr(13);
1316             testOptions.experimentalFeatures.add(String(key.c_str()), parseBooleanTestHeaderValue(value));
1317         }
1318
1319         if (!key.rfind("internal:")) {
1320             key = key.substr(9);
1321             testOptions.internalDebugFeatures.add(String(key.c_str()), parseBooleanTestHeaderValue(value));
1322         }
1323
1324         if (key == "language")
1325             testOptions.contextOptions.overrideLanguages = String(value.c_str()).split(',');
1326         else if (key == "useThreadedScrolling")
1327             testOptions.useThreadedScrolling = parseBooleanTestHeaderValue(value);
1328         else if (key == "useAcceleratedDrawing")
1329             testOptions.useAcceleratedDrawing = parseBooleanTestHeaderValue(value);
1330         else if (key == "useFlexibleViewport")
1331             testOptions.useFlexibleViewport = parseBooleanTestHeaderValue(value);
1332         else if (key == "useDataDetection")
1333             testOptions.useDataDetection = parseBooleanTestHeaderValue(value);
1334         else if (key == "useMockScrollbars")
1335             testOptions.useMockScrollbars = parseBooleanTestHeaderValue(value);
1336         else if (key == "needsSiteSpecificQuirks")
1337             testOptions.needsSiteSpecificQuirks = parseBooleanTestHeaderValue(value);
1338         else if (key == "ignoresViewportScaleLimits")
1339             testOptions.ignoresViewportScaleLimits = parseBooleanTestHeaderValue(value);
1340         else if (key == "useCharacterSelectionGranularity")
1341             testOptions.useCharacterSelectionGranularity = parseBooleanTestHeaderValue(value);
1342         else if (key == "enableAttachmentElement")
1343             testOptions.enableAttachmentElement = parseBooleanTestHeaderValue(value);
1344         else if (key == "enableIntersectionObserver")
1345             testOptions.enableIntersectionObserver = parseBooleanTestHeaderValue(value);
1346         else if (key == "useEphemeralSession")
1347             testOptions.useEphemeralSession = parseBooleanTestHeaderValue(value);
1348         else if (key == "enableMenuItemElement")
1349             testOptions.enableMenuItemElement = parseBooleanTestHeaderValue(value);
1350         else if (key == "enableKeygenElement")
1351             testOptions.enableKeygenElement = parseBooleanTestHeaderValue(value);
1352         else if (key == "enableModernMediaControls")
1353             testOptions.enableModernMediaControls = parseBooleanTestHeaderValue(value);
1354         else if (key == "enablePointerLock")
1355             testOptions.enablePointerLock = parseBooleanTestHeaderValue(value);
1356         else if (key == "enableWebAuthentication")
1357             testOptions.enableWebAuthentication = parseBooleanTestHeaderValue(value);
1358         else if (key == "enableWebAuthenticationLocalAuthenticator")
1359             testOptions.enableWebAuthenticationLocalAuthenticator = parseBooleanTestHeaderValue(value);
1360         else if (key == "enableIsSecureContextAttribute")
1361             testOptions.enableIsSecureContextAttribute = parseBooleanTestHeaderValue(value);
1362         else if (key == "enableInspectorAdditions")
1363             testOptions.enableInspectorAdditions = parseBooleanTestHeaderValue(value);
1364         else if (key == "dumpJSConsoleLogInStdErr")
1365             testOptions.dumpJSConsoleLogInStdErr = parseBooleanTestHeaderValue(value);
1366         else if (key == "applicationManifest")
1367             testOptions.applicationManifest = parseStringTestHeaderValueAsRelativePath(value, pathOrURL);
1368         else if (key == "allowCrossOriginSubresourcesToAskForCredentials")
1369             testOptions.allowCrossOriginSubresourcesToAskForCredentials = parseBooleanTestHeaderValue(value);
1370         else if (key == "domPasteAllowed")
1371             testOptions.domPasteAllowed = parseBooleanTestHeaderValue(value);
1372         else if (key == "enableProcessSwapOnNavigation")
1373             testOptions.contextOptions.enableProcessSwapOnNavigation = parseBooleanTestHeaderValue(value);
1374         else if (key == "enableProcessSwapOnWindowOpen")
1375             testOptions.contextOptions.enableProcessSwapOnWindowOpen = parseBooleanTestHeaderValue(value);
1376         else if (key == "enableColorFilter")
1377             testOptions.enableColorFilter = parseBooleanTestHeaderValue(value);
1378         else if (key == "punchOutWhiteBackgroundsInDarkMode")
1379             testOptions.punchOutWhiteBackgroundsInDarkMode = parseBooleanTestHeaderValue(value);
1380         else if (key == "jscOptions")
1381             testOptions.jscOptions = value;
1382         else if (key == "additionalSupportedImageTypes")
1383             testOptions.additionalSupportedImageTypes = value;
1384         else if (key == "runSingly")
1385             testOptions.runSingly = parseBooleanTestHeaderValue(value);
1386         else if (key == "shouldIgnoreMetaViewport")
1387             testOptions.shouldIgnoreMetaViewport = parseBooleanTestHeaderValue(value);
1388         else if (key == "spellCheckingDots")
1389             testOptions.shouldShowSpellCheckingDots = parseBooleanTestHeaderValue(value);
1390         else if (key == "enableEditableImages")
1391             testOptions.enableEditableImages = parseBooleanTestHeaderValue(value);
1392         else if (key == "editable")
1393             testOptions.editable = parseBooleanTestHeaderValue(value);
1394         else if (key == "enableUndoManagerAPI")
1395             testOptions.enableUndoManagerAPI = parseBooleanTestHeaderValue(value);
1396         else if (key == "shouldHandleRunOpenPanel")
1397             testOptions.shouldHandleRunOpenPanel = parseBooleanTestHeaderValue(value);
1398         else if (key == "shouldPresentPopovers")
1399             testOptions.shouldPresentPopovers = parseBooleanTestHeaderValue(value);
1400         else if (key == "contentInset.top")
1401             testOptions.contentInsetTop = std::stod(value);
1402         else if (key == "ignoreSynchronousMessagingTimeouts")
1403             testOptions.contextOptions.ignoreSynchronousMessagingTimeouts = parseBooleanTestHeaderValue(value);
1404         else if (key == "contentMode")
1405             testOptions.contentMode = { value.c_str() };
1406         else if (key == "enableAppNap")
1407             testOptions.enableAppNap = parseBooleanTestHeaderValue(value);
1408         else if (key == "enablePageCache")
1409             testOptions.enablePageCache = parseBooleanTestHeaderValue(value);
1410         else if (key == "enableLazyImageLoading")
1411             testOptions.enableLazyImageLoading = parseBooleanTestHeaderValue(value);
1412         else if (key == "allowsLinkPreview")
1413             testOptions.allowsLinkPreview = parseBooleanTestHeaderValue(value);
1414         pairStart = pairEnd + 1;
1415     }
1416 }
1417
1418 TestOptions TestController::testOptionsForTest(const TestCommand& command) const
1419 {
1420     TestOptions options(command.pathOrURL);
1421
1422     options.useRemoteLayerTree = m_shouldUseRemoteLayerTree;
1423     options.shouldShowWebView = m_shouldShowWebView;
1424
1425     updatePlatformSpecificTestOptionsForTest(options, command.pathOrURL);
1426     updateTestOptionsFromTestHeader(options, command.pathOrURL, command.absolutePath);
1427     platformAddTestOptions(options);
1428
1429     return options;
1430 }
1431
1432 void TestController::updateWebViewSizeForTest(const TestInvocation& test)
1433 {
1434     unsigned width = viewWidth;
1435     unsigned height = viewHeight;
1436     if (test.options().isSVGTest) {
1437         width = w3cSVGViewWidth;
1438         height = w3cSVGViewHeight;
1439     }
1440
1441     mainWebView()->resizeTo(width, height);
1442 }
1443
1444 void TestController::updateWindowScaleForTest(PlatformWebView* view, const TestInvocation& test)
1445 {
1446     view->changeWindowScaleIfNeeded(test.options().deviceScaleFactor);
1447 }
1448
1449 void TestController::configureViewForTest(const TestInvocation& test)
1450 {
1451     ensureViewSupportsOptionsForTest(test);
1452     updateWebViewSizeForTest(test);
1453     updateWindowScaleForTest(mainWebView(), test);
1454     configureContentExtensionForTest(test);
1455     platformConfigureViewForTest(test);
1456 }
1457
1458 #if ENABLE(CONTENT_EXTENSIONS) && !PLATFORM(COCOA)
1459 struct ContentExtensionStoreCallbackContext {
1460     explicit ContentExtensionStoreCallbackContext(TestController& controller)
1461         : testController(controller)
1462     {
1463     }
1464
1465     TestController& testController;
1466     uint32_t status { kWKUserContentExtensionStoreSuccess };
1467     WKRetainPtr<WKUserContentFilterRef> filter;
1468     bool done { false };
1469 };
1470
1471 static void contentExtensionStoreCallback(WKUserContentFilterRef filter, uint32_t status, void* userData)
1472 {
1473     auto* context = static_cast<ContentExtensionStoreCallbackContext*>(userData);
1474     context->status = status;
1475     context->filter = filter ? adoptWK(filter) : nullptr;
1476     context->done = true;
1477     context->testController.notifyDone();
1478 }
1479
1480 static std::string contentExtensionJSONPath(WKURLRef url)
1481 {
1482     auto path = testPath(url);
1483     if (path.length())
1484         return path + ".json";
1485
1486     auto p = adoptWK(WKURLCopyPath(url));
1487     auto buffer = std::vector<char>(WKStringGetMaximumUTF8CStringSize(p.get()));
1488     const auto length = WKStringGetUTF8CString(p.get(), buffer.data(), buffer.size());
1489     return std::string("LayoutTests/http/tests") + std::string(buffer.data(), length - 1) + ".json";
1490 }
1491 #endif
1492
1493 #if !PLATFORM(COCOA)
1494 #if ENABLE(CONTENT_EXTENSIONS)
1495 void TestController::configureContentExtensionForTest(const TestInvocation& test)
1496 {
1497     const char* contentExtensionsPath = libraryPathForTesting();
1498     if (!contentExtensionsPath)
1499         contentExtensionsPath = "/tmp/wktr-contentextensions";
1500
1501     if (!test.urlContains("contentextensions/")) {
1502         WKPageSetUserContentExtensionsEnabled(m_mainWebView->page(), false);
1503         return;
1504     }
1505
1506     std::string jsonFilePath(contentExtensionJSONPath(test.url()));
1507     std::ifstream jsonFile(jsonFilePath);
1508     if (!jsonFile.good()) {
1509         WTFLogAlways("Could not open file '%s'", jsonFilePath.c_str());
1510         return;
1511     }
1512
1513     std::string jsonFileContents {std::istreambuf_iterator<char>(jsonFile), std::istreambuf_iterator<char>()};
1514     auto jsonSource = adoptWK(WKStringCreateWithUTF8CString(jsonFileContents.c_str()));
1515
1516     auto storePath = adoptWK(WKStringCreateWithUTF8CString(contentExtensionsPath));
1517     auto extensionStore = adoptWK(WKUserContentExtensionStoreCreate(storePath.get()));
1518     ASSERT(extensionStore);
1519
1520     auto filterIdentifier = adoptWK(WKStringCreateWithUTF8CString("TestContentExtension"));
1521
1522     ContentExtensionStoreCallbackContext context(*this);
1523     WKUserContentExtensionStoreCompile(extensionStore.get(), filterIdentifier.get(), jsonSource.get(), &context, contentExtensionStoreCallback);
1524     runUntil(context.done, noTimeout);
1525     ASSERT(context.status == kWKUserContentExtensionStoreSuccess);
1526     ASSERT(context.filter);
1527
1528     WKPageSetUserContentExtensionsEnabled(mainWebView()->page(), true);
1529     WKUserContentControllerAddUserContentFilter(userContentController(), context.filter.get());
1530 }
1531
1532 void TestController::resetContentExtensions()
1533 {
1534     if (!mainWebView())
1535         return;
1536
1537     WKPageSetUserContentExtensionsEnabled(mainWebView()->page(), false);
1538
1539     const char* contentExtensionsPath = libraryPathForTesting();
1540     if (!contentExtensionsPath)
1541         return;
1542
1543     WKUserContentControllerRemoveAllUserContentFilters(userContentController());
1544
1545     auto storePath = adoptWK(WKStringCreateWithUTF8CString(contentExtensionsPath));
1546     auto extensionStore = adoptWK(WKUserContentExtensionStoreCreate(storePath.get()));
1547     ASSERT(extensionStore);
1548
1549     auto filterIdentifier = adoptWK(WKStringCreateWithUTF8CString("TestContentExtension"));
1550
1551     ContentExtensionStoreCallbackContext context(*this);
1552     WKUserContentExtensionStoreRemove(extensionStore.get(), filterIdentifier.get(), &context, contentExtensionStoreCallback);
1553     runUntil(context.done, noTimeout);
1554     ASSERT(!context.filter);
1555 }
1556 #else // ENABLE(CONTENT_EXTENSIONS)
1557 void TestController::configureContentExtensionForTest(const TestInvocation&)
1558 {
1559 }
1560
1561 void TestController::resetContentExtensions()
1562 {
1563 }
1564 #endif // ENABLE(CONTENT_EXTENSIONS)
1565 #endif // !PLATFORM(COCOA)
1566
1567 class CommandTokenizer {
1568 public:
1569     explicit CommandTokenizer(const std::string& input)
1570         : m_input(input)
1571         , m_posNextSeparator(0)
1572     {
1573         pump();
1574     }
1575
1576     bool hasNext() const;
1577     std::string next();
1578
1579 private:
1580     void pump();
1581     static const char kSeparator = '\'';
1582     const std::string& m_input;
1583     std::string m_next;
1584     size_t m_posNextSeparator;
1585 };
1586
1587 void CommandTokenizer::pump()
1588 {
1589     if (m_posNextSeparator == std::string::npos || m_posNextSeparator == m_input.size()) {
1590         m_next = std::string();
1591         return;
1592     }
1593     size_t start = m_posNextSeparator ? m_posNextSeparator + 1 : 0;
1594     m_posNextSeparator = m_input.find(kSeparator, start);
1595     size_t size = m_posNextSeparator == std::string::npos ? std::string::npos : m_posNextSeparator - start;
1596     m_next = std::string(m_input, start, size);
1597 }
1598
1599 std::string CommandTokenizer::next()
1600 {
1601     ASSERT(hasNext());
1602
1603     std::string oldNext = m_next;
1604     pump();
1605     return oldNext;
1606 }
1607
1608 bool CommandTokenizer::hasNext() const
1609 {
1610     return !m_next.empty();
1611 }
1612
1613 NO_RETURN static void die(const std::string& inputLine)
1614 {
1615     fprintf(stderr, "Unexpected input line: %s\n", inputLine.c_str());
1616     exit(1);
1617 }
1618
1619 static TestCommand parseInputLine(const std::string& inputLine)
1620 {
1621     TestCommand result;
1622     CommandTokenizer tokenizer(inputLine);
1623     if (!tokenizer.hasNext())
1624         die(inputLine);
1625
1626     std::string arg = tokenizer.next();
1627     result.pathOrURL = arg;
1628     while (tokenizer.hasNext()) {
1629         arg = tokenizer.next();
1630         if (arg == std::string("--timeout")) {
1631             std::string timeoutToken = tokenizer.next();
1632             result.timeout = Seconds::fromMilliseconds(atoi(timeoutToken.c_str()));
1633         } else if (arg == std::string("-p") || arg == std::string("--pixel-test")) {
1634             result.shouldDumpPixels = true;
1635             if (tokenizer.hasNext())
1636                 result.expectedPixelHash = tokenizer.next();
1637         } else if (arg == std::string("--dump-jsconsolelog-in-stderr"))
1638             result.dumpJSConsoleLogInStdErr = true;
1639         else if (arg == std::string("--absolutePath"))
1640             result.absolutePath = tokenizer.next();
1641         else
1642             die(inputLine);
1643     }
1644     return result;
1645 }
1646
1647 bool TestController::runTest(const char* inputLine)
1648 {
1649     AutodrainedPool pool;
1650     
1651     WKTextCheckerSetTestingMode(true);
1652     TestCommand command = parseInputLine(std::string(inputLine));
1653
1654     m_state = RunningTest;
1655     
1656     TestOptions options = testOptionsForTest(command);
1657
1658     WKRetainPtr<WKURLRef> wkURL = adoptWK(createTestURL(command.pathOrURL.c_str()));
1659     m_currentInvocation = makeUnique<TestInvocation>(wkURL.get(), options);
1660
1661     if (command.shouldDumpPixels || m_shouldDumpPixelsForAllTests)
1662         m_currentInvocation->setIsPixelTest(command.expectedPixelHash);
1663
1664     if (command.timeout > 0_s)
1665         m_currentInvocation->setCustomTimeout(command.timeout);
1666
1667     m_currentInvocation->setDumpJSConsoleLogInStdErr(command.dumpJSConsoleLogInStdErr || options.dumpJSConsoleLogInStdErr);
1668
1669     platformWillRunTest(*m_currentInvocation);
1670
1671     m_currentInvocation->invoke();
1672     m_currentInvocation = nullptr;
1673
1674     return true;
1675 }
1676
1677 bool TestController::waitForCompletion(const WTF::Function<void ()>& function, WTF::Seconds timeout)
1678 {
1679     m_doneResetting = false;
1680     function();
1681     runUntil(m_doneResetting, timeout);
1682     return !m_doneResetting;
1683 }
1684
1685 bool TestController::handleControlCommand(const char* command)
1686 {
1687     if (!strncmp("#CHECK FOR WORLD LEAKS", command, 22)) {
1688         if (m_checkForWorldLeaks)
1689             findAndDumpWorldLeaks();
1690         else
1691             WTFLogAlways("WebKitTestRunner asked to check for world leaks, but was not run with --world-leaks");
1692         return true;
1693     }
1694
1695     if (!strncmp("#LIST CHILD PROCESSES", command, 21)) {
1696         findAndDumpWebKitProcessIdentifiers();
1697         return true;
1698     }
1699
1700     return false;
1701 }
1702
1703 void TestController::runTestingServerLoop()
1704 {
1705     char filenameBuffer[2048];
1706     while (fgets(filenameBuffer, sizeof(filenameBuffer), stdin)) {
1707         char* newLineCharacter = strchr(filenameBuffer, '\n');
1708         if (newLineCharacter)
1709             *newLineCharacter = '\0';
1710
1711         if (strlen(filenameBuffer) == 0)
1712             continue;
1713
1714         if (handleControlCommand(filenameBuffer))
1715             continue;
1716
1717         if (!runTest(filenameBuffer))
1718             break;
1719     }
1720 }
1721
1722 void TestController::run()
1723 {
1724     if (m_usingServerMode)
1725         runTestingServerLoop();
1726     else {
1727         for (size_t i = 0; i < m_paths.size(); ++i) {
1728             if (!runTest(m_paths[i].c_str()))
1729                 break;
1730         }
1731         if (m_checkForWorldLeaks)
1732             findAndDumpWorldLeaks();
1733     }
1734 }
1735
1736 void TestController::runUntil(bool& done, WTF::Seconds timeout)
1737 {
1738     if (m_forceNoTimeout)
1739         timeout = noTimeout;
1740
1741     platformRunUntil(done, timeout);
1742 }
1743
1744 // WKContextInjectedBundleClient
1745
1746 void TestController::didReceiveMessageFromInjectedBundle(WKContextRef context, WKStringRef messageName, WKTypeRef messageBody, const void* clientInfo)
1747 {
1748     static_cast<TestController*>(const_cast<void*>(clientInfo))->didReceiveMessageFromInjectedBundle(messageName, messageBody);
1749 }
1750
1751 void TestController::didReceiveSynchronousMessageFromInjectedBundleWithListener(WKContextRef context, WKStringRef messageName, WKTypeRef messageBody, WKMessageListenerRef listener, const void* clientInfo)
1752 {
1753     static_cast<TestController*>(const_cast<void*>(clientInfo))->didReceiveSynchronousMessageFromInjectedBundle(messageName, messageBody, listener);
1754 }
1755
1756 WKTypeRef TestController::getInjectedBundleInitializationUserData(WKContextRef, const void* clientInfo)
1757 {
1758     return static_cast<TestController*>(const_cast<void*>(clientInfo))->getInjectedBundleInitializationUserData().leakRef();
1759 }
1760
1761 // WKPageInjectedBundleClient
1762
1763 void TestController::didReceivePageMessageFromInjectedBundle(WKPageRef page, WKStringRef messageName, WKTypeRef messageBody, const void* clientInfo)
1764 {
1765     static_cast<TestController*>(const_cast<void*>(clientInfo))->didReceiveMessageFromInjectedBundle(messageName, messageBody);
1766 }
1767
1768 void TestController::didReceiveSynchronousPageMessageFromInjectedBundleWithListener(WKPageRef page, WKStringRef messageName, WKTypeRef messageBody, WKMessageListenerRef listener, const void* clientInfo)
1769 {
1770     static_cast<TestController*>(const_cast<void*>(clientInfo))->didReceiveSynchronousMessageFromInjectedBundle(messageName, messageBody, listener);
1771 }
1772
1773 void TestController::networkProcessDidCrash(WKContextRef context, const void *clientInfo)
1774 {
1775     static_cast<TestController*>(const_cast<void*>(clientInfo))->networkProcessDidCrash();
1776 }
1777
1778 void TestController::didReceiveKeyDownMessageFromInjectedBundle(WKDictionaryRef messageBodyDictionary, bool synchronous)
1779 {
1780     WKRetainPtr<WKStringRef> keyKey = adoptWK(WKStringCreateWithUTF8CString("Key"));
1781     WKStringRef key = static_cast<WKStringRef>(WKDictionaryGetItemForKey(messageBodyDictionary, keyKey.get()));
1782
1783     WKRetainPtr<WKStringRef> modifiersKey = adoptWK(WKStringCreateWithUTF8CString("Modifiers"));
1784     WKEventModifiers modifiers = static_cast<WKEventModifiers>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, modifiersKey.get()))));
1785
1786     WKRetainPtr<WKStringRef> locationKey = adoptWK(WKStringCreateWithUTF8CString("Location"));
1787     unsigned location = static_cast<unsigned>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, locationKey.get()))));
1788
1789     m_eventSenderProxy->keyDown(key, modifiers, location);
1790 }
1791
1792 void TestController::didReceiveLiveDocumentsList(WKArrayRef liveDocumentList)
1793 {
1794     auto numDocuments = WKArrayGetSize(liveDocumentList);
1795
1796     HashMap<uint64_t, String> documentInfo;
1797     for (size_t i = 0; i < numDocuments; ++i) {
1798         WKTypeRef item = WKArrayGetItemAtIndex(liveDocumentList, i);
1799         if (item && WKGetTypeID(item) == WKDictionaryGetTypeID()) {
1800             WKDictionaryRef liveDocumentItem = static_cast<WKDictionaryRef>(item);
1801
1802             WKRetainPtr<WKStringRef> idKey = adoptWK(WKStringCreateWithUTF8CString("id"));
1803             WKUInt64Ref documentID = static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(liveDocumentItem, idKey.get()));
1804
1805             WKRetainPtr<WKStringRef> urlKey = adoptWK(WKStringCreateWithUTF8CString("url"));
1806             WKStringRef documentURL = static_cast<WKStringRef>(WKDictionaryGetItemForKey(liveDocumentItem, urlKey.get()));
1807
1808             documentInfo.add(WKUInt64GetValue(documentID), toWTFString(documentURL));
1809         }
1810     }
1811
1812     if (!documentInfo.size()) {
1813         m_abandonedDocumentInfo.clear();
1814         return;
1815     }
1816
1817     // Remove any documents which are no longer live.
1818     m_abandonedDocumentInfo.removeIf([&](auto& keyAndValue) {
1819         return !documentInfo.contains(keyAndValue.key);
1820     });
1821     
1822     // Add newly abandoned documents.
1823     String currentTestURL = m_currentInvocation ? toWTFString(adoptWK(WKURLCopyString(m_currentInvocation->url()))) : "no test";
1824     for (const auto& it : documentInfo)
1825         m_abandonedDocumentInfo.add(it.key, AbandonedDocumentInfo(currentTestURL, it.value));
1826 }
1827
1828 void TestController::didReceiveMessageFromInjectedBundle(WKStringRef messageName, WKTypeRef messageBody)
1829 {
1830     if (WKStringIsEqualToUTF8CString(messageName, "LiveDocuments")) {
1831         ASSERT(WKGetTypeID(messageBody) == WKArrayGetTypeID());
1832         didReceiveLiveDocumentsList(static_cast<WKArrayRef>(messageBody));
1833         AsyncTask::currentTask()->taskComplete();
1834         return;
1835     }
1836
1837     if (WKStringIsEqualToUTF8CString(messageName, "EventSender")) {
1838         if (m_state != RunningTest)
1839             return;
1840
1841         ASSERT(WKGetTypeID(messageBody) == WKDictionaryGetTypeID());
1842         WKDictionaryRef messageBodyDictionary = static_cast<WKDictionaryRef>(messageBody);
1843
1844         WKRetainPtr<WKStringRef> subMessageKey = adoptWK(WKStringCreateWithUTF8CString("SubMessage"));
1845         WKStringRef subMessageName = static_cast<WKStringRef>(WKDictionaryGetItemForKey(messageBodyDictionary, subMessageKey.get()));
1846
1847         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseDown") || WKStringIsEqualToUTF8CString(subMessageName, "MouseUp")) {
1848             WKRetainPtr<WKStringRef> buttonKey = adoptWK(WKStringCreateWithUTF8CString("Button"));
1849             unsigned button = static_cast<unsigned>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, buttonKey.get()))));
1850
1851             WKRetainPtr<WKStringRef> modifiersKey = adoptWK(WKStringCreateWithUTF8CString("Modifiers"));
1852             WKEventModifiers modifiers = static_cast<WKEventModifiers>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, modifiersKey.get()))));
1853
1854             // Forward to WebProcess
1855             if (WKStringIsEqualToUTF8CString(subMessageName, "MouseDown"))
1856                 m_eventSenderProxy->mouseDown(button, modifiers);
1857             else
1858                 m_eventSenderProxy->mouseUp(button, modifiers);
1859
1860             return;
1861         }
1862
1863         if (WKStringIsEqualToUTF8CString(subMessageName, "KeyDown")) {
1864             didReceiveKeyDownMessageFromInjectedBundle(messageBodyDictionary, false);
1865             return;
1866         }
1867
1868         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseScrollBy")) {
1869             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
1870             double x = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get())));
1871
1872             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
1873             double y = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get())));
1874
1875             // Forward to WebProcess
1876             m_eventSenderProxy->mouseScrollBy(x, y);
1877             return;
1878         }
1879
1880         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseScrollByWithWheelAndMomentumPhases")) {
1881             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
1882             double x = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get())));
1883             
1884             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
1885             double y = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get())));
1886             
1887             WKRetainPtr<WKStringRef> phaseKey = adoptWK(WKStringCreateWithUTF8CString("Phase"));
1888             int phase = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, phaseKey.get()))));
1889             WKRetainPtr<WKStringRef> momentumKey = adoptWK(WKStringCreateWithUTF8CString("Momentum"));
1890             int momentum = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, momentumKey.get()))));
1891             
1892             // Forward to WebProcess
1893             m_eventSenderProxy->mouseScrollByWithWheelAndMomentumPhases(x, y, phase, momentum);
1894
1895             return;
1896         }
1897
1898         ASSERT_NOT_REACHED();
1899     }
1900
1901     if (!m_currentInvocation)
1902         return;
1903
1904     m_currentInvocation->didReceiveMessageFromInjectedBundle(messageName, messageBody);
1905 }
1906
1907 void TestController::didReceiveSynchronousMessageFromInjectedBundle(WKStringRef messageName, WKTypeRef messageBody, WKMessageListenerRef listener)
1908 {
1909     auto completionHandler = [listener = retainWK(listener)] (WKTypeRef reply) {
1910         WKMessageListenerSendReply(listener.get(), reply);
1911     };
1912
1913     if (WKStringIsEqualToUTF8CString(messageName, "EventSender")) {
1914         if (m_state != RunningTest)
1915             return completionHandler(nullptr);
1916
1917         ASSERT(WKGetTypeID(messageBody) == WKDictionaryGetTypeID());
1918         WKDictionaryRef messageBodyDictionary = static_cast<WKDictionaryRef>(messageBody);
1919
1920         WKRetainPtr<WKStringRef> subMessageKey = adoptWK(WKStringCreateWithUTF8CString("SubMessage"));
1921         WKStringRef subMessageName = static_cast<WKStringRef>(WKDictionaryGetItemForKey(messageBodyDictionary, subMessageKey.get()));
1922
1923         if (WKStringIsEqualToUTF8CString(subMessageName, "KeyDown")) {
1924             didReceiveKeyDownMessageFromInjectedBundle(messageBodyDictionary, true);
1925
1926             return completionHandler(nullptr);
1927         }
1928
1929         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseDown") || WKStringIsEqualToUTF8CString(subMessageName, "MouseUp")) {
1930             WKRetainPtr<WKStringRef> buttonKey = adoptWK(WKStringCreateWithUTF8CString("Button"));
1931             unsigned button = static_cast<unsigned>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, buttonKey.get()))));
1932
1933             WKRetainPtr<WKStringRef> modifiersKey = adoptWK(WKStringCreateWithUTF8CString("Modifiers"));
1934             WKEventModifiers modifiers = static_cast<WKEventModifiers>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, modifiersKey.get()))));
1935
1936             // Forward to WebProcess
1937             if (WKStringIsEqualToUTF8CString(subMessageName, "MouseDown"))
1938                 m_eventSenderProxy->mouseDown(button, modifiers);
1939             else
1940                 m_eventSenderProxy->mouseUp(button, modifiers);
1941             return completionHandler(nullptr);
1942         }
1943
1944         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseMoveTo")) {
1945             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
1946             double x = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get())));
1947
1948             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
1949             double y = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get())));
1950
1951             // Forward to WebProcess
1952             m_eventSenderProxy->mouseMoveTo(x, y);
1953             return completionHandler(nullptr);
1954         }
1955
1956 #if PLATFORM(MAC)
1957         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseForceClick")) {
1958             m_eventSenderProxy->mouseForceClick();
1959             return completionHandler(nullptr);
1960         }
1961
1962         if (WKStringIsEqualToUTF8CString(subMessageName, "StartAndCancelMouseForceClick")) {
1963             m_eventSenderProxy->startAndCancelMouseForceClick();
1964             return completionHandler(nullptr);
1965         }
1966
1967         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseForceDown")) {
1968             m_eventSenderProxy->mouseForceDown();
1969             return completionHandler(nullptr);
1970         }
1971
1972         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseForceUp")) {
1973             m_eventSenderProxy->mouseForceUp();
1974             return completionHandler(nullptr);
1975         }
1976
1977         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseForceChanged")) {
1978             WKRetainPtr<WKStringRef> forceKey = adoptWK(WKStringCreateWithUTF8CString("Force"));
1979             double force = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, forceKey.get())));
1980
1981             m_eventSenderProxy->mouseForceChanged(force);
1982             return completionHandler(nullptr);
1983         }
1984 #endif // PLATFORM(MAC)
1985
1986         if (WKStringIsEqualToUTF8CString(subMessageName, "ContinuousMouseScrollBy")) {
1987             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
1988             double x = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get())));
1989
1990             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
1991             double y = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get())));
1992
1993             WKRetainPtr<WKStringRef> pagedKey = adoptWK(WKStringCreateWithUTF8CString("Paged"));
1994             bool paged = static_cast<bool>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, pagedKey.get()))));
1995
1996             // Forward to WebProcess
1997             m_eventSenderProxy->continuousMouseScrollBy(x, y, paged);
1998             return completionHandler(nullptr);
1999         }
2000
2001         if (WKStringIsEqualToUTF8CString(subMessageName, "LeapForward")) {
2002             WKRetainPtr<WKStringRef> timeKey = adoptWK(WKStringCreateWithUTF8CString("TimeInMilliseconds"));
2003             unsigned time = static_cast<unsigned>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, timeKey.get()))));
2004
2005             m_eventSenderProxy->leapForward(time);
2006             return completionHandler(nullptr);
2007         }
2008
2009 #if ENABLE(TOUCH_EVENTS)
2010         if (WKStringIsEqualToUTF8CString(subMessageName, "AddTouchPoint")) {
2011             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
2012             int x = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get()))));
2013
2014             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
2015             int y = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get()))));
2016
2017             m_eventSenderProxy->addTouchPoint(x, y);
2018             return completionHandler(nullptr);
2019         }
2020
2021         if (WKStringIsEqualToUTF8CString(subMessageName, "UpdateTouchPoint")) {
2022             WKRetainPtr<WKStringRef> indexKey = adoptWK(WKStringCreateWithUTF8CString("Index"));
2023             int index = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, indexKey.get()))));
2024
2025             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
2026             int x = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get()))));
2027
2028             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
2029             int y = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get()))));
2030
2031             m_eventSenderProxy->updateTouchPoint(index, x, y);
2032             return completionHandler(nullptr);
2033         }
2034
2035         if (WKStringIsEqualToUTF8CString(subMessageName, "SetTouchModifier")) {
2036             WKRetainPtr<WKStringRef> modifierKey = adoptWK(WKStringCreateWithUTF8CString("Modifier"));
2037             WKEventModifiers modifier = static_cast<WKEventModifiers>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, modifierKey.get()))));
2038
2039             WKRetainPtr<WKStringRef> enableKey = adoptWK(WKStringCreateWithUTF8CString("Enable"));
2040             bool enable = static_cast<bool>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, enableKey.get()))));
2041
2042             m_eventSenderProxy->setTouchModifier(modifier, enable);
2043             return completionHandler(nullptr);
2044         }
2045
2046         if (WKStringIsEqualToUTF8CString(subMessageName, "SetTouchPointRadius")) {
2047             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("RadiusX"));
2048             int x = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get()))));
2049
2050             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("RadiusY"));
2051             int y = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get()))));
2052
2053             m_eventSenderProxy->setTouchPointRadius(x, y);
2054             return completionHandler(nullptr);
2055         }
2056
2057         if (WKStringIsEqualToUTF8CString(subMessageName, "TouchStart")) {
2058             m_eventSenderProxy->touchStart();
2059             return completionHandler(nullptr);
2060         }
2061
2062         if (WKStringIsEqualToUTF8CString(subMessageName, "TouchMove")) {
2063             m_eventSenderProxy->touchMove();
2064             return completionHandler(nullptr);
2065         }
2066
2067         if (WKStringIsEqualToUTF8CString(subMessageName, "TouchEnd")) {
2068             m_eventSenderProxy->touchEnd();
2069             return completionHandler(nullptr);
2070         }
2071
2072         if (WKStringIsEqualToUTF8CString(subMessageName, "TouchCancel")) {
2073             m_eventSenderProxy->touchCancel();
2074             return completionHandler(nullptr);
2075         }
2076
2077         if (WKStringIsEqualToUTF8CString(subMessageName, "ClearTouchPoints")) {
2078             m_eventSenderProxy->clearTouchPoints();
2079             return completionHandler(nullptr);
2080         }
2081
2082         if (WKStringIsEqualToUTF8CString(subMessageName, "ReleaseTouchPoint")) {
2083             WKRetainPtr<WKStringRef> indexKey = adoptWK(WKStringCreateWithUTF8CString("Index"));
2084             int index = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, indexKey.get()))));
2085             m_eventSenderProxy->releaseTouchPoint(index);
2086             return completionHandler(nullptr);
2087         }
2088
2089         if (WKStringIsEqualToUTF8CString(subMessageName, "CancelTouchPoint")) {
2090             WKRetainPtr<WKStringRef> indexKey = adoptWK(WKStringCreateWithUTF8CString("Index"));
2091             int index = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, indexKey.get()))));
2092             m_eventSenderProxy->cancelTouchPoint(index);
2093             return completionHandler(nullptr);
2094         }
2095 #endif
2096         ASSERT_NOT_REACHED();
2097     }
2098
2099     auto setHTTPCookieAcceptPolicy = [&] (WKHTTPCookieAcceptPolicy policy, CompletionHandler<void(WKTypeRef)>&& completionHandler) {
2100         auto context = new CompletionHandler<void(WKTypeRef)>(WTFMove(completionHandler));
2101         WKHTTPCookieStoreSetHTTPCookieAcceptPolicy(WKWebsiteDataStoreGetHTTPCookieStore(WKContextGetWebsiteDataStore(m_context.get())), policy, context, [] (void* context) {
2102             auto completionHandlerPointer = static_cast<CompletionHandler<void(WKTypeRef)>*>(context);
2103             (*completionHandlerPointer)(nullptr);
2104             delete completionHandlerPointer;
2105         });
2106     };
2107
2108     if (WKStringIsEqualToUTF8CString(messageName, "SetAlwaysAcceptCookies")) {
2109         WKBooleanRef accept = static_cast<WKBooleanRef>(messageBody);
2110         WKHTTPCookieAcceptPolicy policy = WKBooleanGetValue(accept) ? kWKHTTPCookieAcceptPolicyAlways : kWKHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain;
2111         return setHTTPCookieAcceptPolicy(policy, WTFMove(completionHandler));
2112     }
2113
2114     if (WKStringIsEqualToUTF8CString(messageName, "SetOnlyAcceptFirstPartyCookies")) {
2115         WKBooleanRef accept = static_cast<WKBooleanRef>(messageBody);
2116         WKHTTPCookieAcceptPolicy policy = WKBooleanGetValue(accept) ? kWKHTTPCookieAcceptPolicyExclusivelyFromMainDocumentDomain : kWKHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain;
2117         return setHTTPCookieAcceptPolicy(policy, WTFMove(completionHandler));
2118     }
2119
2120     completionHandler(m_currentInvocation->didReceiveSynchronousMessageFromInjectedBundle(messageName, messageBody).get());
2121 }
2122
2123 WKRetainPtr<WKTypeRef> TestController::getInjectedBundleInitializationUserData()
2124 {
2125     return nullptr;
2126 }
2127
2128 // WKContextClient
2129
2130 void TestController::networkProcessDidCrash()
2131 {
2132     pid_t pid = WKContextGetNetworkProcessIdentifier(m_context.get());
2133     fprintf(stderr, "#CRASHED - %s (pid %ld)\n", networkProcessName(), static_cast<long>(pid));
2134     exit(1);
2135 }
2136
2137 // WKPageNavigationClient
2138
2139 void TestController::didCommitNavigation(WKPageRef page, WKNavigationRef navigation, WKTypeRef, const void* clientInfo)
2140 {
2141     static_cast<TestController*>(const_cast<void*>(clientInfo))->didCommitNavigation(page, navigation);
2142 }
2143
2144 void TestController::didFinishNavigation(WKPageRef page, WKNavigationRef navigation, WKTypeRef, const void* clientInfo)
2145 {
2146     static_cast<TestController*>(const_cast<void*>(clientInfo))->didFinishNavigation(page, navigation);
2147 }
2148
2149 void TestController::didReceiveServerRedirectForProvisionalNavigation(WKPageRef page, WKNavigationRef navigation, WKTypeRef userData, const void* clientInfo)
2150 {
2151     static_cast<TestController*>(const_cast<void*>(clientInfo))->didReceiveServerRedirectForProvisionalNavigation(page, navigation, userData);
2152 }
2153
2154 bool TestController::canAuthenticateAgainstProtectionSpace(WKPageRef page, WKProtectionSpaceRef protectionSpace, const void* clientInfo)
2155 {
2156     return static_cast<TestController*>(const_cast<void*>(clientInfo))->canAuthenticateAgainstProtectionSpace(page, protectionSpace);
2157 }
2158
2159 void TestController::didReceiveAuthenticationChallenge(WKPageRef page, WKAuthenticationChallengeRef authenticationChallenge, const void *clientInfo)
2160 {
2161     static_cast<TestController*>(const_cast<void*>(clientInfo))->didReceiveAuthenticationChallenge(page, /*frame,*/ authenticationChallenge);
2162 }
2163
2164 void TestController::processDidCrash(WKPageRef page, const void* clientInfo)
2165 {
2166     static_cast<TestController*>(const_cast<void*>(clientInfo))->processDidCrash();
2167 }
2168
2169 void TestController::didBeginNavigationGesture(WKPageRef page, const void *clientInfo)
2170 {
2171     static_cast<TestController*>(const_cast<void*>(clientInfo))->didBeginNavigationGesture(page);
2172 }
2173
2174 void TestController::willEndNavigationGesture(WKPageRef page, WKBackForwardListItemRef backForwardListItem, const void *clientInfo)
2175 {
2176     static_cast<TestController*>(const_cast<void*>(clientInfo))->willEndNavigationGesture(page, backForwardListItem);
2177 }
2178
2179 void TestController::didEndNavigationGesture(WKPageRef page, WKBackForwardListItemRef backForwardListItem, const void *clientInfo)
2180 {
2181     static_cast<TestController*>(const_cast<void*>(clientInfo))->didEndNavigationGesture(page, backForwardListItem);
2182 }
2183
2184 void TestController::didRemoveNavigationGestureSnapshot(WKPageRef page, const void *clientInfo)
2185 {
2186     static_cast<TestController*>(const_cast<void*>(clientInfo))->didRemoveNavigationGestureSnapshot(page);
2187 }
2188
2189 WKPluginLoadPolicy TestController::decidePolicyForPluginLoad(WKPageRef page, WKPluginLoadPolicy currentPluginLoadPolicy, WKDictionaryRef pluginInformation, WKStringRef* unavailabilityDescription, const void* clientInfo)
2190 {
2191     return static_cast<TestController*>(const_cast<void*>(clientInfo))->decidePolicyForPluginLoad(page, currentPluginLoadPolicy, pluginInformation, unavailabilityDescription);
2192 }
2193
2194 WKPluginLoadPolicy TestController::decidePolicyForPluginLoad(WKPageRef, WKPluginLoadPolicy currentPluginLoadPolicy, WKDictionaryRef pluginInformation, WKStringRef* unavailabilityDescription)
2195 {
2196     if (m_shouldBlockAllPlugins)
2197         return kWKPluginLoadPolicyBlocked;
2198
2199 #if PLATFORM(MAC)
2200     WKStringRef bundleIdentifier = (WKStringRef)WKDictionaryGetItemForKey(pluginInformation, WKPluginInformationBundleIdentifierKey());
2201     if (!bundleIdentifier)
2202         return currentPluginLoadPolicy;
2203
2204     if (WKStringIsEqualToUTF8CString(bundleIdentifier, "com.apple.QuickTime Plugin.plugin"))
2205         return currentPluginLoadPolicy;
2206
2207     if (WKStringIsEqualToUTF8CString(bundleIdentifier, "com.apple.testnetscapeplugin"))
2208         return currentPluginLoadPolicy;
2209
2210     RELEASE_ASSERT_NOT_REACHED(); // Please don't use any other plug-ins in tests, as they will not be installed on all machines.
2211 #else
2212     return currentPluginLoadPolicy;
2213 #endif
2214 }
2215
2216 void TestController::setBlockAllPlugins(bool shouldBlock)
2217 {
2218     m_shouldBlockAllPlugins = shouldBlock;
2219
2220 #if PLATFORM(MAC)
2221     auto policy = shouldBlock ? kWKPluginLoadClientPolicyBlock : kWKPluginLoadClientPolicyAllow;
2222
2223     WKRetainPtr<WKStringRef> nameNetscape = adoptWK(WKStringCreateWithUTF8CString("com.apple.testnetscapeplugin"));
2224     WKRetainPtr<WKStringRef> nameFlash = adoptWK(WKStringCreateWithUTF8CString("com.macromedia.Flash Player.plugin"));
2225     WKRetainPtr<WKStringRef> emptyString = adoptWK(WKStringCreateWithUTF8CString(""));
2226     WKContextSetPluginLoadClientPolicy(m_context.get(), policy, emptyString.get(), nameNetscape.get(), emptyString.get());
2227     WKContextSetPluginLoadClientPolicy(m_context.get(), policy, emptyString.get(), nameFlash.get(), emptyString.get());
2228 #endif
2229 }
2230
2231 void TestController::setPluginSupportedMode(const String& mode)
2232 {
2233     if (m_unsupportedPluginMode == mode)
2234         return;
2235
2236     m_unsupportedPluginMode = mode;
2237     if (m_unsupportedPluginMode.isEmpty()) {
2238         WKContextClearSupportedPlugins(m_context.get());
2239         return;
2240     }
2241
2242     WKRetainPtr<WKMutableArrayRef> emptyArray = adoptWK(WKMutableArrayCreate());
2243     WKRetainPtr<WKStringRef> allOrigins = adoptWK(WKStringCreateWithUTF8CString(""));
2244     WKRetainPtr<WKStringRef> specificOrigin = adoptWK(WKStringCreateWithUTF8CString("localhost"));
2245
2246     WKRetainPtr<WKStringRef> pdfName = adoptWK(WKStringCreateWithUTF8CString("My personal PDF"));
2247     WKContextAddSupportedPlugin(m_context.get(), allOrigins.get(), pdfName.get(), emptyArray.get(), emptyArray.get());
2248
2249     WKRetainPtr<WKStringRef> nameNetscape = adoptWK(WKStringCreateWithUTF8CString("com.apple.testnetscapeplugin"));
2250     WKRetainPtr<WKStringRef> mimeTypeNetscape = adoptWK(WKStringCreateWithUTF8CString("application/x-webkit-test-netscape"));
2251     WKRetainPtr<WKMutableArrayRef> mimeTypesNetscape = adoptWK(WKMutableArrayCreate());
2252     WKArrayAppendItem(mimeTypesNetscape.get(), mimeTypeNetscape.get());
2253
2254     WKRetainPtr<WKStringRef> namePdf = adoptWK(WKStringCreateWithUTF8CString("WebKit built-in PDF"));
2255
2256     if (m_unsupportedPluginMode == "allOrigins") {
2257         WKContextAddSupportedPlugin(m_context.get(), allOrigins.get(), nameNetscape.get(), mimeTypesNetscape.get(), emptyArray.get());
2258         WKContextAddSupportedPlugin(m_context.get(), allOrigins.get(), namePdf.get(), emptyArray.get(), emptyArray.get());
2259         return;
2260     }
2261
2262     if (m_unsupportedPluginMode == "specificOrigin") {
2263         WKContextAddSupportedPlugin(m_context.get(), specificOrigin.get(), nameNetscape.get(), mimeTypesNetscape.get(), emptyArray.get());
2264         WKContextAddSupportedPlugin(m_context.get(), specificOrigin.get(), namePdf.get(), emptyArray.get(), emptyArray.get());
2265         return;
2266     }
2267 }
2268
2269 void TestController::didCommitNavigation(WKPageRef page, WKNavigationRef navigation)
2270 {
2271     mainWebView()->focus();
2272 }
2273
2274 void TestController::didReceiveServerRedirectForProvisionalNavigation(WKPageRef page, WKNavigationRef navigation, WKTypeRef userData)
2275 {
2276     m_didReceiveServerRedirectForProvisionalNavigation = true;
2277     return;
2278 }
2279
2280 static const char* toString(WKProtectionSpaceAuthenticationScheme scheme)
2281 {
2282     switch (scheme) {
2283     case kWKProtectionSpaceAuthenticationSchemeDefault:
2284         return "ProtectionSpaceAuthenticationSchemeDefault";
2285     case kWKProtectionSpaceAuthenticationSchemeHTTPBasic:
2286         return "ProtectionSpaceAuthenticationSchemeHTTPBasic";
2287     case kWKProtectionSpaceAuthenticationSchemeHTMLForm:
2288         return "ProtectionSpaceAuthenticationSchemeHTMLForm";
2289     case kWKProtectionSpaceAuthenticationSchemeNTLM:
2290         return "ProtectionSpaceAuthenticationSchemeNTLM";
2291     case kWKProtectionSpaceAuthenticationSchemeNegotiate:
2292         return "ProtectionSpaceAuthenticationSchemeNegotiate";
2293     case kWKProtectionSpaceAuthenticationSchemeClientCertificateRequested:
2294         return "ProtectionSpaceAuthenticationSchemeClientCertificateRequested";
2295     case kWKProtectionSpaceAuthenticationSchemeServerTrustEvaluationRequested:
2296         return "ProtectionSpaceAuthenticationSchemeServerTrustEvaluationRequested";
2297     case kWKProtectionSpaceAuthenticationSchemeOAuth:
2298         return "ProtectionSpaceAuthenticationSchemeOAuth";
2299     case kWKProtectionSpaceAuthenticationSchemeUnknown:
2300         return "ProtectionSpaceAuthenticationSchemeUnknown";
2301     }
2302     ASSERT_NOT_REACHED();
2303     return "ProtectionSpaceAuthenticationSchemeUnknown";
2304 }
2305
2306 bool TestController::canAuthenticateAgainstProtectionSpace(WKPageRef page, WKProtectionSpaceRef protectionSpace)
2307 {
2308     if (m_shouldLogCanAuthenticateAgainstProtectionSpace)
2309         m_currentInvocation->outputText("canAuthenticateAgainstProtectionSpace\n");
2310     WKProtectionSpaceAuthenticationScheme authenticationScheme = WKProtectionSpaceGetAuthenticationScheme(protectionSpace);
2311     
2312     if (authenticationScheme == kWKProtectionSpaceAuthenticationSchemeServerTrustEvaluationRequested) {
2313         std::string host = toSTD(adoptWK(WKProtectionSpaceCopyHost(protectionSpace)).get());
2314         return host == "localhost" || host == "127.0.0.1" || (m_allowAnyHTTPSCertificateForAllowedHosts && m_allowedHosts.find(host) != m_allowedHosts.end());
2315     }
2316     
2317     return authenticationScheme <= kWKProtectionSpaceAuthenticationSchemeHTTPDigest || authenticationScheme == kWKProtectionSpaceAuthenticationSchemeOAuth;
2318 }
2319
2320 void TestController::didFinishNavigation(WKPageRef page, WKNavigationRef navigation)
2321 {
2322     if (m_state != Resetting)
2323         return;
2324
2325     WKRetainPtr<WKURLRef> wkURL = adoptWK(WKFrameCopyURL(WKPageGetMainFrame(page)));
2326     if (!WKURLIsEqual(wkURL.get(), blankURL()))
2327         return;
2328
2329     m_doneResetting = true;
2330     singleton().notifyDone();
2331 }
2332
2333 void TestController::didReceiveAuthenticationChallenge(WKPageRef page, WKAuthenticationChallengeRef authenticationChallenge)
2334 {
2335     WKProtectionSpaceRef protectionSpace = WKAuthenticationChallengeGetProtectionSpace(authenticationChallenge);
2336     WKAuthenticationDecisionListenerRef decisionListener = WKAuthenticationChallengeGetDecisionListener(authenticationChallenge);
2337     WKProtectionSpaceAuthenticationScheme authenticationScheme = WKProtectionSpaceGetAuthenticationScheme(protectionSpace);
2338
2339     if (authenticationScheme == kWKProtectionSpaceAuthenticationSchemeServerTrustEvaluationRequested) {
2340         // Any non-empty credential signals to accept the server trust. Since the cross-platform API
2341         // doesn't expose a way to create a credential from server trust, we use a password credential.
2342
2343         m_serverTrustEvaluationCallbackCallsCount++;
2344
2345         if (m_allowsAnySSLCertificate) {
2346             WKRetainPtr<WKCredentialRef> credential = adoptWK(WKCredentialCreate(toWK("accept server trust").get(), toWK("").get(), kWKCredentialPersistenceNone));
2347             WKAuthenticationDecisionListenerUseCredential(decisionListener, credential.get());
2348             return;
2349         }
2350         WKAuthenticationDecisionListenerRejectProtectionSpaceAndContinue(decisionListener);
2351         return;
2352     }
2353
2354     if (m_rejectsProtectionSpaceAndContinueForAuthenticationChallenges) {
2355         m_currentInvocation->outputText("Simulating reject protection space and continue for authentication challenge\n");
2356         WKAuthenticationDecisionListenerRejectProtectionSpaceAndContinue(decisionListener);
2357         return;
2358     }
2359
2360     std::string host = toSTD(adoptWK(WKProtectionSpaceCopyHost(protectionSpace)).get());
2361     int port = WKProtectionSpaceGetPort(protectionSpace);
2362     String message = makeString(host.c_str(), ':', port, " - didReceiveAuthenticationChallenge - ", toString(authenticationScheme), " - ");
2363     if (!m_handlesAuthenticationChallenges)
2364         message.append("Simulating cancelled authentication sheet\n");
2365     else
2366         message.append("Responding with " + m_authenticationUsername + ":" + m_authenticationPassword + "\n");
2367     m_currentInvocation->outputText(message);
2368
2369     if (!m_handlesAuthenticationChallenges) {
2370         WKAuthenticationDecisionListenerUseCredential(decisionListener, 0);
2371         return;
2372     }
2373     WKRetainPtr<WKStringRef> username = adoptWK(WKStringCreateWithUTF8CString(m_authenticationUsername.utf8().data()));
2374     WKRetainPtr<WKStringRef> password = adoptWK(WKStringCreateWithUTF8CString(m_authenticationPassword.utf8().data()));
2375     WKRetainPtr<WKCredentialRef> credential = adoptWK(WKCredentialCreate(username.get(), password.get(), kWKCredentialPersistenceForSession));
2376     WKAuthenticationDecisionListenerUseCredential(decisionListener, credential.get());
2377 }
2378
2379     
2380 // WKContextDownloadClient
2381
2382 void TestController::downloadDidStart(WKContextRef context, WKDownloadRef download, const void* clientInfo)
2383 {
2384     static_cast<TestController*>(const_cast<void*>(clientInfo))->downloadDidStart(context, download);
2385 }
2386     
2387 WKStringRef TestController::decideDestinationWithSuggestedFilename(WKContextRef context, WKDownloadRef download, WKStringRef filename, bool* allowOverwrite, const void* clientInfo)
2388 {
2389     return static_cast<TestController*>(const_cast<void*>(clientInfo))->decideDestinationWithSuggestedFilename(context, download, filename, allowOverwrite);
2390 }
2391
2392 void TestController::downloadDidFinish(WKContextRef context, WKDownloadRef download, const void* clientInfo)
2393 {
2394     static_cast<TestController*>(const_cast<void*>(clientInfo))->downloadDidFinish(context, download);
2395 }
2396
2397 void TestController::downloadDidFail(WKContextRef context, WKDownloadRef download, WKErrorRef error, const void* clientInfo)
2398 {
2399     static_cast<TestController*>(const_cast<void*>(clientInfo))->downloadDidFail(context, download, error);
2400 }
2401
2402 void TestController::downloadDidCancel(WKContextRef context, WKDownloadRef download, const void* clientInfo)
2403 {
2404     static_cast<TestController*>(const_cast<void*>(clientInfo))->downloadDidCancel(context, download);
2405 }
2406
2407 void TestController::downloadDidReceiveServerRedirectToURL(WKContextRef context, WKDownloadRef download, WKURLRef url, const void* clientInfo)
2408 {
2409     static_cast<TestController*>(const_cast<void*>(clientInfo))->downloadDidReceiveServerRedirectToURL(context, download, url);
2410 }
2411
2412 void TestController::downloadDidStart(WKContextRef context, WKDownloadRef download)
2413 {
2414     if (m_shouldLogDownloadCallbacks)
2415         m_currentInvocation->outputText("Download started.\n");
2416 }
2417
2418 WKStringRef TestController::decideDestinationWithSuggestedFilename(WKContextRef, WKDownloadRef, WKStringRef filename, bool*& allowOverwrite)
2419 {
2420     String suggestedFilename = toWTFString(filename);
2421
2422     if (m_shouldLogDownloadCallbacks) {
2423         StringBuilder builder;
2424         builder.append("Downloading URL with suggested filename \"");
2425         builder.append(suggestedFilename);
2426         builder.append("\"\n");
2427         m_currentInvocation->outputText(builder.toString());
2428     }
2429
2430     const char* dumpRenderTreeTemp = libraryPathForTesting();
2431     if (!dumpRenderTreeTemp)
2432         return nullptr;
2433
2434     *allowOverwrite = true;
2435     String temporaryFolder = String::fromUTF8(dumpRenderTreeTemp);
2436     if (suggestedFilename.isEmpty())
2437         suggestedFilename = "Unknown";
2438
2439     return toWK(temporaryFolder + "/" + suggestedFilename).leakRef();
2440 }
2441
2442 void TestController::downloadDidFinish(WKContextRef, WKDownloadRef)
2443 {
2444     if (m_shouldLogDownloadCallbacks)
2445         m_currentInvocation->outputText("Download completed.\n");
2446     m_currentInvocation->notifyDownloadDone();
2447 }
2448
2449 void TestController::downloadDidReceiveServerRedirectToURL(WKContextRef, WKDownloadRef, WKURLRef url)
2450 {
2451     if (m_shouldLogDownloadCallbacks)
2452         m_currentInvocation->outputText(makeString("Download was redirected to \"", toWTFString(adoptWK(WKURLCopyString(url))), "\".\n"));
2453 }
2454
2455 void TestController::downloadDidFail(WKContextRef, WKDownloadRef, WKErrorRef error)
2456 {
2457     if (m_shouldLogDownloadCallbacks) {
2458         m_currentInvocation->outputText("Download failed.\n"_s);
2459
2460         auto domain = toWTFString(adoptWK(WKErrorCopyDomain(error)));
2461         auto description = toWTFString(adoptWK(WKErrorCopyLocalizedDescription(error)));
2462         int code = WKErrorGetErrorCode(error);
2463
2464         m_currentInvocation->outputText(makeString("Failed: ", domain, ", code=", code, ", description=", description, "\n"));
2465     }
2466     m_currentInvocation->notifyDownloadDone();
2467 }
2468
2469 void TestController::downloadDidCancel(WKContextRef, WKDownloadRef)
2470 {
2471     if (m_shouldLogDownloadCallbacks)
2472         m_currentInvocation->outputText("Download cancelled.\n");
2473     m_currentInvocation->notifyDownloadDone();
2474 }
2475
2476 void TestController::processDidCrash()
2477 {
2478     // This function can be called multiple times when crash logs are being saved on Windows, so
2479     // ensure we only print the crashed message once.
2480     if (!m_didPrintWebProcessCrashedMessage) {
2481         pid_t pid = WKPageGetProcessIdentifier(m_mainWebView->page());
2482         fprintf(stderr, "#CRASHED - %s (pid %ld)\n", webProcessName(), static_cast<long>(pid));
2483         fflush(stderr);
2484         m_didPrintWebProcessCrashedMessage = true;
2485     }
2486
2487     if (m_shouldExitWhenWebProcessCrashes)
2488         exit(1);
2489 }
2490
2491 void TestController::didBeginNavigationGesture(WKPageRef)
2492 {
2493     m_currentInvocation->didBeginSwipe();
2494 }
2495
2496 void TestController::willEndNavigationGesture(WKPageRef, WKBackForwardListItemRef)
2497 {
2498     m_currentInvocation->willEndSwipe();
2499 }
2500
2501 void TestController::didEndNavigationGesture(WKPageRef, WKBackForwardListItemRef)
2502 {
2503     m_currentInvocation->didEndSwipe();
2504 }
2505
2506 void TestController::didRemoveNavigationGestureSnapshot(WKPageRef)
2507 {
2508     m_currentInvocation->didRemoveSwipeSnapshot();
2509 }
2510
2511 void TestController::simulateWebNotificationClick(uint64_t notificationID)
2512 {
2513     m_webNotificationProvider.simulateWebNotificationClick(mainWebView()->page(), notificationID);
2514 }
2515
2516 void TestController::setGeolocationPermission(bool enabled)
2517 {
2518     m_isGeolocationPermissionSet = true;
2519     m_isGeolocationPermissionAllowed = enabled;
2520     decidePolicyForGeolocationPermissionRequestIfPossible();
2521 }
2522
2523 void TestController::setMockGeolocationPosition(double latitude, double longitude, double accuracy, bool providesAltitude, double altitude, bool providesAltitudeAccuracy, double altitudeAccuracy, bool providesHeading, double heading, bool providesSpeed, double speed, bool providesFloorLevel, double floorLevel)
2524 {
2525     m_geolocationProvider->setPosition(latitude, longitude, accuracy, providesAltitude, altitude, providesAltitudeAccuracy, altitudeAccuracy, providesHeading, heading, providesSpeed, speed, providesFloorLevel, floorLevel);
2526 }
2527
2528 void TestController::setMockGeolocationPositionUnavailableError(WKStringRef errorMessage)
2529 {
2530     m_geolocationProvider->setPositionUnavailableError(errorMessage);
2531 }
2532
2533 void TestController::handleGeolocationPermissionRequest(WKGeolocationPermissionRequestRef geolocationPermissionRequest)
2534 {
2535     m_geolocationPermissionRequests.append(geolocationPermissionRequest);
2536     decidePolicyForGeolocationPermissionRequestIfPossible();
2537 }
2538
2539 bool TestController::isGeolocationProviderActive() const
2540 {
2541     return m_geolocationProvider->isActive();
2542 }
2543
2544 static String originUserVisibleName(WKSecurityOriginRef origin)
2545 {
2546     if (!origin)
2547         return emptyString();
2548
2549     auto host = toWTFString(adoptWK(WKSecurityOriginCopyHost(origin)));
2550     auto protocol = toWTFString(adoptWK(WKSecurityOriginCopyProtocol(origin)));
2551
2552     if (host.isEmpty() || protocol.isEmpty())
2553         return emptyString();
2554
2555     if (int port = WKSecurityOriginGetPort(origin))
2556         return makeString(protocol, "://", host, ':', port);
2557
2558     return makeString(protocol, "://", host);
2559 }
2560
2561 static String userMediaOriginHash(WKSecurityOriginRef userMediaDocumentOrigin, WKSecurityOriginRef topLevelDocumentOrigin)
2562 {
2563     String userMediaDocumentOriginString = originUserVisibleName(userMediaDocumentOrigin);
2564     String topLevelDocumentOriginString = originUserVisibleName(topLevelDocumentOrigin);
2565
2566     if (topLevelDocumentOriginString.isEmpty())
2567         return userMediaDocumentOriginString;
2568
2569     return makeString(userMediaDocumentOriginString, '-', topLevelDocumentOriginString);
2570 }
2571
2572 static String userMediaOriginHash(WKStringRef userMediaDocumentOriginString, WKStringRef topLevelDocumentOriginString)
2573 {
2574     auto userMediaDocumentOrigin = adoptWK(WKSecurityOriginCreateFromString(userMediaDocumentOriginString));
2575     if (!WKStringGetLength(topLevelDocumentOriginString))
2576         return userMediaOriginHash(userMediaDocumentOrigin.get(), nullptr);
2577
2578     auto topLevelDocumentOrigin = adoptWK(WKSecurityOriginCreateFromString(topLevelDocumentOriginString));
2579     return userMediaOriginHash(userMediaDocumentOrigin.get(), topLevelDocumentOrigin.get());
2580 }
2581
2582 void TestController::setUserMediaPermission(bool enabled)
2583 {
2584     m_isUserMediaPermissionSet = true;
2585     m_isUserMediaPermissionAllowed = enabled;
2586     decidePolicyForUserMediaPermissionRequestIfPossible();
2587 }
2588
2589 void TestController::resetUserMediaPermission()
2590 {
2591     m_isUserMediaPermissionSet = false;
2592 }
2593
2594 void TestController::setShouldDismissJavaScriptAlertsAsynchronously(bool value)
2595 {
2596     m_shouldDismissJavaScriptAlertsAsynchronously = value;
2597 }
2598
2599 void TestController::handleJavaScriptAlert(WKPageRunJavaScriptAlertResultListenerRef listener)
2600 {
2601     if (!m_shouldDismissJavaScriptAlertsAsynchronously) {
2602         WKPageRunJavaScriptAlertResultListenerCall(listener);
2603         return;
2604     }
2605
2606     WKRetain(listener);
2607     callOnMainThread([listener] {
2608         WKPageRunJavaScriptAlertResultListenerCall(listener);
2609         WKRelease(listener);
2610     });
2611 }
2612
2613 class OriginSettings : public RefCounted<OriginSettings> {
2614 public:
2615     explicit OriginSettings()
2616     {
2617     }
2618
2619     bool persistentPermission() const { return m_persistentPermission; }
2620     void setPersistentPermission(bool permission) { m_persistentPermission = permission; }
2621
2622     String persistentSalt() const { return m_persistentSalt; }
2623     void setPersistentSalt(const String& salt) { m_persistentSalt = salt; }
2624
2625     HashMap<uint64_t, String>& ephemeralSalts() { return m_ephemeralSalts; }
2626
2627     void incrementRequestCount() { ++m_requestCount; }
2628     void resetRequestCount() { m_requestCount = 0; }
2629     unsigned requestCount() const { return m_requestCount; }
2630
2631 private:
2632     HashMap<uint64_t, String> m_ephemeralSalts;
2633     String m_persistentSalt;
2634     unsigned m_requestCount { 0 };
2635     bool m_persistentPermission { false };
2636 };
2637
2638 String TestController::saltForOrigin(WKFrameRef frame, String originHash)
2639 {
2640     auto& settings = settingsForOrigin(originHash);
2641     auto& ephemeralSalts = settings.ephemeralSalts();
2642     auto frameInfo = adoptWK(WKFrameCreateFrameInfo(frame));
2643     auto frameHandle = WKFrameInfoGetFrameHandleRef(frameInfo.get());
2644     uint64_t frameIdentifier = WKFrameHandleGetFrameID(frameHandle);
2645     String frameSalt = ephemeralSalts.get(frameIdentifier);
2646
2647     if (settings.persistentPermission()) {
2648         if (frameSalt.length())
2649             return frameSalt;
2650
2651         if (!settings.persistentSalt().length())
2652             settings.setPersistentSalt(createCanonicalUUIDString());
2653
2654         return settings.persistentSalt();
2655     }
2656
2657     if (!frameSalt.length()) {
2658         frameSalt = createCanonicalUUIDString();
2659         ephemeralSalts.add(frameIdentifier, frameSalt);
2660     }
2661
2662     return frameSalt;
2663 }
2664
2665 void TestController::setUserMediaPersistentPermissionForOrigin(bool permission, WKStringRef userMediaDocumentOriginString, WKStringRef topLevelDocumentOriginString)
2666 {
2667     auto originHash = userMediaOriginHash(userMediaDocumentOriginString, topLevelDocumentOriginString);
2668     auto& settings = settingsForOrigin(originHash);
2669     settings.setPersistentPermission(permission);
2670 }
2671
2672 void TestController::handleCheckOfUserMediaPermissionForOrigin(WKFrameRef frame, WKSecurityOriginRef userMediaDocumentOrigin, WKSecurityOriginRef topLevelDocumentOrigin, const WKUserMediaPermissionCheckRef& checkRequest)
2673 {
2674     auto originHash = userMediaOriginHash(userMediaDocumentOrigin, topLevelDocumentOrigin);
2675     auto salt = saltForOrigin(frame, originHash);
2676     WKRetainPtr<WKStringRef> saltString = adoptWK(WKStringCreateWithUTF8CString(salt.utf8().data()));
2677
2678     WKUserMediaPermissionCheckSetUserMediaAccessInfo(checkRequest, saltString.get(), settingsForOrigin(originHash).persistentPermission());
2679 }
2680
2681 bool TestController::handleDeviceOrientationAndMotionAccessRequest(WKSecurityOriginRef origin)
2682 {
2683     m_currentInvocation->outputText(makeString("Received device orientation & motion access request for security origin \"", originUserVisibleName(origin), "\".\n"));
2684     return m_shouldAllowDeviceOrientationAndMotionAccess;
2685 }
2686
2687 void TestController::handleUserMediaPermissionRequest(WKFrameRef frame, WKSecurityOriginRef userMediaDocumentOrigin, WKSecurityOriginRef topLevelDocumentOrigin, WKUserMediaPermissionRequestRef request)
2688 {
2689     auto originHash = userMediaOriginHash(userMediaDocumentOrigin, topLevelDocumentOrigin);
2690     m_userMediaPermissionRequests.append(std::make_pair(originHash, request));
2691     decidePolicyForUserMediaPermissionRequestIfPossible();
2692 }
2693
2694 OriginSettings& TestController::settingsForOrigin(const String& originHash)
2695 {
2696     RefPtr<OriginSettings> settings = m_cachedUserMediaPermissions.get(originHash);
2697     if (!settings) {
2698         settings = adoptRef(*new OriginSettings());
2699         m_cachedUserMediaPermissions.add(originHash, settings);
2700     }
2701
2702     return *settings;
2703 }
2704
2705 unsigned TestController::userMediaPermissionRequestCountForOrigin(WKStringRef userMediaDocumentOriginString, WKStringRef topLevelDocumentOriginString)
2706 {
2707     auto originHash = userMediaOriginHash(userMediaDocumentOriginString, topLevelDocumentOriginString);
2708     return settingsForOrigin(originHash).requestCount();
2709 }
2710
2711 void TestController::resetUserMediaPermissionRequestCountForOrigin(WKStringRef userMediaDocumentOriginString, WKStringRef topLevelDocumentOriginString)
2712 {
2713     auto originHash = userMediaOriginHash(userMediaDocumentOriginString, topLevelDocumentOriginString);
2714     settingsForOrigin(originHash).resetRequestCount();
2715 }
2716
2717 void TestController::decidePolicyForUserMediaPermissionRequestIfPossible()
2718 {
2719     if (!m_isUserMediaPermissionSet)
2720         return;
2721
2722     for (auto& pair : m_userMediaPermissionRequests) {
2723         auto originHash = pair.first;
2724         auto request = pair.second.get();
2725
2726         auto& settings = settingsForOrigin(originHash);
2727         settings.incrementRequestCount();
2728
2729         if (!m_isUserMediaPermissionAllowed && !settings.persistentPermission()) {
2730             WKUserMediaPermissionRequestDeny(request, kWKPermissionDenied);
2731             continue;
2732         }
2733
2734         WKRetainPtr<WKArrayRef> audioDeviceUIDs = adoptWK(WKUserMediaPermissionRequestAudioDeviceUIDs(request));
2735         WKRetainPtr<WKArrayRef> videoDeviceUIDs = adoptWK(WKUserMediaPermissionRequestVideoDeviceUIDs(request));
2736
2737         if (!WKArrayGetSize(videoDeviceUIDs.get()) && !WKArrayGetSize(audioDeviceUIDs.get())) {
2738             WKUserMediaPermissionRequestDeny(request, kWKNoConstraints);
2739             continue;
2740         }
2741
2742         WKRetainPtr<WKStringRef> videoDeviceUID;
2743         if (WKArrayGetSize(videoDeviceUIDs.get()))
2744             videoDeviceUID = reinterpret_cast<WKStringRef>(WKArrayGetItemAtIndex(videoDeviceUIDs.get(), 0));
2745         else
2746             videoDeviceUID = adoptWK(WKStringCreateWithUTF8CString(""));
2747
2748         WKRetainPtr<WKStringRef> audioDeviceUID;
2749         if (WKArrayGetSize(audioDeviceUIDs.get()))
2750             audioDeviceUID = reinterpret_cast<WKStringRef>(WKArrayGetItemAtIndex(audioDeviceUIDs.get(), 0));
2751         else
2752             audioDeviceUID = adoptWK(WKStringCreateWithUTF8CString(""));
2753
2754         WKUserMediaPermissionRequestAllow(request, audioDeviceUID.get(), videoDeviceUID.get());
2755     }
2756     m_userMediaPermissionRequests.clear();
2757 }
2758
2759 void TestController::setCustomPolicyDelegate(bool enabled, bool permissive)
2760 {
2761     m_policyDelegateEnabled = enabled;
2762     m_policyDelegatePermissive = permissive;
2763 }
2764
2765 void TestController::decidePolicyForGeolocationPermissionRequestIfPossible()
2766 {
2767     if (!m_isGeolocationPermissionSet)
2768         return;
2769
2770     for (size_t i = 0; i < m_geolocationPermissionRequests.size(); ++i) {
2771         WKGeolocationPermissionRequestRef permissionRequest = m_geolocationPermissionRequests[i].get();
2772         if (m_isGeolocationPermissionAllowed)
2773             WKGeolocationPermissionRequestAllow(permissionRequest);
2774         else
2775             WKGeolocationPermissionRequestDeny(permissionRequest);
2776     }
2777     m_geolocationPermissionRequests.clear();
2778 }
2779
2780 void TestController::decidePolicyForNotificationPermissionRequest(WKPageRef page, WKSecurityOriginRef origin, WKNotificationPermissionRequestRef request, const void*)
2781 {
2782     TestController::singleton().decidePolicyForNotificationPermissionRequest(page, origin, request);
2783 }
2784
2785 void TestController::decidePolicyForNotificationPermissionRequest(WKPageRef, WKSecurityOriginRef, WKNotificationPermissionRequestRef request)
2786 {
2787     WKNotificationPermissionRequestAllow(request);
2788 }
2789
2790 void TestController::unavailablePluginButtonClicked(WKPageRef, WKPluginUnavailabilityReason, WKDictionaryRef, const void*)
2791 {
2792     printf("MISSING PLUGIN BUTTON PRESSED\n");
2793 }
2794
2795 void TestController::decidePolicyForNavigationAction(WKPageRef, WKNavigationActionRef navigationAction, WKFramePolicyListenerRef listener, WKTypeRef, const void* clientInfo)
2796 {
2797     static_cast<TestController*>(const_cast<void*>(clientInfo))->decidePolicyForNavigationAction(navigationAction, listener);
2798 }
2799
2800 void TestController::decidePolicyForNavigationAction(WKNavigationActionRef navigationAction, WKFramePolicyListenerRef listener)
2801 {
2802     WKRetainPtr<WKFramePolicyListenerRef> retainedListener { listener };
2803     WKRetainPtr<WKNavigationActionRef> retainedNavigationAction { navigationAction };
2804     const bool shouldIgnore { m_policyDelegateEnabled && !m_policyDelegatePermissive };
2805     auto decisionFunction = [shouldIgnore, retainedListener, retainedNavigationAction]() {
2806         if (shouldIgnore)
2807             WKFramePolicyListenerIgnore(retainedListener.get());
2808         else if (WKNavigationActionShouldPerformDownload(retainedNavigationAction.get()))
2809             WKFramePolicyListenerDownload(retainedListener.get());
2810         else
2811             WKFramePolicyListenerUse(retainedListener.get());
2812     };
2813
2814     if (m_shouldDecideNavigationPolicyAfterDelay)
2815         RunLoop::main().dispatch(WTFMove(decisionFunction));
2816     else
2817         decisionFunction();
2818 }
2819
2820 void TestController::decidePolicyForNavigationResponse(WKPageRef, WKNavigationResponseRef navigationResponse, WKFramePolicyListenerRef listener, WKTypeRef, const void* clientInfo)
2821 {
2822     static_cast<TestController*>(const_cast<void*>(clientInfo))->decidePolicyForNavigationResponse(navigationResponse, listener);
2823 }
2824
2825 void TestController::decidePolicyForNavigationResponse(WKNavigationResponseRef navigationResponse, WKFramePolicyListenerRef listener)
2826 {
2827     WKRetainPtr<WKNavigationResponseRef> retainedNavigationResponse { navigationResponse };
2828     WKRetainPtr<WKFramePolicyListenerRef> retainedListener { listener };
2829
2830     bool shouldDownloadUndisplayableMIMETypes = m_shouldDownloadUndisplayableMIMETypes;
2831     auto decisionFunction = [shouldDownloadUndisplayableMIMETypes, retainedNavigationResponse, retainedListener]() {
2832         // Even though Response was already checked by WKBundlePagePolicyClient, the check did not include plugins
2833         // so we have to re-check again.
2834         if (WKNavigationResponseCanShowMIMEType(retainedNavigationResponse.get())) {
2835             WKFramePolicyListenerUse(retainedListener.get());
2836             return;
2837         }
2838
2839         if (shouldDownloadUndisplayableMIMETypes)
2840             WKFramePolicyListenerDownload(retainedListener.get());
2841         else
2842             WKFramePolicyListenerIgnore(retainedListener.get());
2843     };
2844
2845     if (m_shouldDecideResponsePolicyAfterDelay)
2846         RunLoop::main().dispatch(WTFMove(decisionFunction));
2847     else
2848         decisionFunction();
2849 }
2850
2851 void TestController::didNavigateWithNavigationData(WKContextRef, WKPageRef, WKNavigationDataRef navigationData, WKFrameRef frame, const void* clientInfo)
2852 {
2853     static_cast<TestController*>(const_cast<void*>(clientInfo))->didNavigateWithNavigationData(navigationData, frame);
2854 }
2855
2856 void TestController::didNavigateWithNavigationData(WKNavigationDataRef navigationData, WKFrameRef)
2857 {
2858     if (m_state != RunningTest)
2859         return;
2860
2861     if (!m_shouldLogHistoryClientCallbacks)
2862         return;
2863
2864     // URL
2865     auto url = adoptWK(WKNavigationDataCopyURL(navigationData));
2866     auto urlString = toWTFString(adoptWK(WKURLCopyString(url.get())));
2867     // Title
2868     auto title = toWTFString(adoptWK(WKNavigationDataCopyTitle(navigationData)));
2869     // HTTP method
2870     auto request = adoptWK(WKNavigationDataCopyOriginalRequest(navigationData));
2871     auto method = toWTFString(adoptWK(WKURLRequestCopyHTTPMethod(request.get())));
2872
2873     // FIXME: Determine whether the navigation was successful / a client redirect rather than hard-coding the message here.
2874     m_currentInvocation->outputText(makeString("WebView navigated to url \"", urlString, "\" with title \"", title, "\" with HTTP equivalent method \"", method,
2875         "\".  The navigation was successful and was not a client redirect.\n"));
2876 }
2877
2878 void TestController::didPerformClientRedirect(WKContextRef, WKPageRef, WKURLRef sourceURL, WKURLRef destinationURL, WKFrameRef frame, const void* clientInfo)
2879 {
2880     static_cast<TestController*>(const_cast<void*>(clientInfo))->didPerformClientRedirect(sourceURL, destinationURL, frame);
2881 }
2882
2883 void TestController::didPerformClientRedirect(WKURLRef sourceURL, WKURLRef destinationURL, WKFrameRef)
2884 {
2885     if (m_state != RunningTest)
2886         return;
2887
2888     if (!m_shouldLogHistoryClientCallbacks)
2889         return;
2890
2891     auto source = toWTFString(adoptWK(WKURLCopyString(sourceURL)));
2892     auto destination = toWTFString(adoptWK(WKURLCopyString(destinationURL)));
2893
2894     m_currentInvocation->outputText(makeString("WebView performed a client redirect from \"", source, "\" to \"", destination, "\".\n"));
2895 }
2896
2897 void TestController::didPerformServerRedirect(WKContextRef, WKPageRef, WKURLRef sourceURL, WKURLRef destinationURL, WKFrameRef frame, const void* clientInfo)
2898 {
2899     static_cast<TestController*>(const_cast<void*>(clientInfo))->didPerformServerRedirect(sourceURL, destinationURL, frame);
2900 }
2901
2902 void TestController::didPerformServerRedirect(WKURLRef sourceURL, WKURLRef destinationURL, WKFrameRef)
2903 {
2904     if (m_state != RunningTest)
2905         return;
2906
2907     if (!m_shouldLogHistoryClientCallbacks)
2908         return;
2909
2910     auto source = toWTFString(adoptWK(WKURLCopyString(sourceURL)));
2911     auto destination = toWTFString(adoptWK(WKURLCopyString(destinationURL)));
2912
2913     m_currentInvocation->outputText(makeString("WebView performed a server redirect from \"", source, "\" to \"", destination, "\".\n"));
2914 }
2915
2916 void TestController::didUpdateHistoryTitle(WKContextRef, WKPageRef, WKStringRef title, WKURLRef URL, WKFrameRef frame, const void* clientInfo)
2917 {
2918     static_cast<TestController*>(const_cast<void*>(clientInfo))->didUpdateHistoryTitle(title, URL, frame);
2919 }
2920
2921 void TestController::didUpdateHistoryTitle(WKStringRef title, WKURLRef URL, WKFrameRef)
2922 {
2923     if (m_state != RunningTest)
2924         return;
2925
2926     if (!m_shouldLogHistoryClientCallbacks)
2927         return;
2928
2929     auto urlString = toWTFString(adoptWK(WKURLCopyString(URL)));
2930     m_currentInvocation->outputText(makeString("WebView updated the title for history URL \"", urlString, "\" to \"", toWTFString(title), "\".\n"));
2931 }
2932
2933 void TestController::setNavigationGesturesEnabled(bool value)
2934 {
2935     m_mainWebView->setNavigationGesturesEnabled(value);
2936 }
2937
2938 void TestController::setIgnoresViewportScaleLimits(bool ignoresViewportScaleLimits)
2939 {
2940     WKPageSetIgnoresViewportScaleLimits(m_mainWebView->page(), ignoresViewportScaleLimits);
2941 }
2942
2943 void TestController::terminateNetworkProcess()
2944 {
2945     WKContextTerminateNetworkProcess(platformContext());
2946 }
2947
2948 void TestController::terminateServiceWorkerProcess()
2949 {
2950     WKContextTerminateServiceWorkerProcess(platformContext());
2951 }
2952
2953 #if !PLATFORM(COCOA)
2954 void TestController::platformWillRunTest(const TestInvocation&)
2955 {
2956 }
2957
2958 void TestController::platformCreateWebView(WKPageConfigurationRef configuration, const TestOptions& options)
2959 {
2960     m_mainWebView = makeUnique<PlatformWebView>(configuration, options);
2961 }
2962
2963 PlatformWebView* TestController::platformCreateOtherPage(PlatformWebView* parentView, WKPageConfigurationRef configuration, const TestOptions& options)
2964 {
2965     return new PlatformWebView(configuration, options);
2966 }
2967
2968 WKContextRef TestController::platformAdjustContext(WKContextRef context, WKContextConfigurationRef contextConfiguration)
2969 {
2970     auto* dataStore = WKContextGetWebsiteDataStore(context);
2971     WKWebsiteDataStoreSetResourceLoadStatisticsEnabled(dataStore, true);
2972
2973     if (const char* dumpRenderTreeTemp = libraryPathForTesting()) {
2974         String temporaryFolder = String::fromUTF8(dumpRenderTreeTemp);
2975
2976         WKWebsiteDataStoreSetServiceWorkerRegistrationDirectory(dataStore, toWK(temporaryFolder + pathSeparator + "ServiceWorkers").get());
2977     }
2978
2979     return context;
2980 }
2981
2982 void TestController::platformResetStateToConsistentValues(const TestOptions&)
2983 {
2984 }
2985
2986 unsigned TestController::imageCountInGeneralPasteboard() const
2987 {
2988     return 0;
2989 }
2990
2991 void TestController::removeAllSessionCredentials()
2992 {
2993 }
2994
2995 void TestController::getAllStorageAccessEntries()
2996 {
2997 }
2998
2999 #endif
3000
3001 struct ClearServiceWorkerRegistrationsCallbackContext {
3002     explicit ClearServiceWorkerRegistrationsCallbackContext(TestController& controller)
3003         : testController(controller)
3004     {
3005     }
3006
3007     TestController& testController;
3008     bool done { false };
3009 };
3010
3011 static void clearServiceWorkerRegistrationsCallback(void* userData)
3012 {
3013     auto* context = static_cast<ClearServiceWorkerRegistrationsCallbackContext*>(userData);
3014     context->done = true;
3015     context->testController.notifyDone();
3016 }
3017
3018 void TestController::clearServiceWorkerRegistrations()
3019 {
3020     auto websiteDataStore = WKContextGetWebsiteDataStore(platformContext());
3021     ClearServiceWorkerRegistrationsCallbackContext context(*this);
3022
3023     WKWebsiteDataStoreRemoveAllServiceWorkerRegistrations(websiteDataStore, &context, clearServiceWorkerRegistrationsCallback);
3024     runUntil(context.done, noTimeout);
3025 }
3026
3027 struct ClearDOMCacheCallbackContext {
3028     explicit ClearDOMCacheCallbackContext(TestController& controller)
3029         : testController(controller)
3030     {
3031     }
3032
3033     TestController& testController;
3034     bool done { false };
3035 };
3036
3037 static void clearDOMCacheCallback(void* userData)
3038 {
3039     auto* context = static_cast<ClearDOMCacheCallbackContext*>(userData);
3040     context->done = true;
3041     context->testController.notifyDone();
3042 }
3043
3044 void TestController::clearDOMCache(WKStringRef origin)
3045 {
3046     auto websiteDataStore = WKContextGetWebsiteDataStore(platformContext());
3047     ClearDOMCacheCallbackContext context(*this);
3048
3049     auto cacheOrigin = adoptWK(WKSecurityOriginCreateFromString(origin));
3050     WKWebsiteDataStoreRemoveFetchCacheForOrigin(websiteDataStore, cacheOrigin.get(), &context, clearDOMCacheCallback);
3051     runUntil(context.done, noTimeout);
3052 }
3053
3054 void TestController::clearDOMCaches()
3055 {
3056     auto websiteDataStore = WKContextGetWebsiteDataStore(platformContext());
3057     ClearDOMCacheCallbackContext context(*this);
3058
3059     WKWebsiteDataStoreRemoveAllFetchCaches(websiteDataStore, &context, clearDOMCacheCallback);
3060     runUntil(context.done, noTimeout);
3061 }
3062
3063 struct StorageVoidCallbackContext {
3064     explicit StorageVoidCallbackContext(TestController& controller)
3065         : testController(controller)
3066     {
3067     }
3068
3069     TestController& testController;
3070     bool done { false };
3071 };
3072
3073 static void StorageVoidCallback(void* userData)
3074 {
3075     auto* context = static_cast<StorageVoidCallbackContext*>(userData);
3076     context->done = true;
3077     context->testController.notifyDone();
3078 }
3079
3080 void TestController::clearIndexedDatabases()
3081 {
3082     auto websiteDataStore = WKContextGetWebsiteDataStore(platformContext());
3083     StorageVoidCallbackContext context(*this);
3084     WKWebsiteDataStoreRemoveAllIndexedDatabases(websiteDataStore, &context, StorageVoidCallback);
3085     runUntil(context.done, noTimeout);
3086 }
3087
3088 void TestController::clearLocalStorage()
3089 {
3090     auto websiteDataStore = WKContextGetWebsiteDataStore(platformContext());
3091     StorageVoidCallbackContext context(*this);
3092     WKWebsiteDataStoreRemoveLocalStorage(websiteDataStore, &context, StorageVoidCallback);
3093     runUntil(context.done, noTimeout);
3094
3095     StorageVoidCallbackContext legacyContext(*this);
3096     WKContextClearLegacyPrivateBrowsingLocalStorage(platformContext(), &legacyContext, StorageVoidCallback);
3097     runUntil(legacyContext.done, noTimeout);
3098 }
3099
3100 void TestController::syncLocalStorage()
3101 {
3102     StorageVoidCallbackContext context(*this);
3103     WKContextSyncLocalStorage(platformContext(), &context, StorageVoidCallback);
3104     runUntil(context.done, noTimeout);
3105 }
3106
3107 struct FetchCacheOriginsCallbackContext {
3108     FetchCacheOriginsCallbackContext(TestController& controller, WKStringRef origin)
3109         : testController(controller)
3110         , origin(origin)
3111     {
3112     }
3113
3114     TestController& testController;
3115     WKStringRef origin;
3116
3117     bool done { false };
3118     bool result { false };
3119 };
3120
3121 static void fetchCacheOriginsCallback(WKArrayRef origins, void* userData)
3122 {
3123     auto* context = static_cast<FetchCacheOriginsCallbackContext*>(userData);
3124     context->done = true;
3125
3126     auto size = WKArrayGetSize(origins);
3127     for (size_t index = 0; index < size && !context->result; ++index) {
3128         WKSecurityOriginRef securityOrigin = reinterpret_cast<WKSecurityOriginRef>(WKArrayGetItemAtIndex(origins, index));
3129         if (WKStringIsEqual(context->origin, adoptWK(WKSecurityOriginCopyToString(securityOrigin)).get()))
3130             context->result = true;
3131     }
3132     context->testController.notifyDone();
3133 }
3134
3135 bool TestController::hasDOMCache(WKStringRef origin)
3136 {
3137     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3138     FetchCacheOriginsCallbackContext context(*this, origin);
3139     WKWebsiteDataStoreGetFetchCacheOrigins(dataStore, &context, fetchCacheOriginsCallback);
3140     runUntil(context.done, noTimeout);
3141     return context.result;
3142 }
3143
3144 struct FetchCacheSizeForOriginCallbackContext {
3145     explicit FetchCacheSizeForOriginCallbackContext(TestController& controller)
3146         : testController(controller)
3147     {
3148     }
3149
3150     TestController& testController;
3151
3152     bool done { false };
3153     uint64_t result { 0 };
3154 };
3155
3156 static void fetchCacheSizeForOriginCallback(uint64_t size, void* userData)
3157 {
3158     auto* context = static_cast<FetchCacheSizeForOriginCallbackContext*>(userData);
3159     context->done = true;
3160     context->result = size;
3161     context->testController.notifyDone();
3162 }
3163
3164 uint64_t TestController::domCacheSize(WKStringRef origin)
3165 {
3166     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3167     FetchCacheSizeForOriginCallbackContext context(*this);
3168     WKWebsiteDataStoreGetFetchCacheSizeForOrigin(dataStore, origin, &context, fetchCacheSizeForOriginCallback);
3169     runUntil(context.done, noTimeout);
3170     return context.result;
3171 }
3172
3173 #if !PLATFORM(COCOA)
3174 void TestController::setAllowStorageQuotaIncrease(bool)
3175 {
3176     // FIXME: To implement.
3177 }
3178
3179 bool TestController::isDoingMediaCapture() const
3180 {
3181     return false;
3182 }
3183
3184 #endif
3185
3186 struct ResourceStatisticsCallbackContext {
3187     explicit ResourceStatisticsCallbackContext(TestController& controller)
3188         : testController(controller)
3189     {
3190     }
3191
3192     TestController& testController;
3193     bool done { false };
3194     bool result { false };
3195     WKRetainPtr<WKStringRef> resourceLoadStatisticsRepresentation;
3196 };
3197     
3198 static void resourceStatisticsStringResultCallback(WKStringRef resourceLoadStatisticsRepresentation, void* userData)
3199 {
3200     auto* context = static_cast<ResourceStatisticsCallbackContext*>(userData);
3201     context->resourceLoadStatisticsRepresentation = resourceLoadStatisticsRepresentation;
3202     context->done = true;
3203     context->testController.notifyDone();
3204 }
3205
3206 static void resourceStatisticsVoidResultCallback(void* userData)
3207 {
3208     auto* context = static_cast<ResourceStatisticsCallbackContext*>(userData);
3209     context->done = true;
3210     context->testController.notifyDone();
3211 }
3212
3213 static void resourceStatisticsBooleanResultCallback(bool result, void* userData)
3214 {
3215     auto* context = static_cast<ResourceStatisticsCallbackContext*>(userData);
3216     context->result = result;
3217     context->done = true;
3218     context->testController.notifyDone();
3219 }
3220
3221 void TestController::setStatisticsDebugMode(bool value)
3222 {
3223     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3224     ResourceStatisticsCallbackContext context(*this);
3225     WKWebsiteDataStoreSetResourceLoadStatisticsDebugModeWithCompletionHandler(dataStore, value, &context, resourceStatisticsVoidResultCallback);
3226     runUntil(context.done, noTimeout);
3227     m_currentInvocation->didSetStatisticsDebugMode();
3228 }
3229
3230 void TestController::setStatisticsPrevalentResourceForDebugMode(WKStringRef hostName)
3231 {
3232     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3233     ResourceStatisticsCallbackContext context(*this);
3234     WKWebsiteDataStoreSetResourceLoadStatisticsPrevalentResourceForDebugMode(dataStore, hostName, &context, resourceStatisticsVoidResultCallback);
3235     runUntil(context.done, noTimeout);
3236     m_currentInvocation->didSetPrevalentResourceForDebugMode();
3237 }
3238
3239 void TestController::setStatisticsLastSeen(WKStringRef host, double seconds)
3240 {
3241     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3242     ResourceStatisticsCallbackContext context(*this);
3243     WKWebsiteDataStoreSetStatisticsLastSeen(dataStore, host, seconds, &context, resourceStatisticsVoidResultCallback);
3244     runUntil(context.done, noTimeout);
3245     m_currentInvocation->didSetLastSeen();
3246 }
3247
3248 void TestController::setStatisticsPrevalentResource(WKStringRef host, bool value)
3249 {
3250     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3251     ResourceStatisticsCallbackContext context(*this);
3252     WKWebsiteDataStoreSetStatisticsPrevalentResource(dataStore, host, value, &context, resourceStatisticsVoidResultCallback);
3253     runUntil(context.done, noTimeout);
3254     m_currentInvocation->didSetPrevalentResource();
3255 }
3256
3257 void TestController::setStatisticsVeryPrevalentResource(WKStringRef host, bool value)
3258 {
3259     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3260     ResourceStatisticsCallbackContext context(*this);
3261     WKWebsiteDataStoreSetStatisticsVeryPrevalentResource(dataStore, host, value, &context, resourceStatisticsVoidResultCallback);
3262     runUntil(context.done, noTimeout);
3263     m_currentInvocation->didSetVeryPrevalentResource();
3264 }
3265     
3266 String TestController::dumpResourceLoadStatistics()
3267 {
3268     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3269     ResourceStatisticsCallbackContext context(*this);
3270     WKWebsiteDataStoreDumpResourceLoadStatistics(dataStore, &context, resourceStatisticsStringResultCallback);
3271     runUntil(context.done, noTimeout);
3272     return toWTFString(context.resourceLoadStatisticsRepresentation.get());
3273 }
3274
3275 bool TestController::isStatisticsPrevalentResource(WKStringRef host)
3276 {
3277     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3278     ResourceStatisticsCallbackContext context(*this);
3279     WKWebsiteDataStoreIsStatisticsPrevalentResource(dataStore, host, &context, resourceStatisticsBooleanResultCallback);
3280     runUntil(context.done, noTimeout);
3281     return context.result;
3282 }
3283
3284 bool TestController::isStatisticsVeryPrevalentResource(WKStringRef host)
3285 {
3286     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3287     ResourceStatisticsCallbackContext context(*this);
3288     WKWebsiteDataStoreIsStatisticsVeryPrevalentResource(dataStore, host, &context, resourceStatisticsBooleanResultCallback);
3289     runUntil(context.done, noTimeout);
3290     return context.result;
3291 }
3292
3293 bool TestController::isStatisticsRegisteredAsSubresourceUnder(WKStringRef subresourceHost, WKStringRef topFrameHost)
3294 {
3295     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3296     ResourceStatisticsCallbackContext context(*this);
3297     WKWebsiteDataStoreIsStatisticsRegisteredAsSubresourceUnder(dataStore, subresourceHost, topFrameHost, &context, resourceStatisticsBooleanResultCallback);
3298     runUntil(context.done, noTimeout);
3299     return context.result;
3300 }
3301
3302 bool TestController::isStatisticsRegisteredAsSubFrameUnder(WKStringRef subFrameHost, WKStringRef topFrameHost)
3303 {
3304     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3305     ResourceStatisticsCallbackContext context(*this);
3306     WKWebsiteDataStoreIsStatisticsRegisteredAsSubFrameUnder(dataStore, subFrameHost, topFrameHost, &context, resourceStatisticsBooleanResultCallback);
3307     runUntil(context.done, noTimeout);
3308     return context.result;
3309 }
3310
3311 bool TestController::isStatisticsRegisteredAsRedirectingTo(WKStringRef hostRedirectedFrom, WKStringRef hostRedirectedTo)
3312 {
3313     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3314     ResourceStatisticsCallbackContext context(*this);
3315     WKWebsiteDataStoreIsStatisticsRegisteredAsRedirectingTo(dataStore, hostRedirectedFrom, hostRedirectedTo, &context, resourceStatisticsBooleanResultCallback);
3316     runUntil(context.done, noTimeout);
3317     return context.result;
3318 }
3319
3320 void TestController::setStatisticsHasHadUserInteraction(WKStringRef host, bool value)
3321 {
3322     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3323     ResourceStatisticsCallbackContext context(*this);
3324     WKWebsiteDataStoreSetStatisticsHasHadUserInteraction(dataStore, host, value, &context, resourceStatisticsVoidResultCallback);
3325     runUntil(context.done, noTimeout);
3326     m_currentInvocation->didSetHasHadUserInteraction();
3327 }
3328
3329 bool TestController::isStatisticsHasHadUserInteraction(WKStringRef host)
3330 {
3331     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3332     ResourceStatisticsCallbackContext context(*this);
3333     WKWebsiteDataStoreIsStatisticsHasHadUserInteraction(dataStore, host, &context, resourceStatisticsBooleanResultCallback);
3334     runUntil(context.done, noTimeout);
3335     return context.result;
3336 }
3337
3338 void TestController::setStatisticsGrandfathered(WKStringRef host, bool value)
3339 {
3340     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3341     WKWebsiteDataStoreSetStatisticsGrandfathered(dataStore, host, value);
3342 }
3343
3344 bool TestController::isStatisticsGrandfathered(WKStringRef host)
3345 {
3346     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3347     ResourceStatisticsCallbackContext context(*this);
3348     WKWebsiteDataStoreIsStatisticsGrandfathered(dataStore, host, &context, resourceStatisticsBooleanResultCallback);
3349     runUntil(context.done, noTimeout);
3350     return context.result;
3351 }
3352
3353 void TestController::setStatisticsSubframeUnderTopFrameOrigin(WKStringRef host, WKStringRef topFrameHost)
3354 {
3355     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3356     WKWebsiteDataStoreSetStatisticsSubframeUnderTopFrameOrigin(dataStore, host, topFrameHost);
3357 }
3358
3359 void TestController::setStatisticsSubresourceUnderTopFrameOrigin(WKStringRef host, WKStringRef topFrameHost)
3360 {
3361     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3362     WKWebsiteDataStoreSetStatisticsSubresourceUnderTopFrameOrigin(dataStore, host, topFrameHost);
3363 }
3364
3365 void TestController::setStatisticsSubresourceUniqueRedirectTo(WKStringRef host, WKStringRef hostRedirectedTo)
3366 {
3367     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3368     WKWebsiteDataStoreSetStatisticsSubresourceUniqueRedirectTo(dataStore, host, hostRedirectedTo);
3369 }
3370
3371 void TestController::setStatisticsSubresourceUniqueRedirectFrom(WKStringRef host, WKStringRef hostRedirectedFrom)
3372 {
3373     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3374     WKWebsiteDataStoreSetStatisticsSubresourceUniqueRedirectFrom(dataStore, host, hostRedirectedFrom);
3375 }
3376
3377 void TestController::setStatisticsTopFrameUniqueRedirectTo(WKStringRef host, WKStringRef hostRedirectedTo)
3378 {
3379     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3380     WKWebsiteDataStoreSetStatisticsTopFrameUniqueRedirectTo(dataStore, host, hostRedirectedTo);
3381 }
3382
3383 void TestController::setStatisticsTopFrameUniqueRedirectFrom(WKStringRef host, WKStringRef hostRedirectedFrom)
3384 {
3385     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3386     WKWebsiteDataStoreSetStatisticsTopFrameUniqueRedirectFrom(dataStore, host, hostRedirectedFrom);
3387 }
3388
3389 void TestController::setStatisticsCrossSiteLoadWithLinkDecoration(WKStringRef fromHost, WKStringRef toHost)
3390 {
3391     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3392     ResourceStatisticsCallbackContext context(*this);
3393     WKWebsiteDataStoreSetStatisticsCrossSiteLoadWithLinkDecoration(dataStore, fromHost, toHost, &context, resourceStatisticsVoidResultCallback);
3394     runUntil(context.done, noTimeout);
3395 }
3396
3397 void TestController::setStatisticsTimeToLiveUserInteraction(double seconds)
3398 {
3399     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3400     ResourceStatisticsCallbackContext context(*this);
3401     WKWebsiteDataStoreSetStatisticsTimeToLiveUserInteraction(dataStore, seconds, &context, resourceStatisticsVoidResultCallback);
3402     runUntil(context.done, noTimeout);
3403 }
3404
3405 void TestController::statisticsProcessStatisticsAndDataRecords()
3406 {
3407     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3408     ResourceStatisticsCallbackContext context(*this);
3409     WKWebsiteDataStoreStatisticsProcessStatisticsAndDataRecords(dataStore, &context, resourceStatisticsVoidResultCallback);
3410     runUntil(context.done, noTimeout);
3411 }
3412
3413 void TestController::statisticsUpdateCookieBlocking()
3414 {
3415     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3416     ResourceStatisticsCallbackContext context(*this);
3417     WKWebsiteDataStoreStatisticsUpdateCookieBlocking(dataStore, &context, resourceStatisticsVoidResultCallback);
3418     runUntil(context.done, noTimeout);
3419     m_currentInvocation->didSetBlockCookiesForHost();
3420 }
3421
3422 void TestController::statisticsSubmitTelemetry()
3423 {
3424     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3425     WKWebsiteDataStoreStatisticsSubmitTelemetry(dataStore);
3426 }
3427
3428 void TestController::setStatisticsNotifyPagesWhenDataRecordsWereScanned(bool value)
3429 {
3430     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3431     WKWebsiteDataStoreSetStatisticsNotifyPagesWhenDataRecordsWereScanned(dataStore, value);
3432 }
3433
3434 void TestController::setStatisticsIsRunningTest(bool value)
3435 {
3436     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3437     ResourceStatisticsCallbackContext context(*this);
3438     WKWebsiteDataStoreSetStatisticsIsRunningTest(dataStore, value, &context, resourceStatisticsVoidResultCallback);
3439     runUntil(context.done, noTimeout);
3440 }
3441
3442 void TestController::setStatisticsShouldClassifyResourcesBeforeDataRecordsRemoval(bool value)
3443 {
3444     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3445     WKWebsiteDataStoreSetStatisticsShouldClassifyResourcesBeforeDataRecordsRemoval(dataStore, value);
3446 }
3447
3448 void TestController::setStatisticsNotifyPagesWhenTelemetryWasCaptured(bool value)
3449 {