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