3e9eeb654f67a547911b1090fb17621ae57a34b6
[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     platformResetPreferencesToConsistentValues();
870 }
871
872 bool TestController::resetStateToConsistentValues(const TestOptions& options, ResetStage resetStage)
873 {
874     SetForScope<State> changeState(m_state, Resetting);
875     m_beforeUnloadReturnValue = true;
876
877     // This setting differs between the antique and modern Mac WebKit2 API.
878     // For now, maintain the antique behavior, because some tests depend on it!
879     // FIXME: We should be testing the default.
880     WKPageSetBackgroundExtendsBeyondPage(m_mainWebView->page(), false);
881
882     WKPageSetCustomUserAgent(m_mainWebView->page(), nullptr);
883
884     WKRetainPtr<WKStringRef> messageName = adoptWK(WKStringCreateWithUTF8CString("Reset"));
885     WKRetainPtr<WKMutableDictionaryRef> resetMessageBody = adoptWK(WKMutableDictionaryCreate());
886
887     WKRetainPtr<WKStringRef> shouldGCKey = adoptWK(WKStringCreateWithUTF8CString("ShouldGC"));
888     WKRetainPtr<WKBooleanRef> shouldGCValue = adoptWK(WKBooleanCreate(m_gcBetweenTests));
889     WKDictionarySetItem(resetMessageBody.get(), shouldGCKey.get(), shouldGCValue.get());
890
891     WKRetainPtr<WKStringRef> allowedHostsKey = adoptWK(WKStringCreateWithUTF8CString("AllowedHosts"));
892     WKRetainPtr<WKMutableArrayRef> allowedHostsValue = adoptWK(WKMutableArrayCreate());
893     for (auto& host : m_allowedHosts) {
894         WKRetainPtr<WKStringRef> wkHost = adoptWK(WKStringCreateWithUTF8CString(host.c_str()));
895         WKArrayAppendItem(allowedHostsValue.get(), wkHost.get());
896     }
897     WKDictionarySetItem(resetMessageBody.get(), allowedHostsKey.get(), allowedHostsValue.get());
898
899     if (options.jscOptions.length()) {
900         WKRetainPtr<WKStringRef> jscOptionsKey = adoptWK(WKStringCreateWithUTF8CString("JSCOptions"));
901         WKRetainPtr<WKStringRef> jscOptionsValue = adoptWK(WKStringCreateWithUTF8CString(options.jscOptions.c_str()));
902         WKDictionarySetItem(resetMessageBody.get(), jscOptionsKey.get(), jscOptionsValue.get());
903     }
904
905     WKPagePostMessageToInjectedBundle(TestController::singleton().mainWebView()->page(), messageName.get(), resetMessageBody.get());
906
907     WKContextSetShouldUseFontSmoothing(TestController::singleton().context(), false);
908
909     WKContextSetCacheModel(TestController::singleton().context(), kWKCacheModelDocumentBrowser);
910
911     WKContextClearCachedCredentials(TestController::singleton().context());
912
913     ClearIndexedDatabases();
914     setIDBPerOriginQuota(50 * MB);
915
916     clearServiceWorkerRegistrations();
917     clearDOMCaches();
918
919     WKContextSetAllowsAnySSLCertificateForServiceWorkerTesting(platformContext(), true);
920
921     WKContextClearCurrentModifierStateForTesting(TestController::singleton().context());
922
923     // FIXME: This function should also ensure that there is only one page open.
924
925     // Reset the EventSender for each test.
926     m_eventSenderProxy = std::make_unique<EventSenderProxy>(this);
927
928     // FIXME: Is this needed? Nothing in TestController changes preferences during tests, and if there is
929     // some other code doing this, it should probably be responsible for cleanup too.
930     resetPreferencesToConsistentValues(options);
931
932 #if PLATFORM(GTK)
933     WKTextCheckerContinuousSpellCheckingEnabledStateChanged(true);
934 #endif
935
936     // Make sure the view is in the window (a test can unparent it).
937     m_mainWebView->addToWindow();
938
939     // In the case that a test using the chrome input field failed, be sure to clean up for the next test.
940     m_mainWebView->removeChromeInputField();
941     m_mainWebView->focus();
942
943     // Re-set to the default backing scale factor by setting the custom scale factor to 0.
944     WKPageSetCustomBackingScaleFactor(m_mainWebView->page(), 0);
945
946     WKPageClearWheelEventTestTrigger(m_mainWebView->page());
947
948     WKPageSetMuted(m_mainWebView->page(), true);
949
950     WKPageClearUserMediaState(m_mainWebView->page());
951
952     // Reset notification permissions
953     m_webNotificationProvider.reset();
954
955     // Reset Geolocation permissions.
956     m_geolocationPermissionRequests.clear();
957     m_isGeolocationPermissionSet = false;
958     m_isGeolocationPermissionAllowed = false;
959
960     // Reset UserMedia permissions.
961     m_userMediaPermissionRequests.clear();
962     m_cachedUserMediaPermissions.clear();
963     setUserMediaPermission(true);
964
965     // Reset Custom Policy Delegate.
966     setCustomPolicyDelegate(false, false);
967
968     // Reset Content Extensions.
969     resetContentExtensions();
970
971     m_shouldDownloadUndisplayableMIMETypes = false;
972
973     m_shouldAllowDeviceOrientationAndMotionAccess = false;
974
975     m_workQueueManager.clearWorkQueue();
976
977     m_rejectsProtectionSpaceAndContinueForAuthenticationChallenges = false;
978     m_handlesAuthenticationChallenges = false;
979     m_authenticationUsername = String();
980     m_authenticationPassword = String();
981
982     setBlockAllPlugins(false);
983     setPluginSupportedMode({ });
984
985     m_shouldLogDownloadCallbacks = false;
986     m_shouldLogHistoryClientCallbacks = false;
987     m_shouldLogCanAuthenticateAgainstProtectionSpace = false;
988
989     setHidden(false);
990
991     platformResetStateToConsistentValues(options);
992
993     m_shouldDecideNavigationPolicyAfterDelay = false;
994     m_shouldDecideResponsePolicyAfterDelay = false;
995
996     setNavigationGesturesEnabled(false);
997     
998     setIgnoresViewportScaleLimits(options.ignoresViewportScaleLimits);
999
1000     m_openPanelFileURLs = nullptr;
1001     
1002     statisticsResetToConsistentState();
1003     
1004     clearAdClickAttribution();
1005
1006     m_didReceiveServerRedirectForProvisionalNavigation = false;
1007     m_serverTrustEvaluationCallbackCallsCount = 0;
1008     m_shouldDismissJavaScriptAlertsAsynchronously = false;
1009
1010     // Reset main page back to about:blank
1011     m_doneResetting = false;
1012     WKPageLoadURL(m_mainWebView->page(), blankURL());
1013     runUntil(m_doneResetting, m_currentInvocation->shortTimeout());
1014     if (!m_doneResetting)
1015         return false;
1016     
1017     if (resetStage == ResetStage::AfterTest)
1018         updateLiveDocumentsAfterTest();
1019
1020     return m_doneResetting;
1021 }
1022
1023 void TestController::updateLiveDocumentsAfterTest()
1024 {
1025     if (!m_checkForWorldLeaks)
1026         return;
1027
1028     AsyncTask([]() {
1029         // After each test, we update the list of live documents so that we can detect when an abandoned document first showed up.
1030         WKRetainPtr<WKStringRef> messageName = adoptWK(WKStringCreateWithUTF8CString("GetLiveDocuments"));
1031         WKPagePostMessageToInjectedBundle(TestController::singleton().mainWebView()->page(), messageName.get(), nullptr);
1032     }, 5_s).run();
1033 }
1034
1035 void TestController::checkForWorldLeaks()
1036 {
1037     if (!m_checkForWorldLeaks || !TestController::singleton().mainWebView())
1038         return;
1039
1040     AsyncTask([]() {
1041         // This runs at the end of a series of tests. It clears caches, runs a GC and then fetches the list of documents.
1042         WKRetainPtr<WKStringRef> messageName = adoptWK(WKStringCreateWithUTF8CString("CheckForWorldLeaks"));
1043         WKPagePostMessageToInjectedBundle(TestController::singleton().mainWebView()->page(), messageName.get(), nullptr);
1044     }, 20_s).run();
1045 }
1046
1047 void TestController::dumpResponse(const String& result)
1048 {
1049     unsigned resultLength = result.length();
1050     printf("Content-Type: text/plain\n");
1051     printf("Content-Length: %u\n", resultLength);
1052     fwrite(result.utf8().data(), 1, resultLength, stdout);
1053     printf("#EOF\n");
1054     fprintf(stderr, "#EOF\n");
1055     fflush(stdout);
1056     fflush(stderr);
1057 }
1058
1059 void TestController::findAndDumpWebKitProcessIdentifiers()
1060 {
1061     StringBuilder builder;
1062
1063 #if PLATFORM(COCOA)
1064     builder.append(TestController::webProcessName());
1065     builder.appendLiteral(": ");
1066     pid_t webContentPID = WKPageGetProcessIdentifier(TestController::singleton().mainWebView()->page());
1067     builder.appendNumber(webContentPID);
1068     builder.append('\n');
1069
1070     builder.append(TestController::networkProcessName());
1071     builder.appendLiteral(": ");
1072     pid_t networkingPID = WKContextGetNetworkProcessIdentifier(m_context.get());
1073     builder.appendNumber(networkingPID);
1074     builder.append('\n');
1075 #else
1076     builder.append('\n');
1077 #endif
1078
1079     dumpResponse(builder.toString());
1080 }
1081
1082 void TestController::findAndDumpWorldLeaks()
1083 {
1084     if (!m_checkForWorldLeaks)
1085         return;
1086
1087     checkForWorldLeaks();
1088
1089     StringBuilder builder;
1090     
1091     if (m_abandonedDocumentInfo.size()) {
1092         for (const auto& it : m_abandonedDocumentInfo) {
1093             auto documentURL = it.value.abandonedDocumentURL;
1094             if (documentURL.isEmpty())
1095                 documentURL = "(no url)";
1096             builder.append("TEST: ");
1097             builder.append(it.value.testURL);
1098             builder.append('\n');
1099             builder.append("ABANDONED DOCUMENT: ");
1100             builder.append(documentURL);
1101             builder.append('\n');
1102         }
1103     } else
1104         builder.append("no abandoned documents\n");
1105
1106     dumpResponse(builder.toString());
1107 }
1108
1109 void TestController::willDestroyWebView()
1110 {
1111     // Before we kill the web view, look for abandoned documents before that web process goes away.
1112     checkForWorldLeaks();
1113 }
1114
1115 void TestController::terminateWebContentProcess()
1116 {
1117     WKPageTerminate(m_mainWebView->page());
1118 }
1119
1120 void TestController::reattachPageToWebProcess()
1121 {
1122     // Loading a web page is the only way to reattach an existing page to a process.
1123     SetForScope<State> changeState(m_state, Resetting);
1124     m_doneResetting = false;
1125     WKPageLoadURL(m_mainWebView->page(), blankURL());
1126     runUntil(m_doneResetting, noTimeout);
1127 }
1128
1129 const char* TestController::webProcessName()
1130 {
1131     // FIXME: Find a way to not hardcode the process name.
1132 #if PLATFORM(IOS_FAMILY) && !PLATFORM(IOS_FAMILY_SIMULATOR)
1133     return "com.apple.WebKit.WebContent";
1134 #elif PLATFORM(COCOA)
1135     return "com.apple.WebKit.WebContent.Development";
1136 #elif PLATFORM(GTK)
1137     return "WebKitWebProcess";
1138 #elif PLATFORM(WPE)
1139     return "WPEWebProcess";
1140 #else
1141     return "WebProcess";
1142 #endif
1143 }
1144
1145 const char* TestController::networkProcessName()
1146 {
1147     // FIXME: Find a way to not hardcode the process name.
1148 #if PLATFORM(IOS_FAMILY) && !PLATFORM(IOS_FAMILY_SIMULATOR)
1149     return "com.apple.WebKit.Networking";
1150 #elif PLATFORM(COCOA)
1151     return "com.apple.WebKit.Networking.Development";
1152 #elif PLATFORM(GTK)
1153     return "WebKitNetworkProcess";
1154 #elif PLATFORM(WPE)
1155     return "WPENetworkProcess";
1156 #else
1157     return "NetworkProcess";
1158 #endif
1159 }
1160
1161 void TestController::setAllowsAnySSLCertificate(bool allows)
1162 {
1163     WKContextSetAllowsAnySSLCertificateForWebSocketTesting(platformContext(), allows);
1164 }
1165
1166 static std::string testPath(WKURLRef url)
1167 {
1168     auto scheme = adoptWK(WKURLCopyScheme(url));
1169     if (WKStringIsEqualToUTF8CStringIgnoringCase(scheme.get(), "file")) {
1170         auto path = adoptWK(WKURLCopyPath(url));
1171         auto buffer = std::vector<char>(WKStringGetMaximumUTF8CStringSize(path.get()));
1172         auto length = WKStringGetUTF8CString(path.get(), buffer.data(), buffer.size());
1173         RELEASE_ASSERT(length > 0);
1174 #if OS(WINDOWS)
1175         // Remove the first '/' if it starts with something like "/C:/".
1176         if (length >= 4 && buffer[0] == '/' && buffer[2] == ':' && buffer[3] == '/')
1177             return std::string(buffer.data() + 1, length - 1);
1178 #endif
1179         return std::string(buffer.data(), length - 1);
1180     }
1181     return std::string();
1182 }
1183
1184 static WKURLRef createTestURL(const char* pathOrURL)
1185 {
1186     if (strstr(pathOrURL, "http://") || strstr(pathOrURL, "https://") || strstr(pathOrURL, "file://"))
1187         return WKURLCreateWithUTF8CString(pathOrURL);
1188
1189     // Creating from filesytem path.
1190     size_t length = strlen(pathOrURL);
1191     if (!length)
1192         return 0;
1193
1194 #if PLATFORM(WIN)
1195     bool isAbsolutePath = false;
1196     if (strlen(pathOrURL) >= 3 && pathOrURL[1] == ':' && pathOrURL[2] == pathSeparator)
1197         isAbsolutePath = true;
1198 #else
1199     bool isAbsolutePath = pathOrURL[0] == pathSeparator;
1200 #endif
1201     const char* filePrefix = "file://";
1202     static const size_t prefixLength = strlen(filePrefix);
1203
1204     std::unique_ptr<char[]> buffer;
1205     if (isAbsolutePath) {
1206         buffer = std::make_unique<char[]>(prefixLength + length + 1);
1207         strcpy(buffer.get(), filePrefix);
1208         strcpy(buffer.get() + prefixLength, pathOrURL);
1209     } else {
1210         buffer = std::make_unique<char[]>(prefixLength + PATH_MAX + length + 2); // 1 for the pathSeparator
1211         strcpy(buffer.get(), filePrefix);
1212         if (!getcwd(buffer.get() + prefixLength, PATH_MAX))
1213             return 0;
1214         size_t numCharacters = strlen(buffer.get());
1215         buffer[numCharacters] = pathSeparator;
1216         strcpy(buffer.get() + numCharacters + 1, pathOrURL);
1217     }
1218
1219     return WKURLCreateWithUTF8CString(buffer.get());
1220 }
1221
1222 static bool parseBooleanTestHeaderValue(const std::string& value)
1223 {
1224     if (value == "true")
1225         return true;
1226     if (value == "false")
1227         return false;
1228
1229     LOG_ERROR("Found unexpected value '%s' for boolean option. Expected 'true' or 'false'.", value.c_str());
1230     return false;
1231 }
1232
1233 static std::string parseStringTestHeaderValueAsRelativePath(const std::string& value, const std::string& pathOrURL)
1234 {
1235     WKRetainPtr<WKURLRef> baseURL(AdoptWK, createTestURL(pathOrURL.c_str()));
1236     WKRetainPtr<WKURLRef> relativeURL(AdoptWK, WKURLCreateWithBaseURL(baseURL.get(), value.c_str()));
1237     return toSTD(adoptWK(WKURLCopyPath(relativeURL.get())));
1238 }
1239
1240 static void updateTestOptionsFromTestHeader(TestOptions& testOptions, const std::string& pathOrURL, const std::string& absolutePath)
1241 {
1242     std::string filename = absolutePath;
1243     if (filename.empty()) {
1244         // Gross. Need to reduce conversions between all the string types and URLs.
1245         WKRetainPtr<WKURLRef> wkURL(AdoptWK, createTestURL(pathOrURL.c_str()));
1246         filename = testPath(wkURL.get());
1247     }
1248
1249     if (filename.empty())
1250         return;
1251
1252     std::string options;
1253     std::ifstream testFile(filename.data());
1254     if (!testFile.good())
1255         return;
1256     getline(testFile, options);
1257     std::string beginString("webkit-test-runner [ ");
1258     std::string endString(" ]");
1259     size_t beginLocation = options.find(beginString);
1260     if (beginLocation == std::string::npos)
1261         return;
1262     size_t endLocation = options.find(endString, beginLocation);
1263     if (endLocation == std::string::npos) {
1264         LOG_ERROR("Could not find end of test header in %s", filename.c_str());
1265         return;
1266     }
1267     std::string pairString = options.substr(beginLocation + beginString.size(), endLocation - (beginLocation + beginString.size()));
1268     size_t pairStart = 0;
1269     while (pairStart < pairString.size()) {
1270         size_t pairEnd = pairString.find(" ", pairStart);
1271         if (pairEnd == std::string::npos)
1272             pairEnd = pairString.size();
1273         size_t equalsLocation = pairString.find("=", pairStart);
1274         if (equalsLocation == std::string::npos) {
1275             LOG_ERROR("Malformed option in test header (could not find '=' character) in %s", filename.c_str());
1276             break;
1277         }
1278         auto key = pairString.substr(pairStart, equalsLocation - pairStart);
1279         auto value = pairString.substr(equalsLocation + 1, pairEnd - (equalsLocation + 1));
1280
1281         if (!key.rfind("experimental:")) {
1282             key = key.substr(13);
1283             testOptions.experimentalFeatures.add(String(key.c_str()), parseBooleanTestHeaderValue(value));
1284         }
1285
1286         if (!key.rfind("internal:")) {
1287             key = key.substr(9);
1288             testOptions.internalDebugFeatures.add(String(key.c_str()), parseBooleanTestHeaderValue(value));
1289         }
1290
1291         if (key == "language")
1292             testOptions.contextOptions.overrideLanguages = String(value.c_str()).split(',');
1293         else if (key == "useThreadedScrolling")
1294             testOptions.useThreadedScrolling = parseBooleanTestHeaderValue(value);
1295         else if (key == "useAcceleratedDrawing")
1296             testOptions.useAcceleratedDrawing = parseBooleanTestHeaderValue(value);
1297         else if (key == "useFlexibleViewport")
1298             testOptions.useFlexibleViewport = parseBooleanTestHeaderValue(value);
1299         else if (key == "useDataDetection")
1300             testOptions.useDataDetection = parseBooleanTestHeaderValue(value);
1301         else if (key == "useMockScrollbars")
1302             testOptions.useMockScrollbars = parseBooleanTestHeaderValue(value);
1303         else if (key == "needsSiteSpecificQuirks")
1304             testOptions.needsSiteSpecificQuirks = parseBooleanTestHeaderValue(value);
1305         else if (key == "ignoresViewportScaleLimits")
1306             testOptions.ignoresViewportScaleLimits = parseBooleanTestHeaderValue(value);
1307         else if (key == "useCharacterSelectionGranularity")
1308             testOptions.useCharacterSelectionGranularity = parseBooleanTestHeaderValue(value);
1309         else if (key == "enableAttachmentElement")
1310             testOptions.enableAttachmentElement = parseBooleanTestHeaderValue(value);
1311         else if (key == "enableIntersectionObserver")
1312             testOptions.enableIntersectionObserver = parseBooleanTestHeaderValue(value);
1313         else if (key == "enableMenuItemElement")
1314             testOptions.enableMenuItemElement = parseBooleanTestHeaderValue(value);
1315         else if (key == "enableModernMediaControls")
1316             testOptions.enableModernMediaControls = parseBooleanTestHeaderValue(value);
1317         else if (key == "enablePointerLock")
1318             testOptions.enablePointerLock = parseBooleanTestHeaderValue(value);
1319         else if (key == "enableWebAuthentication")
1320             testOptions.enableWebAuthentication = parseBooleanTestHeaderValue(value);
1321         else if (key == "enableWebAuthenticationLocalAuthenticator")
1322             testOptions.enableWebAuthenticationLocalAuthenticator = parseBooleanTestHeaderValue(value);
1323         else if (key == "enableIsSecureContextAttribute")
1324             testOptions.enableIsSecureContextAttribute = parseBooleanTestHeaderValue(value);
1325         else if (key == "enableInspectorAdditions")
1326             testOptions.enableInspectorAdditions = parseBooleanTestHeaderValue(value);
1327         else if (key == "dumpJSConsoleLogInStdErr")
1328             testOptions.dumpJSConsoleLogInStdErr = parseBooleanTestHeaderValue(value);
1329         else if (key == "applicationManifest")
1330             testOptions.applicationManifest = parseStringTestHeaderValueAsRelativePath(value, pathOrURL);
1331         else if (key == "allowCrossOriginSubresourcesToAskForCredentials")
1332             testOptions.allowCrossOriginSubresourcesToAskForCredentials = parseBooleanTestHeaderValue(value);
1333         else if (key == "domPasteAllowed")
1334             testOptions.domPasteAllowed = parseBooleanTestHeaderValue(value);
1335         else if (key == "enableProcessSwapOnNavigation")
1336             testOptions.contextOptions.enableProcessSwapOnNavigation = parseBooleanTestHeaderValue(value);
1337         else if (key == "enableProcessSwapOnWindowOpen")
1338             testOptions.contextOptions.enableProcessSwapOnWindowOpen = parseBooleanTestHeaderValue(value);
1339         else if (key == "enableColorFilter")
1340             testOptions.enableColorFilter = parseBooleanTestHeaderValue(value);
1341         else if (key == "punchOutWhiteBackgroundsInDarkMode")
1342             testOptions.punchOutWhiteBackgroundsInDarkMode = parseBooleanTestHeaderValue(value);
1343         else if (key == "jscOptions")
1344             testOptions.jscOptions = value;
1345         else if (key == "runSingly")
1346             testOptions.runSingly = parseBooleanTestHeaderValue(value);
1347         else if (key == "shouldIgnoreMetaViewport")
1348             testOptions.shouldIgnoreMetaViewport = parseBooleanTestHeaderValue(value);
1349         else if (key == "spellCheckingDots")
1350             testOptions.shouldShowSpellCheckingDots = parseBooleanTestHeaderValue(value);
1351         else if (key == "enableEditableImages")
1352             testOptions.enableEditableImages = parseBooleanTestHeaderValue(value);
1353         else if (key == "editable")
1354             testOptions.editable = parseBooleanTestHeaderValue(value);
1355         else if (key == "enableUndoManagerAPI")
1356             testOptions.enableUndoManagerAPI = parseBooleanTestHeaderValue(value);
1357         else if (key == "shouldHandleRunOpenPanel")
1358             testOptions.shouldHandleRunOpenPanel = parseBooleanTestHeaderValue(value);
1359         else if (key == "shouldPresentPopovers")
1360             testOptions.shouldPresentPopovers = parseBooleanTestHeaderValue(value);
1361         else if (key == "contentInset.top")
1362             testOptions.contentInsetTop = std::stod(value);
1363         else if (key == "ignoreSynchronousMessagingTimeouts")
1364             testOptions.contextOptions.ignoreSynchronousMessagingTimeouts = parseBooleanTestHeaderValue(value);
1365         pairStart = pairEnd + 1;
1366     }
1367 }
1368
1369 TestOptions TestController::testOptionsForTest(const TestCommand& command) const
1370 {
1371     TestOptions options(command.pathOrURL);
1372
1373     options.useRemoteLayerTree = m_shouldUseRemoteLayerTree;
1374     options.shouldShowWebView = m_shouldShowWebView;
1375
1376     updatePlatformSpecificTestOptionsForTest(options, command.pathOrURL);
1377     updateTestOptionsFromTestHeader(options, command.pathOrURL, command.absolutePath);
1378     platformAddTestOptions(options);
1379
1380     return options;
1381 }
1382
1383 void TestController::updateWebViewSizeForTest(const TestInvocation& test)
1384 {
1385     unsigned width = viewWidth;
1386     unsigned height = viewHeight;
1387     if (test.options().isSVGTest) {
1388         width = w3cSVGViewWidth;
1389         height = w3cSVGViewHeight;
1390     }
1391
1392     mainWebView()->resizeTo(width, height);
1393 }
1394
1395 void TestController::updateWindowScaleForTest(PlatformWebView* view, const TestInvocation& test)
1396 {
1397     view->changeWindowScaleIfNeeded(test.options().deviceScaleFactor);
1398 }
1399
1400 void TestController::configureViewForTest(const TestInvocation& test)
1401 {
1402     ensureViewSupportsOptionsForTest(test);
1403     updateWebViewSizeForTest(test);
1404     updateWindowScaleForTest(mainWebView(), test);
1405     configureContentExtensionForTest(test);
1406     platformConfigureViewForTest(test);
1407 }
1408
1409 #if ENABLE(CONTENT_EXTENSIONS) && !PLATFORM(COCOA)
1410 struct ContentExtensionStoreCallbackContext {
1411     explicit ContentExtensionStoreCallbackContext(TestController& controller)
1412         : testController(controller)
1413     {
1414     }
1415
1416     TestController& testController;
1417     uint32_t status { kWKUserContentExtensionStoreSuccess };
1418     WKRetainPtr<WKUserContentFilterRef> filter;
1419     bool done { false };
1420 };
1421
1422 static void contentExtensionStoreCallback(WKUserContentFilterRef filter, uint32_t status, void* userData)
1423 {
1424     auto* context = static_cast<ContentExtensionStoreCallbackContext*>(userData);
1425     context->status = status;
1426     context->filter = filter ? adoptWK(filter) : nullptr;
1427     context->done = true;
1428     context->testController.notifyDone();
1429 }
1430
1431 static std::string contentExtensionJSONPath(WKURLRef url)
1432 {
1433     auto path = testPath(url);
1434     if (path.length())
1435         return path + ".json";
1436
1437     auto p = adoptWK(WKURLCopyPath(url));
1438     auto buffer = std::vector<char>(WKStringGetMaximumUTF8CStringSize(p.get()));
1439     const auto length = WKStringGetUTF8CString(p.get(), buffer.data(), buffer.size());
1440     return std::string("LayoutTests/http/tests") + std::string(buffer.data(), length - 1) + ".json";
1441 }
1442 #endif
1443
1444 #if !PLATFORM(COCOA)
1445 #if ENABLE(CONTENT_EXTENSIONS)
1446 void TestController::configureContentExtensionForTest(const TestInvocation& test)
1447 {
1448     const char* contentExtensionsPath = libraryPathForTesting();
1449     if (!contentExtensionsPath)
1450         contentExtensionsPath = "/tmp/wktr-contentextensions";
1451
1452     if (!test.urlContains("contentextensions/")) {
1453         WKPageSetUserContentExtensionsEnabled(m_mainWebView->page(), false);
1454         return;
1455     }
1456
1457     std::string jsonFilePath(contentExtensionJSONPath(test.url()));
1458     std::ifstream jsonFile(jsonFilePath);
1459     if (!jsonFile.good()) {
1460         WTFLogAlways("Could not open file '%s'", jsonFilePath.c_str());
1461         return;
1462     }
1463
1464     std::string jsonFileContents {std::istreambuf_iterator<char>(jsonFile), std::istreambuf_iterator<char>()};
1465     auto jsonSource = adoptWK(WKStringCreateWithUTF8CString(jsonFileContents.c_str()));
1466
1467     auto storePath = adoptWK(WKStringCreateWithUTF8CString(contentExtensionsPath));
1468     auto extensionStore = adoptWK(WKUserContentExtensionStoreCreate(storePath.get()));
1469     ASSERT(extensionStore);
1470
1471     auto filterIdentifier = adoptWK(WKStringCreateWithUTF8CString("TestContentExtension"));
1472
1473     ContentExtensionStoreCallbackContext context(*this);
1474     WKUserContentExtensionStoreCompile(extensionStore.get(), filterIdentifier.get(), jsonSource.get(), &context, contentExtensionStoreCallback);
1475     runUntil(context.done, noTimeout);
1476     ASSERT(context.status == kWKUserContentExtensionStoreSuccess);
1477     ASSERT(context.filter);
1478
1479     WKPageSetUserContentExtensionsEnabled(mainWebView()->page(), true);
1480     WKUserContentControllerAddUserContentFilter(userContentController(), context.filter.get());
1481 }
1482
1483 void TestController::resetContentExtensions()
1484 {
1485     if (!mainWebView())
1486         return;
1487
1488     WKPageSetUserContentExtensionsEnabled(mainWebView()->page(), false);
1489
1490     const char* contentExtensionsPath = libraryPathForTesting();
1491     if (!contentExtensionsPath)
1492         return;
1493
1494     WKUserContentControllerRemoveAllUserContentFilters(userContentController());
1495
1496     auto storePath = adoptWK(WKStringCreateWithUTF8CString(contentExtensionsPath));
1497     auto extensionStore = adoptWK(WKUserContentExtensionStoreCreate(storePath.get()));
1498     ASSERT(extensionStore);
1499
1500     auto filterIdentifier = adoptWK(WKStringCreateWithUTF8CString("TestContentExtension"));
1501
1502     ContentExtensionStoreCallbackContext context(*this);
1503     WKUserContentExtensionStoreRemove(extensionStore.get(), filterIdentifier.get(), &context, contentExtensionStoreCallback);
1504     runUntil(context.done, noTimeout);
1505     ASSERT(!context.filter);
1506 }
1507 #else // ENABLE(CONTENT_EXTENSIONS)
1508 void TestController::configureContentExtensionForTest(const TestInvocation&)
1509 {
1510 }
1511
1512 void TestController::resetContentExtensions()
1513 {
1514 }
1515 #endif // ENABLE(CONTENT_EXTENSIONS)
1516 #endif // !PLATFORM(COCOA)
1517
1518 class CommandTokenizer {
1519 public:
1520     explicit CommandTokenizer(const std::string& input)
1521         : m_input(input)
1522         , m_posNextSeparator(0)
1523     {
1524         pump();
1525     }
1526
1527     bool hasNext() const;
1528     std::string next();
1529
1530 private:
1531     void pump();
1532     static const char kSeparator = '\'';
1533     const std::string& m_input;
1534     std::string m_next;
1535     size_t m_posNextSeparator;
1536 };
1537
1538 void CommandTokenizer::pump()
1539 {
1540     if (m_posNextSeparator == std::string::npos || m_posNextSeparator == m_input.size()) {
1541         m_next = std::string();
1542         return;
1543     }
1544     size_t start = m_posNextSeparator ? m_posNextSeparator + 1 : 0;
1545     m_posNextSeparator = m_input.find(kSeparator, start);
1546     size_t size = m_posNextSeparator == std::string::npos ? std::string::npos : m_posNextSeparator - start;
1547     m_next = std::string(m_input, start, size);
1548 }
1549
1550 std::string CommandTokenizer::next()
1551 {
1552     ASSERT(hasNext());
1553
1554     std::string oldNext = m_next;
1555     pump();
1556     return oldNext;
1557 }
1558
1559 bool CommandTokenizer::hasNext() const
1560 {
1561     return !m_next.empty();
1562 }
1563
1564 NO_RETURN static void die(const std::string& inputLine)
1565 {
1566     fprintf(stderr, "Unexpected input line: %s\n", inputLine.c_str());
1567     exit(1);
1568 }
1569
1570 static TestCommand parseInputLine(const std::string& inputLine)
1571 {
1572     TestCommand result;
1573     CommandTokenizer tokenizer(inputLine);
1574     if (!tokenizer.hasNext())
1575         die(inputLine);
1576
1577     std::string arg = tokenizer.next();
1578     result.pathOrURL = arg;
1579     while (tokenizer.hasNext()) {
1580         arg = tokenizer.next();
1581         if (arg == std::string("--timeout")) {
1582             std::string timeoutToken = tokenizer.next();
1583             result.timeout = Seconds::fromMilliseconds(atoi(timeoutToken.c_str()));
1584         } else if (arg == std::string("-p") || arg == std::string("--pixel-test")) {
1585             result.shouldDumpPixels = true;
1586             if (tokenizer.hasNext())
1587                 result.expectedPixelHash = tokenizer.next();
1588         } else if (arg == std::string("--dump-jsconsolelog-in-stderr"))
1589             result.dumpJSConsoleLogInStdErr = true;
1590         else if (arg == std::string("--absolutePath"))
1591             result.absolutePath = tokenizer.next();
1592         else
1593             die(inputLine);
1594     }
1595     return result;
1596 }
1597
1598 bool TestController::runTest(const char* inputLine)
1599 {
1600     AutodrainedPool pool;
1601     
1602     WKTextCheckerSetTestingMode(true);
1603     TestCommand command = parseInputLine(std::string(inputLine));
1604
1605     m_state = RunningTest;
1606     
1607     TestOptions options = testOptionsForTest(command);
1608
1609     WKRetainPtr<WKURLRef> wkURL(AdoptWK, createTestURL(command.pathOrURL.c_str()));
1610     m_currentInvocation = std::make_unique<TestInvocation>(wkURL.get(), options);
1611
1612     if (command.shouldDumpPixels || m_shouldDumpPixelsForAllTests)
1613         m_currentInvocation->setIsPixelTest(command.expectedPixelHash);
1614
1615     if (command.timeout > 0_s)
1616         m_currentInvocation->setCustomTimeout(command.timeout);
1617
1618     m_currentInvocation->setDumpJSConsoleLogInStdErr(command.dumpJSConsoleLogInStdErr || options.dumpJSConsoleLogInStdErr);
1619
1620     platformWillRunTest(*m_currentInvocation);
1621
1622     m_currentInvocation->invoke();
1623     m_currentInvocation = nullptr;
1624
1625     return true;
1626 }
1627
1628 bool TestController::waitForCompletion(const WTF::Function<void ()>& function, WTF::Seconds timeout)
1629 {
1630     m_doneResetting = false;
1631     function();
1632     runUntil(m_doneResetting, timeout);
1633     return !m_doneResetting;
1634 }
1635
1636 bool TestController::handleControlCommand(const char* command)
1637 {
1638     if (!strncmp("#CHECK FOR WORLD LEAKS", command, 22)) {
1639         if (m_checkForWorldLeaks)
1640             findAndDumpWorldLeaks();
1641         else
1642             WTFLogAlways("WebKitTestRunner asked to check for world leaks, but was not run with --world-leaks");
1643         return true;
1644     }
1645
1646     if (!strncmp("#LIST CHILD PROCESSES", command, 21)) {
1647         findAndDumpWebKitProcessIdentifiers();
1648         return true;
1649     }
1650
1651     return false;
1652 }
1653
1654 void TestController::runTestingServerLoop()
1655 {
1656     char filenameBuffer[2048];
1657     while (fgets(filenameBuffer, sizeof(filenameBuffer), stdin)) {
1658         char* newLineCharacter = strchr(filenameBuffer, '\n');
1659         if (newLineCharacter)
1660             *newLineCharacter = '\0';
1661
1662         if (strlen(filenameBuffer) == 0)
1663             continue;
1664
1665         if (handleControlCommand(filenameBuffer))
1666             continue;
1667
1668         if (!runTest(filenameBuffer))
1669             break;
1670     }
1671 }
1672
1673 void TestController::run()
1674 {
1675     if (m_usingServerMode)
1676         runTestingServerLoop();
1677     else {
1678         for (size_t i = 0; i < m_paths.size(); ++i) {
1679             if (!runTest(m_paths[i].c_str()))
1680                 break;
1681         }
1682         if (m_checkForWorldLeaks)
1683             findAndDumpWorldLeaks();
1684     }
1685 }
1686
1687 void TestController::runUntil(bool& done, WTF::Seconds timeout)
1688 {
1689     if (m_forceNoTimeout)
1690         timeout = noTimeout;
1691
1692     platformRunUntil(done, timeout);
1693 }
1694
1695 // WKContextInjectedBundleClient
1696
1697 void TestController::didReceiveMessageFromInjectedBundle(WKContextRef context, WKStringRef messageName, WKTypeRef messageBody, const void* clientInfo)
1698 {
1699     static_cast<TestController*>(const_cast<void*>(clientInfo))->didReceiveMessageFromInjectedBundle(messageName, messageBody);
1700 }
1701
1702 void TestController::didReceiveSynchronousMessageFromInjectedBundle(WKContextRef context, WKStringRef messageName, WKTypeRef messageBody, WKTypeRef* returnData, const void* clientInfo)
1703 {
1704     *returnData = static_cast<TestController*>(const_cast<void*>(clientInfo))->didReceiveSynchronousMessageFromInjectedBundle(messageName, messageBody).leakRef();
1705 }
1706
1707 WKTypeRef TestController::getInjectedBundleInitializationUserData(WKContextRef, const void* clientInfo)
1708 {
1709     return static_cast<TestController*>(const_cast<void*>(clientInfo))->getInjectedBundleInitializationUserData().leakRef();
1710 }
1711
1712 // WKPageInjectedBundleClient
1713
1714 void TestController::didReceivePageMessageFromInjectedBundle(WKPageRef page, WKStringRef messageName, WKTypeRef messageBody, const void* clientInfo)
1715 {
1716     static_cast<TestController*>(const_cast<void*>(clientInfo))->didReceiveMessageFromInjectedBundle(messageName, messageBody);
1717 }
1718
1719 void TestController::didReceiveSynchronousPageMessageFromInjectedBundle(WKPageRef page, WKStringRef messageName, WKTypeRef messageBody, WKTypeRef* returnData, const void* clientInfo)
1720 {
1721     *returnData = static_cast<TestController*>(const_cast<void*>(clientInfo))->didReceiveSynchronousMessageFromInjectedBundle(messageName, messageBody).leakRef();
1722 }
1723
1724 void TestController::networkProcessDidCrash(WKContextRef context, const void *clientInfo)
1725 {
1726     static_cast<TestController*>(const_cast<void*>(clientInfo))->networkProcessDidCrash();
1727 }
1728
1729 void TestController::didReceiveKeyDownMessageFromInjectedBundle(WKDictionaryRef messageBodyDictionary, bool synchronous)
1730 {
1731     WKRetainPtr<WKStringRef> keyKey = adoptWK(WKStringCreateWithUTF8CString("Key"));
1732     WKStringRef key = static_cast<WKStringRef>(WKDictionaryGetItemForKey(messageBodyDictionary, keyKey.get()));
1733
1734     WKRetainPtr<WKStringRef> modifiersKey = adoptWK(WKStringCreateWithUTF8CString("Modifiers"));
1735     WKEventModifiers modifiers = static_cast<WKEventModifiers>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, modifiersKey.get()))));
1736
1737     WKRetainPtr<WKStringRef> locationKey = adoptWK(WKStringCreateWithUTF8CString("Location"));
1738     unsigned location = static_cast<unsigned>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, locationKey.get()))));
1739
1740     m_eventSenderProxy->keyDown(key, modifiers, location);
1741 }
1742
1743 void TestController::didReceiveLiveDocumentsList(WKArrayRef liveDocumentList)
1744 {
1745     auto numDocuments = WKArrayGetSize(liveDocumentList);
1746
1747     HashMap<uint64_t, String> documentInfo;
1748     for (size_t i = 0; i < numDocuments; ++i) {
1749         WKTypeRef item = WKArrayGetItemAtIndex(liveDocumentList, i);
1750         if (item && WKGetTypeID(item) == WKDictionaryGetTypeID()) {
1751             WKDictionaryRef liveDocumentItem = static_cast<WKDictionaryRef>(item);
1752
1753             WKRetainPtr<WKStringRef> idKey(AdoptWK, WKStringCreateWithUTF8CString("id"));
1754             WKUInt64Ref documentID = static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(liveDocumentItem, idKey.get()));
1755
1756             WKRetainPtr<WKStringRef> urlKey(AdoptWK, WKStringCreateWithUTF8CString("url"));
1757             WKStringRef documentURL = static_cast<WKStringRef>(WKDictionaryGetItemForKey(liveDocumentItem, urlKey.get()));
1758
1759             documentInfo.add(WKUInt64GetValue(documentID), toWTFString(documentURL));
1760         }
1761     }
1762
1763     if (!documentInfo.size()) {
1764         m_abandonedDocumentInfo.clear();
1765         return;
1766     }
1767
1768     // Remove any documents which are no longer live.
1769     m_abandonedDocumentInfo.removeIf([&](auto& keyAndValue) {
1770         return !documentInfo.contains(keyAndValue.key);
1771     });
1772     
1773     // Add newly abandoned documents.
1774     String currentTestURL = m_currentInvocation ? toWTFString(adoptWK(WKURLCopyString(m_currentInvocation->url()))) : "no test";
1775     for (const auto& it : documentInfo)
1776         m_abandonedDocumentInfo.add(it.key, AbandonedDocumentInfo(currentTestURL, it.value));
1777 }
1778
1779 void TestController::didReceiveMessageFromInjectedBundle(WKStringRef messageName, WKTypeRef messageBody)
1780 {
1781     if (WKStringIsEqualToUTF8CString(messageName, "LiveDocuments")) {
1782         ASSERT(WKGetTypeID(messageBody) == WKArrayGetTypeID());
1783         didReceiveLiveDocumentsList(static_cast<WKArrayRef>(messageBody));
1784         AsyncTask::currentTask()->taskComplete();
1785         return;
1786     }
1787
1788     if (WKStringIsEqualToUTF8CString(messageName, "EventSender")) {
1789         if (m_state != RunningTest)
1790             return;
1791
1792         ASSERT(WKGetTypeID(messageBody) == WKDictionaryGetTypeID());
1793         WKDictionaryRef messageBodyDictionary = static_cast<WKDictionaryRef>(messageBody);
1794
1795         WKRetainPtr<WKStringRef> subMessageKey(AdoptWK, WKStringCreateWithUTF8CString("SubMessage"));
1796         WKStringRef subMessageName = static_cast<WKStringRef>(WKDictionaryGetItemForKey(messageBodyDictionary, subMessageKey.get()));
1797
1798         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseDown") || WKStringIsEqualToUTF8CString(subMessageName, "MouseUp")) {
1799             WKRetainPtr<WKStringRef> buttonKey = adoptWK(WKStringCreateWithUTF8CString("Button"));
1800             unsigned button = static_cast<unsigned>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, buttonKey.get()))));
1801
1802             WKRetainPtr<WKStringRef> modifiersKey = adoptWK(WKStringCreateWithUTF8CString("Modifiers"));
1803             WKEventModifiers modifiers = static_cast<WKEventModifiers>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, modifiersKey.get()))));
1804
1805             // Forward to WebProcess
1806             if (WKStringIsEqualToUTF8CString(subMessageName, "MouseDown"))
1807                 m_eventSenderProxy->mouseDown(button, modifiers);
1808             else
1809                 m_eventSenderProxy->mouseUp(button, modifiers);
1810
1811             return;
1812         }
1813
1814         if (WKStringIsEqualToUTF8CString(subMessageName, "KeyDown")) {
1815             didReceiveKeyDownMessageFromInjectedBundle(messageBodyDictionary, false);
1816             return;
1817         }
1818
1819         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseScrollBy")) {
1820             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
1821             double x = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get())));
1822
1823             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
1824             double y = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get())));
1825
1826             // Forward to WebProcess
1827             m_eventSenderProxy->mouseScrollBy(x, y);
1828             return;
1829         }
1830
1831         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseScrollByWithWheelAndMomentumPhases")) {
1832             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
1833             double x = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get())));
1834             
1835             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
1836             double y = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get())));
1837             
1838             WKRetainPtr<WKStringRef> phaseKey = adoptWK(WKStringCreateWithUTF8CString("Phase"));
1839             int phase = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, phaseKey.get()))));
1840             WKRetainPtr<WKStringRef> momentumKey = adoptWK(WKStringCreateWithUTF8CString("Momentum"));
1841             int momentum = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, momentumKey.get()))));
1842             
1843             // Forward to WebProcess
1844             m_eventSenderProxy->mouseScrollByWithWheelAndMomentumPhases(x, y, phase, momentum);
1845
1846             return;
1847         }
1848
1849         ASSERT_NOT_REACHED();
1850     }
1851
1852     if (!m_currentInvocation)
1853         return;
1854
1855     m_currentInvocation->didReceiveMessageFromInjectedBundle(messageName, messageBody);
1856 }
1857
1858 WKRetainPtr<WKTypeRef> TestController::didReceiveSynchronousMessageFromInjectedBundle(WKStringRef messageName, WKTypeRef messageBody)
1859 {
1860     if (WKStringIsEqualToUTF8CString(messageName, "EventSender")) {
1861         if (m_state != RunningTest)
1862             return nullptr;
1863
1864         ASSERT(WKGetTypeID(messageBody) == WKDictionaryGetTypeID());
1865         WKDictionaryRef messageBodyDictionary = static_cast<WKDictionaryRef>(messageBody);
1866
1867         WKRetainPtr<WKStringRef> subMessageKey(AdoptWK, WKStringCreateWithUTF8CString("SubMessage"));
1868         WKStringRef subMessageName = static_cast<WKStringRef>(WKDictionaryGetItemForKey(messageBodyDictionary, subMessageKey.get()));
1869
1870         if (WKStringIsEqualToUTF8CString(subMessageName, "KeyDown")) {
1871             didReceiveKeyDownMessageFromInjectedBundle(messageBodyDictionary, true);
1872
1873             return 0;
1874         }
1875
1876         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseDown") || WKStringIsEqualToUTF8CString(subMessageName, "MouseUp")) {
1877             WKRetainPtr<WKStringRef> buttonKey = adoptWK(WKStringCreateWithUTF8CString("Button"));
1878             unsigned button = static_cast<unsigned>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, buttonKey.get()))));
1879
1880             WKRetainPtr<WKStringRef> modifiersKey = adoptWK(WKStringCreateWithUTF8CString("Modifiers"));
1881             WKEventModifiers modifiers = static_cast<WKEventModifiers>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, modifiersKey.get()))));
1882
1883             // Forward to WebProcess
1884             if (WKStringIsEqualToUTF8CString(subMessageName, "MouseDown"))
1885                 m_eventSenderProxy->mouseDown(button, modifiers);
1886             else
1887                 m_eventSenderProxy->mouseUp(button, modifiers);
1888             return 0;
1889         }
1890
1891         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseMoveTo")) {
1892             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
1893             double x = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get())));
1894
1895             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
1896             double y = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get())));
1897
1898             // Forward to WebProcess
1899             m_eventSenderProxy->mouseMoveTo(x, y);
1900             return 0;
1901         }
1902
1903 #if PLATFORM(MAC)
1904         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseForceClick")) {
1905             m_eventSenderProxy->mouseForceClick();
1906             return 0;
1907         }
1908
1909         if (WKStringIsEqualToUTF8CString(subMessageName, "StartAndCancelMouseForceClick")) {
1910             m_eventSenderProxy->startAndCancelMouseForceClick();
1911             return 0;
1912         }
1913
1914         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseForceDown")) {
1915             m_eventSenderProxy->mouseForceDown();
1916             return 0;
1917         }
1918
1919         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseForceUp")) {
1920             m_eventSenderProxy->mouseForceUp();
1921             return 0;
1922         }
1923
1924         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseForceChanged")) {
1925             WKRetainPtr<WKStringRef> forceKey = adoptWK(WKStringCreateWithUTF8CString("Force"));
1926             double force = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, forceKey.get())));
1927
1928             m_eventSenderProxy->mouseForceChanged(force);
1929             return 0;
1930         }
1931 #endif // PLATFORM(MAC)
1932
1933         if (WKStringIsEqualToUTF8CString(subMessageName, "ContinuousMouseScrollBy")) {
1934             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
1935             double x = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get())));
1936
1937             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
1938             double y = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get())));
1939
1940             WKRetainPtr<WKStringRef> pagedKey = adoptWK(WKStringCreateWithUTF8CString("Paged"));
1941             bool paged = static_cast<bool>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, pagedKey.get()))));
1942
1943             // Forward to WebProcess
1944             m_eventSenderProxy->continuousMouseScrollBy(x, y, paged);
1945             return 0;
1946         }
1947
1948         if (WKStringIsEqualToUTF8CString(subMessageName, "LeapForward")) {
1949             WKRetainPtr<WKStringRef> timeKey = adoptWK(WKStringCreateWithUTF8CString("TimeInMilliseconds"));
1950             unsigned time = static_cast<unsigned>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, timeKey.get()))));
1951
1952             m_eventSenderProxy->leapForward(time);
1953             return 0;
1954         }
1955
1956 #if ENABLE(TOUCH_EVENTS)
1957         if (WKStringIsEqualToUTF8CString(subMessageName, "AddTouchPoint")) {
1958             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
1959             int x = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get()))));
1960
1961             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
1962             int y = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get()))));
1963
1964             m_eventSenderProxy->addTouchPoint(x, y);
1965             return 0;
1966         }
1967
1968         if (WKStringIsEqualToUTF8CString(subMessageName, "UpdateTouchPoint")) {
1969             WKRetainPtr<WKStringRef> indexKey = adoptWK(WKStringCreateWithUTF8CString("Index"));
1970             int index = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, indexKey.get()))));
1971
1972             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
1973             int x = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get()))));
1974
1975             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
1976             int y = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get()))));
1977
1978             m_eventSenderProxy->updateTouchPoint(index, x, y);
1979             return 0;
1980         }
1981
1982         if (WKStringIsEqualToUTF8CString(subMessageName, "SetTouchModifier")) {
1983             WKRetainPtr<WKStringRef> modifierKey = adoptWK(WKStringCreateWithUTF8CString("Modifier"));
1984             WKEventModifiers modifier = static_cast<WKEventModifiers>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, modifierKey.get()))));
1985
1986             WKRetainPtr<WKStringRef> enableKey = adoptWK(WKStringCreateWithUTF8CString("Enable"));
1987             bool enable = static_cast<bool>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, enableKey.get()))));
1988
1989             m_eventSenderProxy->setTouchModifier(modifier, enable);
1990             return 0;
1991         }
1992
1993         if (WKStringIsEqualToUTF8CString(subMessageName, "SetTouchPointRadius")) {
1994             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("RadiusX"));
1995             int x = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get()))));
1996
1997             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("RadiusY"));
1998             int y = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get()))));
1999
2000             m_eventSenderProxy->setTouchPointRadius(x, y);
2001             return 0;
2002         }
2003
2004         if (WKStringIsEqualToUTF8CString(subMessageName, "TouchStart")) {
2005             m_eventSenderProxy->touchStart();
2006             return 0;
2007         }
2008
2009         if (WKStringIsEqualToUTF8CString(subMessageName, "TouchMove")) {
2010             m_eventSenderProxy->touchMove();
2011             return 0;
2012         }
2013
2014         if (WKStringIsEqualToUTF8CString(subMessageName, "TouchEnd")) {
2015             m_eventSenderProxy->touchEnd();
2016             return 0;
2017         }
2018
2019         if (WKStringIsEqualToUTF8CString(subMessageName, "TouchCancel")) {
2020             m_eventSenderProxy->touchCancel();
2021             return 0;
2022         }
2023
2024         if (WKStringIsEqualToUTF8CString(subMessageName, "ClearTouchPoints")) {
2025             m_eventSenderProxy->clearTouchPoints();
2026             return 0;
2027         }
2028
2029         if (WKStringIsEqualToUTF8CString(subMessageName, "ReleaseTouchPoint")) {
2030             WKRetainPtr<WKStringRef> indexKey = adoptWK(WKStringCreateWithUTF8CString("Index"));
2031             int index = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, indexKey.get()))));
2032             m_eventSenderProxy->releaseTouchPoint(index);
2033             return 0;
2034         }
2035
2036         if (WKStringIsEqualToUTF8CString(subMessageName, "CancelTouchPoint")) {
2037             WKRetainPtr<WKStringRef> indexKey = adoptWK(WKStringCreateWithUTF8CString("Index"));
2038             int index = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, indexKey.get()))));
2039             m_eventSenderProxy->cancelTouchPoint(index);
2040             return 0;
2041         }
2042 #endif
2043         ASSERT_NOT_REACHED();
2044     }
2045     return m_currentInvocation->didReceiveSynchronousMessageFromInjectedBundle(messageName, messageBody);
2046 }
2047
2048 WKRetainPtr<WKTypeRef> TestController::getInjectedBundleInitializationUserData()
2049 {
2050     return nullptr;
2051 }
2052
2053 // WKContextClient
2054
2055 void TestController::networkProcessDidCrash()
2056 {
2057     pid_t pid = WKContextGetNetworkProcessIdentifier(m_context.get());
2058     fprintf(stderr, "#CRASHED - %s (pid %ld)\n", networkProcessName(), static_cast<long>(pid));
2059     exit(1);
2060 }
2061
2062 // WKPageNavigationClient
2063
2064 void TestController::didCommitNavigation(WKPageRef page, WKNavigationRef navigation, WKTypeRef, const void* clientInfo)
2065 {
2066     static_cast<TestController*>(const_cast<void*>(clientInfo))->didCommitNavigation(page, navigation);
2067 }
2068
2069 void TestController::didFinishNavigation(WKPageRef page, WKNavigationRef navigation, WKTypeRef, const void* clientInfo)
2070 {
2071     static_cast<TestController*>(const_cast<void*>(clientInfo))->didFinishNavigation(page, navigation);
2072 }
2073
2074 void TestController::didReceiveServerRedirectForProvisionalNavigation(WKPageRef page, WKNavigationRef navigation, WKTypeRef userData, const void* clientInfo)
2075 {
2076     static_cast<TestController*>(const_cast<void*>(clientInfo))->didReceiveServerRedirectForProvisionalNavigation(page, navigation, userData);
2077 }
2078
2079 bool TestController::canAuthenticateAgainstProtectionSpace(WKPageRef page, WKProtectionSpaceRef protectionSpace, const void* clientInfo)
2080 {
2081     return static_cast<TestController*>(const_cast<void*>(clientInfo))->canAuthenticateAgainstProtectionSpace(page, protectionSpace);
2082 }
2083
2084 void TestController::didReceiveAuthenticationChallenge(WKPageRef page, WKAuthenticationChallengeRef authenticationChallenge, const void *clientInfo)
2085 {
2086     static_cast<TestController*>(const_cast<void*>(clientInfo))->didReceiveAuthenticationChallenge(page, /*frame,*/ authenticationChallenge);
2087 }
2088
2089 void TestController::processDidCrash(WKPageRef page, const void* clientInfo)
2090 {
2091     static_cast<TestController*>(const_cast<void*>(clientInfo))->processDidCrash();
2092 }
2093
2094 void TestController::didBeginNavigationGesture(WKPageRef page, const void *clientInfo)
2095 {
2096     static_cast<TestController*>(const_cast<void*>(clientInfo))->didBeginNavigationGesture(page);
2097 }
2098
2099 void TestController::willEndNavigationGesture(WKPageRef page, WKBackForwardListItemRef backForwardListItem, const void *clientInfo)
2100 {
2101     static_cast<TestController*>(const_cast<void*>(clientInfo))->willEndNavigationGesture(page, backForwardListItem);
2102 }
2103
2104 void TestController::didEndNavigationGesture(WKPageRef page, WKBackForwardListItemRef backForwardListItem, const void *clientInfo)
2105 {
2106     static_cast<TestController*>(const_cast<void*>(clientInfo))->didEndNavigationGesture(page, backForwardListItem);
2107 }
2108
2109 void TestController::didRemoveNavigationGestureSnapshot(WKPageRef page, const void *clientInfo)
2110 {
2111     static_cast<TestController*>(const_cast<void*>(clientInfo))->didRemoveNavigationGestureSnapshot(page);
2112 }
2113
2114 WKPluginLoadPolicy TestController::decidePolicyForPluginLoad(WKPageRef page, WKPluginLoadPolicy currentPluginLoadPolicy, WKDictionaryRef pluginInformation, WKStringRef* unavailabilityDescription, const void* clientInfo)
2115 {
2116     return static_cast<TestController*>(const_cast<void*>(clientInfo))->decidePolicyForPluginLoad(page, currentPluginLoadPolicy, pluginInformation, unavailabilityDescription);
2117 }
2118
2119 WKPluginLoadPolicy TestController::decidePolicyForPluginLoad(WKPageRef, WKPluginLoadPolicy currentPluginLoadPolicy, WKDictionaryRef pluginInformation, WKStringRef* unavailabilityDescription)
2120 {
2121     if (m_shouldBlockAllPlugins)
2122         return kWKPluginLoadPolicyBlocked;
2123
2124 #if PLATFORM(MAC)
2125     WKStringRef bundleIdentifier = (WKStringRef)WKDictionaryGetItemForKey(pluginInformation, WKPluginInformationBundleIdentifierKey());
2126     if (!bundleIdentifier)
2127         return currentPluginLoadPolicy;
2128
2129     if (WKStringIsEqualToUTF8CString(bundleIdentifier, "com.apple.QuickTime Plugin.plugin"))
2130         return currentPluginLoadPolicy;
2131
2132     if (WKStringIsEqualToUTF8CString(bundleIdentifier, "com.apple.testnetscapeplugin"))
2133         return currentPluginLoadPolicy;
2134
2135     RELEASE_ASSERT_NOT_REACHED(); // Please don't use any other plug-ins in tests, as they will not be installed on all machines.
2136 #else
2137     return currentPluginLoadPolicy;
2138 #endif
2139 }
2140
2141 void TestController::setBlockAllPlugins(bool shouldBlock)
2142 {
2143     m_shouldBlockAllPlugins = shouldBlock;
2144
2145 #if PLATFORM(MAC)
2146     auto policy = shouldBlock ? kWKPluginLoadClientPolicyBlock : kWKPluginLoadClientPolicyAllow;
2147
2148     WKRetainPtr<WKStringRef> nameNetscape = adoptWK(WKStringCreateWithUTF8CString("com.apple.testnetscapeplugin"));
2149     WKRetainPtr<WKStringRef> nameFlash = adoptWK(WKStringCreateWithUTF8CString("com.macromedia.Flash Player.plugin"));
2150     WKRetainPtr<WKStringRef> emptyString = adoptWK(WKStringCreateWithUTF8CString(""));
2151     WKContextSetPluginLoadClientPolicy(m_context.get(), policy, emptyString.get(), nameNetscape.get(), emptyString.get());
2152     WKContextSetPluginLoadClientPolicy(m_context.get(), policy, emptyString.get(), nameFlash.get(), emptyString.get());
2153 #endif
2154 }
2155
2156 void TestController::setPluginSupportedMode(const String& mode)
2157 {
2158     if (m_unsupportedPluginMode == mode)
2159         return;
2160
2161     m_unsupportedPluginMode = mode;
2162     if (m_unsupportedPluginMode.isEmpty()) {
2163         WKContextClearSupportedPlugins(m_context.get());
2164         return;
2165     }
2166
2167     WKRetainPtr<WKMutableArrayRef> emptyArray = adoptWK(WKMutableArrayCreate());
2168     WKRetainPtr<WKStringRef> allOrigins = adoptWK(WKStringCreateWithUTF8CString(""));
2169     WKRetainPtr<WKStringRef> specificOrigin = adoptWK(WKStringCreateWithUTF8CString("localhost"));
2170
2171     WKRetainPtr<WKStringRef> pdfName = adoptWK(WKStringCreateWithUTF8CString("My personal PDF"));
2172     WKContextAddSupportedPlugin(m_context.get(), allOrigins.get(), pdfName.get(), emptyArray.get(), emptyArray.get());
2173
2174     WKRetainPtr<WKStringRef> nameNetscape = adoptWK(WKStringCreateWithUTF8CString("com.apple.testnetscapeplugin"));
2175     WKRetainPtr<WKStringRef> mimeTypeNetscape = adoptWK(WKStringCreateWithUTF8CString("application/x-webkit-test-netscape"));
2176     WKRetainPtr<WKMutableArrayRef> mimeTypesNetscape = adoptWK(WKMutableArrayCreate());
2177     WKArrayAppendItem(mimeTypesNetscape.get(), mimeTypeNetscape.get());
2178
2179     WKRetainPtr<WKStringRef> namePdf = adoptWK(WKStringCreateWithUTF8CString("WebKit built-in PDF"));
2180
2181     if (m_unsupportedPluginMode == "allOrigins") {
2182         WKContextAddSupportedPlugin(m_context.get(), allOrigins.get(), nameNetscape.get(), mimeTypesNetscape.get(), emptyArray.get());
2183         WKContextAddSupportedPlugin(m_context.get(), allOrigins.get(), namePdf.get(), emptyArray.get(), emptyArray.get());
2184         return;
2185     }
2186
2187     if (m_unsupportedPluginMode == "specificOrigin") {
2188         WKContextAddSupportedPlugin(m_context.get(), specificOrigin.get(), nameNetscape.get(), mimeTypesNetscape.get(), emptyArray.get());
2189         WKContextAddSupportedPlugin(m_context.get(), specificOrigin.get(), namePdf.get(), emptyArray.get(), emptyArray.get());
2190         return;
2191     }
2192 }
2193
2194 void TestController::didCommitNavigation(WKPageRef page, WKNavigationRef navigation)
2195 {
2196     mainWebView()->focus();
2197 }
2198
2199 void TestController::didReceiveServerRedirectForProvisionalNavigation(WKPageRef page, WKNavigationRef navigation, WKTypeRef userData)
2200 {
2201     m_didReceiveServerRedirectForProvisionalNavigation = true;
2202     return;
2203 }
2204
2205 static const char* toString(WKProtectionSpaceAuthenticationScheme scheme)
2206 {
2207     switch (scheme) {
2208     case kWKProtectionSpaceAuthenticationSchemeDefault:
2209         return "ProtectionSpaceAuthenticationSchemeDefault";
2210     case kWKProtectionSpaceAuthenticationSchemeHTTPBasic:
2211         return "ProtectionSpaceAuthenticationSchemeHTTPBasic";
2212     case kWKProtectionSpaceAuthenticationSchemeHTMLForm:
2213         return "ProtectionSpaceAuthenticationSchemeHTMLForm";
2214     case kWKProtectionSpaceAuthenticationSchemeNTLM:
2215         return "ProtectionSpaceAuthenticationSchemeNTLM";
2216     case kWKProtectionSpaceAuthenticationSchemeNegotiate:
2217         return "ProtectionSpaceAuthenticationSchemeNegotiate";
2218     case kWKProtectionSpaceAuthenticationSchemeClientCertificateRequested:
2219         return "ProtectionSpaceAuthenticationSchemeClientCertificateRequested";
2220     case kWKProtectionSpaceAuthenticationSchemeServerTrustEvaluationRequested:
2221         return "ProtectionSpaceAuthenticationSchemeServerTrustEvaluationRequested";
2222     case kWKProtectionSpaceAuthenticationSchemeOAuth:
2223         return "ProtectionSpaceAuthenticationSchemeOAuth";
2224     case kWKProtectionSpaceAuthenticationSchemeUnknown:
2225         return "ProtectionSpaceAuthenticationSchemeUnknown";
2226     }
2227     ASSERT_NOT_REACHED();
2228     return "ProtectionSpaceAuthenticationSchemeUnknown";
2229 }
2230
2231 bool TestController::canAuthenticateAgainstProtectionSpace(WKPageRef page, WKProtectionSpaceRef protectionSpace)
2232 {
2233     if (m_shouldLogCanAuthenticateAgainstProtectionSpace)
2234         m_currentInvocation->outputText("canAuthenticateAgainstProtectionSpace\n");
2235     WKProtectionSpaceAuthenticationScheme authenticationScheme = WKProtectionSpaceGetAuthenticationScheme(protectionSpace);
2236     
2237     if (authenticationScheme == kWKProtectionSpaceAuthenticationSchemeServerTrustEvaluationRequested) {
2238         std::string host = toSTD(adoptWK(WKProtectionSpaceCopyHost(protectionSpace)).get());
2239         return host == "localhost" || host == "127.0.0.1" || (m_allowAnyHTTPSCertificateForAllowedHosts && m_allowedHosts.find(host) != m_allowedHosts.end());
2240     }
2241     
2242     return authenticationScheme <= kWKProtectionSpaceAuthenticationSchemeHTTPDigest || authenticationScheme == kWKProtectionSpaceAuthenticationSchemeOAuth;
2243 }
2244
2245 void TestController::didFinishNavigation(WKPageRef page, WKNavigationRef navigation)
2246 {
2247     if (m_state != Resetting)
2248         return;
2249
2250     WKRetainPtr<WKURLRef> wkURL(AdoptWK, WKFrameCopyURL(WKPageGetMainFrame(page)));
2251     if (!WKURLIsEqual(wkURL.get(), blankURL()))
2252         return;
2253
2254     m_doneResetting = true;
2255     singleton().notifyDone();
2256 }
2257
2258 void TestController::didReceiveAuthenticationChallenge(WKPageRef page, WKAuthenticationChallengeRef authenticationChallenge)
2259 {
2260     WKProtectionSpaceRef protectionSpace = WKAuthenticationChallengeGetProtectionSpace(authenticationChallenge);
2261     WKAuthenticationDecisionListenerRef decisionListener = WKAuthenticationChallengeGetDecisionListener(authenticationChallenge);
2262     WKProtectionSpaceAuthenticationScheme authenticationScheme = WKProtectionSpaceGetAuthenticationScheme(protectionSpace);
2263
2264     if (authenticationScheme == kWKProtectionSpaceAuthenticationSchemeServerTrustEvaluationRequested) {
2265         // Any non-empty credential signals to accept the server trust. Since the cross-platform API
2266         // doesn't expose a way to create a credential from server trust, we use a password credential.
2267
2268         m_serverTrustEvaluationCallbackCallsCount++;
2269
2270         WKRetainPtr<WKCredentialRef> credential = adoptWK(WKCredentialCreate(toWK("accept server trust").get(), toWK("").get(), kWKCredentialPersistenceNone));
2271         WKAuthenticationDecisionListenerUseCredential(decisionListener, credential.get());
2272         return;
2273     }
2274
2275     if (m_rejectsProtectionSpaceAndContinueForAuthenticationChallenges) {
2276         m_currentInvocation->outputText("Simulating reject protection space and continue for authentication challenge\n");
2277         WKAuthenticationDecisionListenerRejectProtectionSpaceAndContinue(decisionListener);
2278         return;
2279     }
2280
2281     std::string host = toSTD(adoptWK(WKProtectionSpaceCopyHost(protectionSpace)).get());
2282     int port = WKProtectionSpaceGetPort(protectionSpace);
2283     String message = makeString(host.c_str(), ':', port, " - didReceiveAuthenticationChallenge - ", toString(authenticationScheme), " - ");
2284     if (!m_handlesAuthenticationChallenges)
2285         message.append("Simulating cancelled authentication sheet\n");
2286     else
2287         message.append("Responding with " + m_authenticationUsername + ":" + m_authenticationPassword + "\n");
2288     m_currentInvocation->outputText(message);
2289
2290     if (!m_handlesAuthenticationChallenges) {
2291         WKAuthenticationDecisionListenerUseCredential(decisionListener, 0);
2292         return;
2293     }
2294     WKRetainPtr<WKStringRef> username(AdoptWK, WKStringCreateWithUTF8CString(m_authenticationUsername.utf8().data()));
2295     WKRetainPtr<WKStringRef> password(AdoptWK, WKStringCreateWithUTF8CString(m_authenticationPassword.utf8().data()));
2296     WKRetainPtr<WKCredentialRef> credential(AdoptWK, WKCredentialCreate(username.get(), password.get(), kWKCredentialPersistenceForSession));
2297     WKAuthenticationDecisionListenerUseCredential(decisionListener, credential.get());
2298 }
2299
2300     
2301 // WKContextDownloadClient
2302
2303 void TestController::downloadDidStart(WKContextRef context, WKDownloadRef download, const void* clientInfo)
2304 {
2305     static_cast<TestController*>(const_cast<void*>(clientInfo))->downloadDidStart(context, download);
2306 }
2307     
2308 WKStringRef TestController::decideDestinationWithSuggestedFilename(WKContextRef context, WKDownloadRef download, WKStringRef filename, bool* allowOverwrite, const void* clientInfo)
2309 {
2310     return static_cast<TestController*>(const_cast<void*>(clientInfo))->decideDestinationWithSuggestedFilename(context, download, filename, allowOverwrite);
2311 }
2312
2313 void TestController::downloadDidFinish(WKContextRef context, WKDownloadRef download, const void* clientInfo)
2314 {
2315     static_cast<TestController*>(const_cast<void*>(clientInfo))->downloadDidFinish(context, download);
2316 }
2317
2318 void TestController::downloadDidFail(WKContextRef context, WKDownloadRef download, WKErrorRef error, const void* clientInfo)
2319 {
2320     static_cast<TestController*>(const_cast<void*>(clientInfo))->downloadDidFail(context, download, error);
2321 }
2322
2323 void TestController::downloadDidCancel(WKContextRef context, WKDownloadRef download, const void* clientInfo)
2324 {
2325     static_cast<TestController*>(const_cast<void*>(clientInfo))->downloadDidCancel(context, download);
2326 }
2327
2328 void TestController::downloadDidReceiveServerRedirectToURL(WKContextRef context, WKDownloadRef download, WKURLRef url, const void* clientInfo)
2329 {
2330     static_cast<TestController*>(const_cast<void*>(clientInfo))->downloadDidReceiveServerRedirectToURL(context, download, url);
2331 }
2332
2333 void TestController::downloadDidStart(WKContextRef context, WKDownloadRef download)
2334 {
2335     if (m_shouldLogDownloadCallbacks)
2336         m_currentInvocation->outputText("Download started.\n");
2337 }
2338
2339 WKStringRef TestController::decideDestinationWithSuggestedFilename(WKContextRef, WKDownloadRef, WKStringRef filename, bool*& allowOverwrite)
2340 {
2341     String suggestedFilename = toWTFString(filename);
2342
2343     if (m_shouldLogDownloadCallbacks) {
2344         StringBuilder builder;
2345         builder.append("Downloading URL with suggested filename \"");
2346         builder.append(suggestedFilename);
2347         builder.append("\"\n");
2348         m_currentInvocation->outputText(builder.toString());
2349     }
2350
2351     const char* dumpRenderTreeTemp = libraryPathForTesting();
2352     if (!dumpRenderTreeTemp)
2353         return nullptr;
2354
2355     *allowOverwrite = true;
2356     String temporaryFolder = String::fromUTF8(dumpRenderTreeTemp);
2357     if (suggestedFilename.isEmpty())
2358         suggestedFilename = "Unknown";
2359
2360     return toWK(temporaryFolder + "/" + suggestedFilename).leakRef();
2361 }
2362
2363 void TestController::downloadDidFinish(WKContextRef, WKDownloadRef)
2364 {
2365     if (m_shouldLogDownloadCallbacks)
2366         m_currentInvocation->outputText("Download completed.\n");
2367     m_currentInvocation->notifyDownloadDone();
2368 }
2369
2370 void TestController::downloadDidReceiveServerRedirectToURL(WKContextRef, WKDownloadRef, WKURLRef url)
2371 {
2372     if (m_shouldLogDownloadCallbacks) {
2373         StringBuilder builder;
2374         builder.appendLiteral("Download was redirected to \"");
2375         WKRetainPtr<WKStringRef> urlStringWK = adoptWK(WKURLCopyString(url));
2376         builder.append(toSTD(urlStringWK).c_str());
2377         builder.appendLiteral("\".\n");
2378         m_currentInvocation->outputText(builder.toString());
2379     }
2380 }
2381
2382 void TestController::downloadDidFail(WKContextRef, WKDownloadRef, WKErrorRef error)
2383 {
2384     if (m_shouldLogDownloadCallbacks) {
2385         m_currentInvocation->outputText("Download failed.\n"_s);
2386
2387         WKRetainPtr<WKStringRef> errorDomain = adoptWK(WKErrorCopyDomain(error));
2388         WKRetainPtr<WKStringRef> errorDescription = adoptWK(WKErrorCopyLocalizedDescription(error));
2389         int errorCode = WKErrorGetErrorCode(error);
2390
2391         StringBuilder errorBuilder;
2392         errorBuilder.append("Failed: ");
2393         errorBuilder.append(toWTFString(errorDomain));
2394         errorBuilder.append(", code=");
2395         errorBuilder.appendNumber(errorCode);
2396         errorBuilder.append(", description=");
2397         errorBuilder.append(toWTFString(errorDescription));
2398         errorBuilder.append("\n");
2399
2400         m_currentInvocation->outputText(errorBuilder.toString());
2401     }
2402     m_currentInvocation->notifyDownloadDone();
2403 }
2404
2405 void TestController::downloadDidCancel(WKContextRef, WKDownloadRef)
2406 {
2407     if (m_shouldLogDownloadCallbacks)
2408         m_currentInvocation->outputText("Download cancelled.\n");
2409     m_currentInvocation->notifyDownloadDone();
2410 }
2411
2412 void TestController::processDidCrash()
2413 {
2414     // This function can be called multiple times when crash logs are being saved on Windows, so
2415     // ensure we only print the crashed message once.
2416     if (!m_didPrintWebProcessCrashedMessage) {
2417         pid_t pid = WKPageGetProcessIdentifier(m_mainWebView->page());
2418         fprintf(stderr, "#CRASHED - %s (pid %ld)\n", webProcessName(), static_cast<long>(pid));
2419         fflush(stderr);
2420         m_didPrintWebProcessCrashedMessage = true;
2421     }
2422
2423     if (m_shouldExitWhenWebProcessCrashes)
2424         exit(1);
2425 }
2426
2427 void TestController::didBeginNavigationGesture(WKPageRef)
2428 {
2429     m_currentInvocation->didBeginSwipe();
2430 }
2431
2432 void TestController::willEndNavigationGesture(WKPageRef, WKBackForwardListItemRef)
2433 {
2434     m_currentInvocation->willEndSwipe();
2435 }
2436
2437 void TestController::didEndNavigationGesture(WKPageRef, WKBackForwardListItemRef)
2438 {
2439     m_currentInvocation->didEndSwipe();
2440 }
2441
2442 void TestController::didRemoveNavigationGestureSnapshot(WKPageRef)
2443 {
2444     m_currentInvocation->didRemoveSwipeSnapshot();
2445 }
2446
2447 void TestController::simulateWebNotificationClick(uint64_t notificationID)
2448 {
2449     m_webNotificationProvider.simulateWebNotificationClick(mainWebView()->page(), notificationID);
2450 }
2451
2452 void TestController::setGeolocationPermission(bool enabled)
2453 {
2454     m_isGeolocationPermissionSet = true;
2455     m_isGeolocationPermissionAllowed = enabled;
2456     decidePolicyForGeolocationPermissionRequestIfPossible();
2457 }
2458
2459 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)
2460 {
2461     m_geolocationProvider->setPosition(latitude, longitude, accuracy, providesAltitude, altitude, providesAltitudeAccuracy, altitudeAccuracy, providesHeading, heading, providesSpeed, speed, providesFloorLevel, floorLevel);
2462 }
2463
2464 void TestController::setMockGeolocationPositionUnavailableError(WKStringRef errorMessage)
2465 {
2466     m_geolocationProvider->setPositionUnavailableError(errorMessage);
2467 }
2468
2469 void TestController::handleGeolocationPermissionRequest(WKGeolocationPermissionRequestRef geolocationPermissionRequest)
2470 {
2471     m_geolocationPermissionRequests.append(geolocationPermissionRequest);
2472     decidePolicyForGeolocationPermissionRequestIfPossible();
2473 }
2474
2475 bool TestController::isGeolocationProviderActive() const
2476 {
2477     return m_geolocationProvider->isActive();
2478 }
2479
2480 static String originUserVisibleName(WKSecurityOriginRef origin)
2481 {
2482     if (!origin)
2483         return emptyString();
2484
2485     auto host = toWTFString(adoptWK(WKSecurityOriginCopyHost(origin)));
2486     auto protocol = toWTFString(adoptWK(WKSecurityOriginCopyProtocol(origin)));
2487
2488     if (host.isEmpty() || protocol.isEmpty())
2489         return emptyString();
2490
2491     if (int port = WKSecurityOriginGetPort(origin))
2492         return makeString(protocol, "://", host, ':', port);
2493
2494     return makeString(protocol, "://", host);
2495 }
2496
2497 static String userMediaOriginHash(WKSecurityOriginRef userMediaDocumentOrigin, WKSecurityOriginRef topLevelDocumentOrigin)
2498 {
2499     String userMediaDocumentOriginString = originUserVisibleName(userMediaDocumentOrigin);
2500     String topLevelDocumentOriginString = originUserVisibleName(topLevelDocumentOrigin);
2501
2502     if (topLevelDocumentOriginString.isEmpty())
2503         return userMediaDocumentOriginString;
2504
2505     return makeString(userMediaDocumentOriginString, '-', topLevelDocumentOriginString);
2506 }
2507
2508 static String userMediaOriginHash(WKStringRef userMediaDocumentOriginString, WKStringRef topLevelDocumentOriginString)
2509 {
2510     auto userMediaDocumentOrigin = adoptWK(WKSecurityOriginCreateFromString(userMediaDocumentOriginString));
2511     if (!WKStringGetLength(topLevelDocumentOriginString))
2512         return userMediaOriginHash(userMediaDocumentOrigin.get(), nullptr);
2513
2514     auto topLevelDocumentOrigin = adoptWK(WKSecurityOriginCreateFromString(topLevelDocumentOriginString));
2515     return userMediaOriginHash(userMediaDocumentOrigin.get(), topLevelDocumentOrigin.get());
2516 }
2517
2518 void TestController::setUserMediaPermission(bool enabled)
2519 {
2520     m_isUserMediaPermissionSet = true;
2521     m_isUserMediaPermissionAllowed = enabled;
2522     decidePolicyForUserMediaPermissionRequestIfPossible();
2523 }
2524
2525 void TestController::resetUserMediaPermission()
2526 {
2527     m_isUserMediaPermissionSet = false;
2528 }
2529
2530 void TestController::setShouldDismissJavaScriptAlertsAsynchronously(bool value)
2531 {
2532     m_shouldDismissJavaScriptAlertsAsynchronously = value;
2533 }
2534
2535 void TestController::handleJavaScriptAlert(WKPageRunJavaScriptAlertResultListenerRef listener)
2536 {
2537     if (!m_shouldDismissJavaScriptAlertsAsynchronously) {
2538         WKPageRunJavaScriptAlertResultListenerCall(listener);
2539         return;
2540     }
2541
2542     WKRetain(listener);
2543     callOnMainThread([listener] {
2544         WKPageRunJavaScriptAlertResultListenerCall(listener);
2545         WKRelease(listener);
2546     });
2547 }
2548
2549 class OriginSettings : public RefCounted<OriginSettings> {
2550 public:
2551     explicit OriginSettings()
2552     {
2553     }
2554
2555     bool persistentPermission() const { return m_persistentPermission; }
2556     void setPersistentPermission(bool permission) { m_persistentPermission = permission; }
2557
2558     String persistentSalt() const { return m_persistentSalt; }
2559     void setPersistentSalt(const String& salt) { m_persistentSalt = salt; }
2560
2561     HashMap<uint64_t, String>& ephemeralSalts() { return m_ephemeralSalts; }
2562
2563     void incrementRequestCount() { ++m_requestCount; }
2564     void resetRequestCount() { m_requestCount = 0; }
2565     unsigned requestCount() const { return m_requestCount; }
2566
2567 private:
2568     HashMap<uint64_t, String> m_ephemeralSalts;
2569     String m_persistentSalt;
2570     unsigned m_requestCount { 0 };
2571     bool m_persistentPermission { false };
2572 };
2573
2574 String TestController::saltForOrigin(WKFrameRef frame, String originHash)
2575 {
2576     auto& settings = settingsForOrigin(originHash);
2577     auto& ephemeralSalts = settings.ephemeralSalts();
2578     auto frameInfo = adoptWK(WKFrameCreateFrameInfo(frame));
2579     auto frameHandle = WKFrameInfoGetFrameHandleRef(frameInfo.get());
2580     uint64_t frameIdentifier = WKFrameHandleGetFrameID(frameHandle);
2581     String frameSalt = ephemeralSalts.get(frameIdentifier);
2582
2583     if (settings.persistentPermission()) {
2584         if (frameSalt.length())
2585             return frameSalt;
2586
2587         if (!settings.persistentSalt().length())
2588             settings.setPersistentSalt(createCanonicalUUIDString());
2589
2590         return settings.persistentSalt();
2591     }
2592
2593     if (!frameSalt.length()) {
2594         frameSalt = createCanonicalUUIDString();
2595         ephemeralSalts.add(frameIdentifier, frameSalt);
2596     }
2597
2598     return frameSalt;
2599 }
2600
2601 void TestController::setUserMediaPersistentPermissionForOrigin(bool permission, WKStringRef userMediaDocumentOriginString, WKStringRef topLevelDocumentOriginString)
2602 {
2603     auto originHash = userMediaOriginHash(userMediaDocumentOriginString, topLevelDocumentOriginString);
2604     auto& settings = settingsForOrigin(originHash);
2605     settings.setPersistentPermission(permission);
2606 }
2607
2608 void TestController::handleCheckOfUserMediaPermissionForOrigin(WKFrameRef frame, WKSecurityOriginRef userMediaDocumentOrigin, WKSecurityOriginRef topLevelDocumentOrigin, const WKUserMediaPermissionCheckRef& checkRequest)
2609 {
2610     auto originHash = userMediaOriginHash(userMediaDocumentOrigin, topLevelDocumentOrigin);
2611     auto salt = saltForOrigin(frame, originHash);
2612     WKRetainPtr<WKStringRef> saltString = adoptWK(WKStringCreateWithUTF8CString(salt.utf8().data()));
2613
2614     WKUserMediaPermissionCheckSetUserMediaAccessInfo(checkRequest, saltString.get(), settingsForOrigin(originHash).persistentPermission());
2615 }
2616
2617 bool TestController::handleDeviceOrientationAndMotionAccessRequest(WKSecurityOriginRef origin)
2618 {
2619     m_currentInvocation->outputText(makeString("Received device orientation & motion access request for security origin \"", originUserVisibleName(origin), "\".\n"));
2620     return m_shouldAllowDeviceOrientationAndMotionAccess;
2621 }
2622
2623 void TestController::handleUserMediaPermissionRequest(WKFrameRef frame, WKSecurityOriginRef userMediaDocumentOrigin, WKSecurityOriginRef topLevelDocumentOrigin, WKUserMediaPermissionRequestRef request)
2624 {
2625     auto originHash = userMediaOriginHash(userMediaDocumentOrigin, topLevelDocumentOrigin);
2626     m_userMediaPermissionRequests.append(std::make_pair(originHash, request));
2627     decidePolicyForUserMediaPermissionRequestIfPossible();
2628 }
2629
2630 OriginSettings& TestController::settingsForOrigin(const String& originHash)
2631 {
2632     RefPtr<OriginSettings> settings = m_cachedUserMediaPermissions.get(originHash);
2633     if (!settings) {
2634         settings = adoptRef(*new OriginSettings());
2635         m_cachedUserMediaPermissions.add(originHash, settings);
2636     }
2637
2638     return *settings;
2639 }
2640
2641 unsigned TestController::userMediaPermissionRequestCountForOrigin(WKStringRef userMediaDocumentOriginString, WKStringRef topLevelDocumentOriginString)
2642 {
2643     auto originHash = userMediaOriginHash(userMediaDocumentOriginString, topLevelDocumentOriginString);
2644     return settingsForOrigin(originHash).requestCount();
2645 }
2646
2647 void TestController::resetUserMediaPermissionRequestCountForOrigin(WKStringRef userMediaDocumentOriginString, WKStringRef topLevelDocumentOriginString)
2648 {
2649     auto originHash = userMediaOriginHash(userMediaDocumentOriginString, topLevelDocumentOriginString);
2650     settingsForOrigin(originHash).resetRequestCount();
2651 }
2652
2653 void TestController::decidePolicyForUserMediaPermissionRequestIfPossible()
2654 {
2655     if (!m_isUserMediaPermissionSet)
2656         return;
2657
2658     for (auto& pair : m_userMediaPermissionRequests) {
2659         auto originHash = pair.first;
2660         auto request = pair.second.get();
2661
2662         auto& settings = settingsForOrigin(originHash);
2663         settings.incrementRequestCount();
2664
2665         if (!m_isUserMediaPermissionAllowed && !settings.persistentPermission()) {
2666             WKUserMediaPermissionRequestDeny(request, kWKPermissionDenied);
2667             continue;
2668         }
2669
2670         WKRetainPtr<WKArrayRef> audioDeviceUIDs = adoptWK(WKUserMediaPermissionRequestAudioDeviceUIDs(request));
2671         WKRetainPtr<WKArrayRef> videoDeviceUIDs = adoptWK(WKUserMediaPermissionRequestVideoDeviceUIDs(request));
2672
2673         if (!WKArrayGetSize(videoDeviceUIDs.get()) && !WKArrayGetSize(audioDeviceUIDs.get())) {
2674             WKUserMediaPermissionRequestDeny(request, kWKNoConstraints);
2675             continue;
2676         }
2677
2678         WKRetainPtr<WKStringRef> videoDeviceUID;
2679         if (WKArrayGetSize(videoDeviceUIDs.get()))
2680             videoDeviceUID = reinterpret_cast<WKStringRef>(WKArrayGetItemAtIndex(videoDeviceUIDs.get(), 0));
2681         else
2682             videoDeviceUID = adoptWK(WKStringCreateWithUTF8CString(""));
2683
2684         WKRetainPtr<WKStringRef> audioDeviceUID;
2685         if (WKArrayGetSize(audioDeviceUIDs.get()))
2686             audioDeviceUID = reinterpret_cast<WKStringRef>(WKArrayGetItemAtIndex(audioDeviceUIDs.get(), 0));
2687         else
2688             audioDeviceUID = adoptWK(WKStringCreateWithUTF8CString(""));
2689
2690         WKUserMediaPermissionRequestAllow(request, audioDeviceUID.get(), videoDeviceUID.get());
2691     }
2692     m_userMediaPermissionRequests.clear();
2693 }
2694
2695 void TestController::setCustomPolicyDelegate(bool enabled, bool permissive)
2696 {
2697     m_policyDelegateEnabled = enabled;
2698     m_policyDelegatePermissive = permissive;
2699 }
2700
2701 void TestController::decidePolicyForGeolocationPermissionRequestIfPossible()
2702 {
2703     if (!m_isGeolocationPermissionSet)
2704         return;
2705
2706     for (size_t i = 0; i < m_geolocationPermissionRequests.size(); ++i) {
2707         WKGeolocationPermissionRequestRef permissionRequest = m_geolocationPermissionRequests[i].get();
2708         if (m_isGeolocationPermissionAllowed)
2709             WKGeolocationPermissionRequestAllow(permissionRequest);
2710         else
2711             WKGeolocationPermissionRequestDeny(permissionRequest);
2712     }
2713     m_geolocationPermissionRequests.clear();
2714 }
2715
2716 void TestController::decidePolicyForNotificationPermissionRequest(WKPageRef page, WKSecurityOriginRef origin, WKNotificationPermissionRequestRef request, const void*)
2717 {
2718     TestController::singleton().decidePolicyForNotificationPermissionRequest(page, origin, request);
2719 }
2720
2721 void TestController::decidePolicyForNotificationPermissionRequest(WKPageRef, WKSecurityOriginRef, WKNotificationPermissionRequestRef request)
2722 {
2723     WKNotificationPermissionRequestAllow(request);
2724 }
2725
2726 void TestController::unavailablePluginButtonClicked(WKPageRef, WKPluginUnavailabilityReason, WKDictionaryRef, const void*)
2727 {
2728     printf("MISSING PLUGIN BUTTON PRESSED\n");
2729 }
2730
2731 void TestController::decidePolicyForNavigationAction(WKPageRef, WKNavigationActionRef navigationAction, WKFramePolicyListenerRef listener, WKTypeRef, const void* clientInfo)
2732 {
2733     static_cast<TestController*>(const_cast<void*>(clientInfo))->decidePolicyForNavigationAction(navigationAction, listener);
2734 }
2735
2736 void TestController::decidePolicyForNavigationAction(WKNavigationActionRef navigationAction, WKFramePolicyListenerRef listener)
2737 {
2738     WKRetainPtr<WKFramePolicyListenerRef> retainedListener { listener };
2739     WKRetainPtr<WKNavigationActionRef> retainedNavigationAction { navigationAction };
2740     const bool shouldIgnore { m_policyDelegateEnabled && !m_policyDelegatePermissive };
2741     auto decisionFunction = [shouldIgnore, retainedListener, retainedNavigationAction]() {
2742         if (shouldIgnore)
2743             WKFramePolicyListenerIgnore(retainedListener.get());
2744         else if (WKNavigationActionShouldPerformDownload(retainedNavigationAction.get()))
2745             WKFramePolicyListenerDownload(retainedListener.get());
2746         else
2747             WKFramePolicyListenerUse(retainedListener.get());
2748     };
2749
2750     if (m_shouldDecideNavigationPolicyAfterDelay)
2751         RunLoop::main().dispatch(WTFMove(decisionFunction));
2752     else
2753         decisionFunction();
2754 }
2755
2756 void TestController::decidePolicyForNavigationResponse(WKPageRef, WKNavigationResponseRef navigationResponse, WKFramePolicyListenerRef listener, WKTypeRef, const void* clientInfo)
2757 {
2758     static_cast<TestController*>(const_cast<void*>(clientInfo))->decidePolicyForNavigationResponse(navigationResponse, listener);
2759 }
2760
2761 void TestController::decidePolicyForNavigationResponse(WKNavigationResponseRef navigationResponse, WKFramePolicyListenerRef listener)
2762 {
2763     WKRetainPtr<WKNavigationResponseRef> retainedNavigationResponse { navigationResponse };
2764     WKRetainPtr<WKFramePolicyListenerRef> retainedListener { listener };
2765
2766     bool shouldDownloadUndisplayableMIMETypes = m_shouldDownloadUndisplayableMIMETypes;
2767     auto decisionFunction = [shouldDownloadUndisplayableMIMETypes, retainedNavigationResponse, retainedListener]() {
2768         // Even though Response was already checked by WKBundlePagePolicyClient, the check did not include plugins
2769         // so we have to re-check again.
2770         if (WKNavigationResponseCanShowMIMEType(retainedNavigationResponse.get())) {
2771             WKFramePolicyListenerUse(retainedListener.get());
2772             return;
2773         }
2774
2775         if (shouldDownloadUndisplayableMIMETypes)
2776             WKFramePolicyListenerDownload(retainedListener.get());
2777         else
2778             WKFramePolicyListenerIgnore(retainedListener.get());
2779     };
2780
2781     if (m_shouldDecideResponsePolicyAfterDelay)
2782         RunLoop::main().dispatch(WTFMove(decisionFunction));
2783     else
2784         decisionFunction();
2785 }
2786
2787 void TestController::didNavigateWithNavigationData(WKContextRef, WKPageRef, WKNavigationDataRef navigationData, WKFrameRef frame, const void* clientInfo)
2788 {
2789     static_cast<TestController*>(const_cast<void*>(clientInfo))->didNavigateWithNavigationData(navigationData, frame);
2790 }
2791
2792 void TestController::didNavigateWithNavigationData(WKNavigationDataRef navigationData, WKFrameRef)
2793 {
2794     if (m_state != RunningTest)
2795         return;
2796
2797     if (!m_shouldLogHistoryClientCallbacks)
2798         return;
2799
2800     // URL
2801     auto url = adoptWK(WKNavigationDataCopyURL(navigationData));
2802     auto urlString = toWTFString(adoptWK(WKURLCopyString(url.get())));
2803     // Title
2804     auto title = toWTFString(adoptWK(WKNavigationDataCopyTitle(navigationData)));
2805     // HTTP method
2806     auto request = adoptWK(WKNavigationDataCopyOriginalRequest(navigationData));
2807     auto method = toWTFString(adoptWK(WKURLRequestCopyHTTPMethod(request.get())));
2808
2809     // FIXME: Determine whether the navigation was successful / a client redirect rather than hard-coding the message here.
2810     m_currentInvocation->outputText(makeString("WebView navigated to url \"", urlString, "\" with title \"", title, "\" with HTTP equivalent method \"", method,
2811         "\".  The navigation was successful and was not a client redirect.\n"));
2812 }
2813
2814 void TestController::didPerformClientRedirect(WKContextRef, WKPageRef, WKURLRef sourceURL, WKURLRef destinationURL, WKFrameRef frame, const void* clientInfo)
2815 {
2816     static_cast<TestController*>(const_cast<void*>(clientInfo))->didPerformClientRedirect(sourceURL, destinationURL, frame);
2817 }
2818
2819 void TestController::didPerformClientRedirect(WKURLRef sourceURL, WKURLRef destinationURL, WKFrameRef)
2820 {
2821     if (m_state != RunningTest)
2822         return;
2823
2824     if (!m_shouldLogHistoryClientCallbacks)
2825         return;
2826
2827     auto source = toWTFString(adoptWK(WKURLCopyString(sourceURL)));
2828     auto destination = toWTFString(adoptWK(WKURLCopyString(destinationURL)));
2829
2830     m_currentInvocation->outputText(makeString("WebView performed a client redirect from \"", source, "\" to \"", destination, "\".\n"));
2831 }
2832
2833 void TestController::didPerformServerRedirect(WKContextRef, WKPageRef, WKURLRef sourceURL, WKURLRef destinationURL, WKFrameRef frame, const void* clientInfo)
2834 {
2835     static_cast<TestController*>(const_cast<void*>(clientInfo))->didPerformServerRedirect(sourceURL, destinationURL, frame);
2836 }
2837
2838 void TestController::didPerformServerRedirect(WKURLRef sourceURL, WKURLRef destinationURL, WKFrameRef)
2839 {
2840     if (m_state != RunningTest)
2841         return;
2842
2843     if (!m_shouldLogHistoryClientCallbacks)
2844         return;
2845
2846     auto source = toWTFString(adoptWK(WKURLCopyString(sourceURL)));
2847     auto destination = toWTFString(adoptWK(WKURLCopyString(destinationURL)));
2848
2849     m_currentInvocation->outputText(makeString("WebView performed a server redirect from \"", source, "\" to \"", destination, "\".\n"));
2850 }
2851
2852 void TestController::didUpdateHistoryTitle(WKContextRef, WKPageRef, WKStringRef title, WKURLRef URL, WKFrameRef frame, const void* clientInfo)
2853 {
2854     static_cast<TestController*>(const_cast<void*>(clientInfo))->didUpdateHistoryTitle(title, URL, frame);
2855 }
2856
2857 void TestController::didUpdateHistoryTitle(WKStringRef title, WKURLRef URL, WKFrameRef)
2858 {
2859     if (m_state != RunningTest)
2860         return;
2861
2862     if (!m_shouldLogHistoryClientCallbacks)
2863         return;
2864
2865     auto urlString = toWTFString(adoptWK(WKURLCopyString(URL)));
2866     m_currentInvocation->outputText(makeString("WebView updated the title for history URL \"", urlString, "\" to \"", toWTFString(title), "\".\n"));
2867 }
2868
2869 void TestController::setNavigationGesturesEnabled(bool value)
2870 {
2871     m_mainWebView->setNavigationGesturesEnabled(value);
2872 }
2873
2874 void TestController::setIgnoresViewportScaleLimits(bool ignoresViewportScaleLimits)
2875 {
2876     WKPageSetIgnoresViewportScaleLimits(m_mainWebView->page(), ignoresViewportScaleLimits);
2877 }
2878
2879 void TestController::terminateNetworkProcess()
2880 {
2881     WKContextTerminateNetworkProcess(platformContext());
2882 }
2883
2884 void TestController::terminateServiceWorkerProcess()
2885 {
2886     WKContextTerminateServiceWorkerProcess(platformContext());
2887 }
2888
2889 #if !PLATFORM(COCOA)
2890 void TestController::platformWillRunTest(const TestInvocation&)
2891 {
2892 }
2893
2894 void TestController::platformCreateWebView(WKPageConfigurationRef configuration, const TestOptions& options)
2895 {
2896     m_mainWebView = std::make_unique<PlatformWebView>(configuration, options);
2897 }
2898
2899 PlatformWebView* TestController::platformCreateOtherPage(PlatformWebView* parentView, WKPageConfigurationRef configuration, const TestOptions& options)
2900 {
2901     return new PlatformWebView(configuration, options);
2902 }
2903
2904 WKContextRef TestController::platformAdjustContext(WKContextRef context, WKContextConfigurationRef contextConfiguration)
2905 {
2906     auto* dataStore = WKContextGetWebsiteDataStore(context);
2907     WKWebsiteDataStoreSetResourceLoadStatisticsEnabled(dataStore, true);
2908
2909     if (const char* dumpRenderTreeTemp = libraryPathForTesting()) {
2910         String temporaryFolder = String::fromUTF8(dumpRenderTreeTemp);
2911
2912         WKWebsiteDataStoreSetServiceWorkerRegistrationDirectory(dataStore, toWK(temporaryFolder + pathSeparator + "ServiceWorkers").get());
2913     }
2914
2915     return context;
2916 }
2917
2918 void TestController::platformResetStateToConsistentValues(const TestOptions&)
2919 {
2920 }
2921
2922 unsigned TestController::imageCountInGeneralPasteboard() const
2923 {
2924     return 0;
2925 }
2926
2927 void TestController::removeAllSessionCredentials()
2928 {
2929 }
2930
2931 void TestController::getAllStorageAccessEntries()
2932 {
2933 }
2934
2935 #endif
2936
2937 struct ClearServiceWorkerRegistrationsCallbackContext {
2938     explicit ClearServiceWorkerRegistrationsCallbackContext(TestController& controller)
2939         : testController(controller)
2940     {
2941     }
2942
2943     TestController& testController;
2944     bool done { false };
2945 };
2946
2947 static void clearServiceWorkerRegistrationsCallback(void* userData)
2948 {
2949     auto* context = static_cast<ClearServiceWorkerRegistrationsCallbackContext*>(userData);
2950     context->done = true;
2951     context->testController.notifyDone();
2952 }
2953
2954 void TestController::clearServiceWorkerRegistrations()
2955 {
2956     auto websiteDataStore = WKContextGetWebsiteDataStore(platformContext());
2957     ClearServiceWorkerRegistrationsCallbackContext context(*this);
2958
2959     WKWebsiteDataStoreRemoveAllServiceWorkerRegistrations(websiteDataStore, &context, clearServiceWorkerRegistrationsCallback);
2960     runUntil(context.done, noTimeout);
2961 }
2962
2963 struct ClearDOMCacheCallbackContext {
2964     explicit ClearDOMCacheCallbackContext(TestController& controller)
2965         : testController(controller)
2966     {
2967     }
2968
2969     TestController& testController;
2970     bool done { false };
2971 };
2972
2973 static void clearDOMCacheCallback(void* userData)
2974 {
2975     auto* context = static_cast<ClearDOMCacheCallbackContext*>(userData);
2976     context->done = true;
2977     context->testController.notifyDone();
2978 }
2979
2980 void TestController::clearDOMCache(WKStringRef origin)
2981 {
2982     auto websiteDataStore = WKContextGetWebsiteDataStore(platformContext());
2983     ClearDOMCacheCallbackContext context(*this);
2984
2985     auto cacheOrigin = adoptWK(WKSecurityOriginCreateFromString(origin));
2986     WKWebsiteDataStoreRemoveFetchCacheForOrigin(websiteDataStore, cacheOrigin.get(), &context, clearDOMCacheCallback);
2987     runUntil(context.done, noTimeout);
2988 }
2989
2990 void TestController::clearDOMCaches()
2991 {
2992     auto websiteDataStore = WKContextGetWebsiteDataStore(platformContext());
2993     ClearDOMCacheCallbackContext context(*this);
2994
2995     WKWebsiteDataStoreRemoveAllFetchCaches(websiteDataStore, &context, clearDOMCacheCallback);
2996     runUntil(context.done, noTimeout);
2997 }
2998
2999 void TestController::setIDBPerOriginQuota(uint64_t quota)
3000 {
3001     WKContextSetIDBPerOriginQuota(platformContext(), quota);
3002 }
3003
3004 struct RemoveAllIndexedDatabasesCallbackContext {
3005     explicit RemoveAllIndexedDatabasesCallbackContext(TestController& controller)
3006         : testController(controller)
3007     {
3008     }
3009
3010     TestController& testController;
3011     bool done { false };
3012 };
3013
3014 static void RemoveAllIndexedDatabasesCallback(void* userData)
3015 {
3016     auto* context = static_cast<RemoveAllIndexedDatabasesCallbackContext*>(userData);
3017     context->done = true;
3018     context->testController.notifyDone();
3019 }
3020
3021 void TestController::ClearIndexedDatabases()
3022 {
3023     auto websiteDataStore = WKContextGetWebsiteDataStore(platformContext());
3024     RemoveAllIndexedDatabasesCallbackContext context(*this);
3025     WKWebsiteDataStoreRemoveAllIndexedDatabases(websiteDataStore, &context, RemoveAllIndexedDatabasesCallback);
3026     runUntil(context.done, noTimeout);
3027 }
3028
3029 struct FetchCacheOriginsCallbackContext {
3030     FetchCacheOriginsCallbackContext(TestController& controller, WKStringRef origin)
3031         : testController(controller)
3032         , origin(origin)
3033     {
3034     }
3035
3036     TestController& testController;
3037     WKStringRef origin;
3038
3039     bool done { false };
3040     bool result { false };
3041 };
3042
3043 static void fetchCacheOriginsCallback(WKArrayRef origins, void* userData)
3044 {
3045     auto* context = static_cast<FetchCacheOriginsCallbackContext*>(userData);
3046     context->done = true;
3047
3048     auto size = WKArrayGetSize(origins);
3049     for (size_t index = 0; index < size && !context->result; ++index) {
3050         WKSecurityOriginRef securityOrigin = reinterpret_cast<WKSecurityOriginRef>(WKArrayGetItemAtIndex(origins, index));
3051         if (WKStringIsEqual(context->origin, adoptWK(WKSecurityOriginCopyToString(securityOrigin)).get()))
3052             context->result = true;
3053     }
3054     context->testController.notifyDone();
3055 }
3056
3057 bool TestController::hasDOMCache(WKStringRef origin)
3058 {
3059     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3060     FetchCacheOriginsCallbackContext context(*this, origin);
3061     WKWebsiteDataStoreGetFetchCacheOrigins(dataStore, &context, fetchCacheOriginsCallback);
3062     runUntil(context.done, noTimeout);
3063     return context.result;
3064 }
3065
3066 struct FetchCacheSizeForOriginCallbackContext {
3067     explicit FetchCacheSizeForOriginCallbackContext(TestController& controller)
3068         : testController(controller)
3069     {
3070     }
3071
3072     TestController& testController;
3073
3074     bool done { false };
3075     uint64_t result { 0 };
3076 };
3077
3078 static void fetchCacheSizeForOriginCallback(uint64_t size, void* userData)
3079 {
3080     auto* context = static_cast<FetchCacheSizeForOriginCallbackContext*>(userData);
3081     context->done = true;
3082     context->result = size;
3083     context->testController.notifyDone();
3084 }
3085
3086 uint64_t TestController::domCacheSize(WKStringRef origin)
3087 {
3088     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3089     FetchCacheSizeForOriginCallbackContext context(*this);
3090     WKWebsiteDataStoreGetFetchCacheSizeForOrigin(dataStore, origin, &context, fetchCacheSizeForOriginCallback);
3091     runUntil(context.done, noTimeout);
3092     return context.result;
3093 }
3094
3095 #if !PLATFORM(COCOA)
3096 void TestController::setAllowStorageQuotaIncrease(bool)
3097 {
3098     // FIXME: To implement.
3099 }
3100
3101 bool TestController::isDoingMediaCapture() const
3102 {
3103     return false;
3104 }
3105
3106 #endif
3107
3108 struct ResourceStatisticsCallbackContext {
3109     explicit ResourceStatisticsCallbackContext(TestController& controller)
3110         : testController(controller)
3111     {
3112     }
3113
3114     TestController& testController;
3115     bool done { false };
3116     bool result { false };
3117     WKRetainPtr<WKStringRef> resourceLoadStatisticsRepresentation;
3118 };
3119     
3120 static void resourceStatisticsStringResultCallback(WKStringRef resourceLoadStatisticsRepresentation, void* userData)
3121 {
3122     auto* context = static_cast<ResourceStatisticsCallbackContext*>(userData);
3123     context->resourceLoadStatisticsRepresentation = resourceLoadStatisticsRepresentation;
3124     context->done = true;
3125     context->testController.notifyDone();
3126 }
3127
3128 static void resourceStatisticsVoidResultCallback(void* userData)
3129 {
3130     auto* context = static_cast<ResourceStatisticsCallbackContext*>(userData);
3131     context->done = true;
3132     context->testController.notifyDone();
3133 }
3134
3135 static void resourceStatisticsBooleanResultCallback(bool result, void* userData)
3136 {
3137     auto* context = static_cast<ResourceStatisticsCallbackContext*>(userData);
3138     context->result = result;
3139     context->done = true;
3140     context->testController.notifyDone();
3141 }
3142
3143 void TestController::setStatisticsDebugMode(bool value)
3144 {
3145     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3146     ResourceStatisticsCallbackContext context(*this);
3147     WKWebsiteDataStoreSetResourceLoadStatisticsDebugModeWithCompletionHandler(dataStore, value, &context, resourceStatisticsVoidResultCallback);
3148     runUntil(context.done, noTimeout);
3149     m_currentInvocation->didSetStatisticsDebugMode();
3150 }
3151
3152 void TestController::setStatisticsPrevalentResourceForDebugMode(WKStringRef hostName)
3153 {
3154     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3155     ResourceStatisticsCallbackContext context(*this);
3156     WKWebsiteDataStoreSetResourceLoadStatisticsPrevalentResourceForDebugMode(dataStore, hostName, &context, resourceStatisticsVoidResultCallback);
3157     runUntil(context.done, noTimeout);
3158     m_currentInvocation->didSetPrevalentResourceForDebugMode();
3159 }
3160
3161 void TestController::setStatisticsLastSeen(WKStringRef host, double seconds)
3162 {
3163     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3164     ResourceStatisticsCallbackContext context(*this);
3165     WKWebsiteDataStoreSetStatisticsLastSeen(dataStore, host, seconds, &context, resourceStatisticsVoidResultCallback);
3166     runUntil(context.done, noTimeout);
3167     m_currentInvocation->didSetLastSeen();
3168 }
3169
3170 void TestController::setStatisticsPrevalentResource(WKStringRef host, bool value)
3171 {
3172     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3173     ResourceStatisticsCallbackContext context(*this);
3174     WKWebsiteDataStoreSetStatisticsPrevalentResource(dataStore, host, value, &context, resourceStatisticsVoidResultCallback);
3175     runUntil(context.done, noTimeout);
3176     m_currentInvocation->didSetPrevalentResource();
3177 }
3178
3179 void TestController::setStatisticsVeryPrevalentResource(WKStringRef host, bool value)
3180 {
3181     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3182     ResourceStatisticsCallbackContext context(*this);
3183     WKWebsiteDataStoreSetStatisticsVeryPrevalentResource(dataStore, host, value, &context, resourceStatisticsVoidResultCallback);
3184     runUntil(context.done, noTimeout);
3185     m_currentInvocation->didSetVeryPrevalentResource();
3186 }
3187     
3188 String TestController::dumpResourceLoadStatistics()
3189 {
3190     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3191     ResourceStatisticsCallbackContext context(*this);
3192     WKWebsiteDataStoreDumpResourceLoadStatistics(dataStore, &context, resourceStatisticsStringResultCallback);
3193     runUntil(context.done, noTimeout);
3194     return toWTFString(context.resourceLoadStatisticsRepresentation.get());
3195 }
3196
3197 bool TestController::isStatisticsPrevalentResource(WKStringRef host)
3198 {
3199     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3200     ResourceStatisticsCallbackContext context(*this);
3201     WKWebsiteDataStoreIsStatisticsPrevalentResource(dataStore, host, &context, resourceStatisticsBooleanResultCallback);
3202     runUntil(context.done, noTimeout);
3203     return context.result;
3204 }
3205
3206 bool TestController::isStatisticsVeryPrevalentResource(WKStringRef host)
3207 {
3208     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3209     ResourceStatisticsCallbackContext context(*this);
3210     WKWebsiteDataStoreIsStatisticsVeryPrevalentResource(dataStore, host, &context, resourceStatisticsBooleanResultCallback);
3211     runUntil(context.done, noTimeout);
3212     return context.result;
3213 }
3214
3215 bool TestController::isStatisticsRegisteredAsSubresourceUnder(WKStringRef subresourceHost, WKStringRef topFrameHost)
3216 {
3217     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3218     ResourceStatisticsCallbackContext context(*this);
3219     WKWebsiteDataStoreIsStatisticsRegisteredAsSubresourceUnder(dataStore, subresourceHost, topFrameHost, &context, resourceStatisticsBooleanResultCallback);
3220     runUntil(context.done, noTimeout);
3221     return context.result;
3222 }
3223
3224 bool TestController::isStatisticsRegisteredAsSubFrameUnder(WKStringRef subFrameHost, WKStringRef topFrameHost)
3225 {
3226     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3227     ResourceStatisticsCallbackContext context(*this);
3228     WKWebsiteDataStoreIsStatisticsRegisteredAsSubFrameUnder(dataStore, subFrameHost, topFrameHost, &context, resourceStatisticsBooleanResultCallback);
3229     runUntil(context.done, noTimeout);
3230     return context.result;
3231 }
3232
3233 bool TestController::isStatisticsRegisteredAsRedirectingTo(WKStringRef hostRedirectedFrom, WKStringRef hostRedirectedTo)
3234 {
3235     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3236     ResourceStatisticsCallbackContext context(*this);
3237     WKWebsiteDataStoreIsStatisticsRegisteredAsRedirectingTo(dataStore, hostRedirectedFrom, hostRedirectedTo, &context, resourceStatisticsBooleanResultCallback);
3238     runUntil(context.done, noTimeout);
3239     return context.result;
3240 }
3241
3242 void TestController::setStatisticsHasHadUserInteraction(WKStringRef host, bool value)
3243 {
3244     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3245     ResourceStatisticsCallbackContext context(*this);
3246     WKWebsiteDataStoreSetStatisticsHasHadUserInteraction(dataStore, host, value, &context, resourceStatisticsVoidResultCallback);
3247     runUntil(context.done, noTimeout);
3248     m_currentInvocation->didSetHasHadUserInteraction();
3249 }
3250
3251 bool TestController::isStatisticsHasHadUserInteraction(WKStringRef host)
3252 {
3253     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3254     ResourceStatisticsCallbackContext context(*this);
3255     WKWebsiteDataStoreIsStatisticsHasHadUserInteraction(dataStore, host, &context, resourceStatisticsBooleanResultCallback);
3256     runUntil(context.done, noTimeout);
3257     return context.result;
3258 }
3259
3260 void TestController::setStatisticsGrandfathered(WKStringRef host, bool value)
3261 {
3262     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3263     WKWebsiteDataStoreSetStatisticsGrandfathered(dataStore, host, value);
3264 }
3265
3266 bool TestController::isStatisticsGrandfathered(WKStringRef host)
3267 {
3268     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3269     ResourceStatisticsCallbackContext context(*this);
3270     WKWebsiteDataStoreIsStatisticsGrandfathered(dataStore, host, &context, resourceStatisticsBooleanResultCallback);
3271     runUntil(context.done, noTimeout);
3272     return context.result;
3273 }
3274
3275 void TestController::setStatisticsSubframeUnderTopFrameOrigin(WKStringRef host, WKStringRef topFrameHost)
3276 {
3277     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3278     WKWebsiteDataStoreSetStatisticsSubframeUnderTopFrameOrigin(dataStore, host, topFrameHost);
3279 }
3280
3281 void TestController::setStatisticsSubresourceUnderTopFrameOrigin(WKStringRef host, WKStringRef topFrameHost)
3282 {
3283     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3284     WKWebsiteDataStoreSetStatisticsSubresourceUnderTopFrameOrigin(dataStore, host, topFrameHost);
3285 }
3286
3287 void TestController::setStatisticsSubresourceUniqueRedirectTo(WKStringRef host, WKStringRef hostRedirectedTo)
3288 {
3289     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3290     WKWebsiteDataStoreSetStatisticsSubresourceUniqueRedirectTo(dataStore, host, hostRedirectedTo);
3291 }
3292
3293 void TestController::setStatisticsSubresourceUniqueRedirectFrom(WKStringRef host, WKStringRef hostRedirectedFrom)
3294 {
3295     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3296     WKWebsiteDataStoreSetStatisticsSubresourceUniqueRedirectFrom(dataStore, host, hostRedirectedFrom);
3297 }
3298
3299 void TestController::setStatisticsTopFrameUniqueRedirectTo(WKStringRef host, WKStringRef hostRedirectedTo)
3300 {
3301     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3302     WKWebsiteDataStoreSetStatisticsTopFrameUniqueRedirectTo(dataStore, host, hostRedirectedTo);
3303 }
3304
3305 void TestController::setStatisticsTopFrameUniqueRedirectFrom(WKStringRef host, WKStringRef hostRedirectedFrom)
3306 {
3307     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3308     WKWebsiteDataStoreSetStatisticsTopFrameUniqueRedirectFrom(dataStore, host, hostRedirectedFrom);
3309 }
3310
3311 void TestController::setStatisticsCrossSiteLoadWithLinkDecoration(WKStringRef fromHost, WKStringRef toHost)
3312 {
3313     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3314     ResourceStatisticsCallbackContext context(*this);
3315     WKWebsiteDataStoreSetStatisticsCrossSiteLoadWithLinkDecoration(dataStore, fromHost, toHost, &context, resourceStatisticsVoidResultCallback);
3316     runUntil(context.done, noTimeout);
3317 }
3318
3319 void TestController::setStatisticsTimeToLiveUserInteraction(double seconds)
3320 {
3321     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3322     ResourceStatisticsCallbackContext context(*this);
3323     WKWebsiteDataStoreSetStatisticsTimeToLiveUserInteraction(dataStore, seconds, &context, resourceStatisticsVoidResultCallback);
3324     runUntil(context.done, noTimeout);
3325 }
3326
3327 void TestController::statisticsProcessStatisticsAndDataRecords()
3328 {
3329     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3330     ResourceStatisticsCallbackContext context(*this);
3331     WKWebsiteDataStoreStatisticsProcessStatisticsAndDataRecords(dataStore, &context, resourceStatisticsVoidResultCallback);
3332     runUntil(context.done, noTimeout);
3333 }
3334
3335 void TestController::statisticsUpdateCookieBlocking()
3336 {
3337     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3338     ResourceStatisticsCallbackContext context(*this);
3339     WKWebsiteDataStoreStatisticsUpdateCookieBlocking(dataStore, &context, resourceStatisticsVoidResultCallback);
3340     runUntil(context.done, noTimeout);
3341     m_currentInvocation->didSetBlockCookiesForHost();
3342 }
3343
3344 void TestController::statisticsSubmitTelemetry()
3345 {
3346     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3347     WKWebsiteDataStoreStatisticsSubmitTelemetry(dataStore);
3348 }
3349
3350 void TestController::setStatisticsNotifyPagesWhenDataRecordsWereScanned(bool value)
3351 {
3352     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3353     WKWebsiteDataStoreSetStatisticsNotifyPagesWhenDataRecordsWereScanned(dataStore, value);
3354 }
3355
3356 void TestController::setStatisticsIsRunningTest(bool value)
3357 {
3358     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3359     ResourceStatisticsCallbackContext context(*this);
3360     WKWebsiteDataStoreSetStatisticsIsRunningTest(dataStore, value, &context, resourceStatisticsVoidResultCallback);
3361     runUntil(context.done, noTimeout);
3362 }
3363
3364 void TestController::setStatisticsShouldClassifyResourcesBeforeDataRecordsRemoval(bool value)
3365 {
3366     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3367     WKWebsiteDataStoreSetStatisticsShouldClassifyResourcesBeforeDataRecordsRemoval(dataStore, value);
3368 }
3369
3370 void TestController::setStatisticsNotifyPagesWhenTelemetryWasCaptured(bool value)
3371 {
3372     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3373     WKWebsiteDataStoreSetStatisticsNotifyPagesWhenTelemetryWasCaptured(dataStore, value);
3374 }
3375
3376 void TestController::setStatisticsMinimumTimeBetweenDataRecordsRemoval(double seconds)
3377 {
3378     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3379     WKWebsiteDataStoreSetStatisticsMinimumTimeBetweenDataRecordsRemoval(dataStore, seconds);
3380 }
3381
3382 void TestController::setStatisticsGrandfatheringTime(double seconds)
3383 {
3384     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3385     WKWebsiteDataStoreSetStatisticsGrandfatheringTime(dataStore, seconds);
3386 }
3387
3388 void TestController::setStatisticsMaxStatisticsEntries(unsigned entries)
3389 {
3390     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3391     WKWebsiteDataStoreSetStatisticsMaxStatisticsEntries(dataStore, entries);
3392 }
3393
3394 void TestController::setStatisticsPruneEntriesDownTo(unsigned entries)
3395 {
3396     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3397     WKWebsiteDataStoreSetStatisticsPruneEntriesDownTo(dataStore, entries);
3398 }
3399
3400 void TestController::statisticsClearInMemoryAndPersistentStore()
3401 {
3402     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3403     ResourceStatisticsCallbackContext context(*this);
3404     WKWebsiteDataStoreStatisticsClearInMemoryAndPersistentStore(dataStore, &context, resourceStatisticsVoidResultCallback);
3405     runUntil(context.done, noTimeout);
3406     m_currentInvocation->didClearStatisticsThroughWebsiteDataRemoval();
3407 }
3408
3409 void TestController::statisticsClearInMemoryAndPersistentStoreModifiedSinceHours(unsigned hours)
3410 {
3411     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3412     ResourceStatisticsCallbackContext context(*this);
3413     WKWebsiteDataStoreStatisticsClearInMemoryAndPersistentStoreModifiedSinceHours(dataStore, hours, &context, resourceStatisticsVoidResultCallback);
3414     runUntil(context.done, noTimeout);
3415     m_currentInvocation->didClearStatisticsThroughWebsiteDataRemoval();
3416 }
3417
3418 void TestController::statisticsClearThroughWebsiteDataRemoval()
3419 {
3420     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3421     ResourceStatisticsCallbackContext context(*this);
3422     WKWebsiteDataStoreStatisticsClearThroughWebsiteDataRemoval(dataStore, &context, resourceStatisticsVoidResultCallback);
3423     runUntil(context.done, noTimeout);
3424     m_currentInvocation->didClearStatisticsThroughWebsiteDataRemoval();
3425 }
3426
3427 void TestController::statisticsDeleteCookiesForHost(WKStringRef host, bool includeHttpOnlyCookies)
3428 {
3429     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3430     ResourceStatisticsCallbackContext context(*this);
3431     WKWebsiteDataStoreStatisticsDeleteCookiesForTesting(dataStore, host, includeHttpOnlyCookies, &context, resourceStatisticsVoidResultCallback);
3432     runUntil(context.done, noTimeout);
3433 }
3434
3435 bool TestController::isStatisticsHasLocalStorage(WKStringRef host)
3436 {
3437     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3438     ResourceStatisticsCallbackContext context(*this);
3439     WKWebsiteDataStoreStatisticsHasLocalStorage(dataStore, host, &context, resourceStatisticsBooleanResultCallback);
3440     runUntil(context.done, noTimeout);
3441     return context.result;
3442 }
3443
3444 void TestController::setStatisticsCacheMaxAgeCap(double seconds)
3445 {
3446     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3447     ResourceStatisticsCallbackContext context(*this);
3448     WKWebsiteDataStoreSetStatisticsCacheMaxAgeCap(dataStore, seconds, &context, resourceStatisticsVoidResultCallback);
3449     runUntil(context.done, noTimeout);
3450 }
3451
3452 void TestController::statisticsResetToConsistentState()
3453 {
3454     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3455     ResourceStatisticsCallbackContext context(*this);
3456     WKWebsiteDataStoreStatisticsResetToConsistentState(dataStore, &context, resourceStatisticsVoidResultCallback);
3457     runUntil(context.done, noTimeout);
3458     m_currentInvocation->didResetStatisticsToConsistentState();
3459 }
3460
3461 void TestController::addMockMediaDevice(WKStringRef persistentID, WKStringRef label, WKStringRef type)
3462 {
3463     WKAddMockMediaDevice(platformContext(), persistentID, label, type);
3464 }
3465
3466 void TestController::clearMockMediaDevices()
3467 {
3468     WKClearMockMediaDevices(platformContext());
3469 }
3470
3471 void TestController::removeMockMediaDevice(WKStringRef persistentID)
3472 {
3473     WKRemoveMockMediaDevice(platformContext(), persistentID);
3474 }
3475
3476 void TestController::resetMockMediaDevices()
3477 {
3478     WKResetMockMediaDevices(platformContext());
3479 }
3480
3481 #if !PLATFORM(COCOA)
3482 void TestController::platformAddTestOptions(TestOptions&) const
3483 {
3484 }
3485
3486 void TestController::injectUserScript(WKStringRef)
3487 {
3488 }
3489
3490 void TestController::addTestKeyToKeychain(const String&, const String&, const String&)
3491 {
3492 }
3493
3494 void TestController::cleanUpKeychain(const String&)
3495 {
3496 }
3497
3498 bool TestController::keyExistsInKeychain(const String&, const String&)
3499 {
3500     return false;
3501 }
3502
3503 bool TestController::canDoServerTrustEvaluationInNetworkProcess() const
3504 {
3505     return false;
3506 }
3507
3508 #endif
3509
3510 void TestController::sendDisplayConfigurationChangedMessageForTesting()
3511 {
3512     WKSendDisplayConfigurationChangedMessageForTesting(platformContext());
3513 }
3514
3515 void TestController::setWebAuthenticationMockConfiguration(WKDictionaryRef configuration)
3516 {
3517     WKWebsiteDataStoreSetWebAuthenticationMockConfiguration(WKContextGetWebsiteDataStore(platformContext()), configuration);
3518 }
3519
3520 struct AdClickAttributionStringResultCallbackContext {
3521     explicit AdClickAttributionStringResultCallbackContext(TestController& controller)
3522         : testController(controller)
3523     {
3524     }
3525     
3526     TestController& testController;
3527     bool done { false };
3528     WKRetainPtr<WKStringRef> adClickAttributionRepresentation;
3529 };
3530
3531 static void adClickAttributionStringResultCallback(WKStringRef adClickAttributionRepresentation, void* userData)
3532 {
3533     auto* context = static_cast<AdClickAttributionStringResultCallbackContext*>(userData);
3534     context->adClickAttributionRepresentation = adClickAttributionRepresentation;
3535     context->done = true;
3536     context->testController.notifyDone();
3537 }
3538
3539 String TestController::dumpAdClickAttribution()
3540 {
3541     AdClickAttributionStringResultCallbackContext callbackContext(*this);
3542     WKPageDumpAdClickAttribution(m_mainWebView->page(), adClickAttributionStringResultCallback, &callbackContext);
3543     runUntil(callbackContext.done, noTimeout);
3544     return toWTFString(callbackContext.adClickAttributionRepresentation.get());
3545 }
3546
3547 struct AdClickAttributionVoidCallbackContext {
3548     explicit AdClickAttributionVoidCallbackContext(TestController& controller)
3549         : testController(controller)
3550     {
3551     }
3552     
3553     TestController& testController;
3554     bool done { false };
3555 };
3556
3557 static void adClickAttributionVoidCallback(void* userData)
3558 {
3559     auto* context = static_cast<AdClickAttributionVoidCallbackContext*>(userData);
3560     context->done = true;
3561     context->testController.notifyDone();
3562 }
3563
3564 void TestController::clearAdClickAttribution()
3565 {
3566     AdClickAttributionVoidCallbackContext callbackContext(*this);
3567     WKPageClearAdClickAttribution(m_mainWebView->page(), adClickAttributionVoidCallback, &callbackContext);
3568     runUntil(callbackContext.done, noTimeout);
3569 }
3570
3571 } // namespace WTR