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