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