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