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