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