6d4dffb49656524c64d962e79fe238384c69c0c6
[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         pairStart = pairEnd + 1;
1268     }
1269 }
1270
1271 TestOptions TestController::testOptionsForTest(const TestCommand& command) const
1272 {
1273     TestOptions options(command.pathOrURL);
1274
1275     options.useRemoteLayerTree = m_shouldUseRemoteLayerTree;
1276     options.shouldShowWebView = m_shouldShowWebView;
1277
1278     updatePlatformSpecificTestOptionsForTest(options, command.pathOrURL);
1279     updateTestOptionsFromTestHeader(options, command.pathOrURL, command.absolutePath);
1280     platformAddTestOptions(options);
1281
1282     return options;
1283 }
1284
1285 void TestController::updateWebViewSizeForTest(const TestInvocation& test)
1286 {
1287     unsigned width = viewWidth;
1288     unsigned height = viewHeight;
1289     if (test.options().isSVGTest) {
1290         width = w3cSVGViewWidth;
1291         height = w3cSVGViewHeight;
1292     }
1293
1294     mainWebView()->resizeTo(width, height);
1295 }
1296
1297 void TestController::updateWindowScaleForTest(PlatformWebView* view, const TestInvocation& test)
1298 {
1299     view->changeWindowScaleIfNeeded(test.options().deviceScaleFactor);
1300 }
1301
1302 void TestController::configureViewForTest(const TestInvocation& test)
1303 {
1304     ensureViewSupportsOptionsForTest(test);
1305     updateWebViewSizeForTest(test);
1306     updateWindowScaleForTest(mainWebView(), test);
1307
1308     platformConfigureViewForTest(test);
1309 }
1310
1311 class CommandTokenizer {
1312 public:
1313     explicit CommandTokenizer(const std::string& input)
1314         : m_input(input)
1315         , m_posNextSeparator(0)
1316     {
1317         pump();
1318     }
1319
1320     bool hasNext() const;
1321     std::string next();
1322
1323 private:
1324     void pump();
1325     static const char kSeparator = '\'';
1326     const std::string& m_input;
1327     std::string m_next;
1328     size_t m_posNextSeparator;
1329 };
1330
1331 void CommandTokenizer::pump()
1332 {
1333     if (m_posNextSeparator == std::string::npos || m_posNextSeparator == m_input.size()) {
1334         m_next = std::string();
1335         return;
1336     }
1337     size_t start = m_posNextSeparator ? m_posNextSeparator + 1 : 0;
1338     m_posNextSeparator = m_input.find(kSeparator, start);
1339     size_t size = m_posNextSeparator == std::string::npos ? std::string::npos : m_posNextSeparator - start;
1340     m_next = std::string(m_input, start, size);
1341 }
1342
1343 std::string CommandTokenizer::next()
1344 {
1345     ASSERT(hasNext());
1346
1347     std::string oldNext = m_next;
1348     pump();
1349     return oldNext;
1350 }
1351
1352 bool CommandTokenizer::hasNext() const
1353 {
1354     return !m_next.empty();
1355 }
1356
1357 NO_RETURN static void die(const std::string& inputLine)
1358 {
1359     fprintf(stderr, "Unexpected input line: %s\n", inputLine.c_str());
1360     exit(1);
1361 }
1362
1363 static TestCommand parseInputLine(const std::string& inputLine)
1364 {
1365     TestCommand result;
1366     CommandTokenizer tokenizer(inputLine);
1367     if (!tokenizer.hasNext())
1368         die(inputLine);
1369
1370     std::string arg = tokenizer.next();
1371     result.pathOrURL = arg;
1372     while (tokenizer.hasNext()) {
1373         arg = tokenizer.next();
1374         if (arg == std::string("--timeout")) {
1375             std::string timeoutToken = tokenizer.next();
1376             result.timeout = Seconds::fromMilliseconds(atoi(timeoutToken.c_str()));
1377         } else if (arg == std::string("-p") || arg == std::string("--pixel-test")) {
1378             result.shouldDumpPixels = true;
1379             if (tokenizer.hasNext())
1380                 result.expectedPixelHash = tokenizer.next();
1381         } else if (arg == std::string("--dump-jsconsolelog-in-stderr"))
1382             result.dumpJSConsoleLogInStdErr = true;
1383         else if (arg == std::string("--absolutePath"))
1384             result.absolutePath = tokenizer.next();
1385         else
1386             die(inputLine);
1387     }
1388     return result;
1389 }
1390
1391 bool TestController::runTest(const char* inputLine)
1392 {
1393     AutodrainedPool pool;
1394     
1395     WKTextCheckerSetTestingMode(true);
1396     TestCommand command = parseInputLine(std::string(inputLine));
1397
1398     m_state = RunningTest;
1399     
1400     TestOptions options = testOptionsForTest(command);
1401
1402     WKRetainPtr<WKURLRef> wkURL(AdoptWK, createTestURL(command.pathOrURL.c_str()));
1403     m_currentInvocation = std::make_unique<TestInvocation>(wkURL.get(), options);
1404
1405     if (command.shouldDumpPixels || m_shouldDumpPixelsForAllTests)
1406         m_currentInvocation->setIsPixelTest(command.expectedPixelHash);
1407
1408     if (command.timeout > 0_s)
1409         m_currentInvocation->setCustomTimeout(command.timeout);
1410
1411     m_currentInvocation->setDumpJSConsoleLogInStdErr(command.dumpJSConsoleLogInStdErr || options.dumpJSConsoleLogInStdErr);
1412
1413     platformWillRunTest(*m_currentInvocation);
1414
1415     m_currentInvocation->invoke();
1416     m_currentInvocation = nullptr;
1417
1418     return true;
1419 }
1420
1421 bool TestController::waitForCompletion(const WTF::Function<void ()>& function, WTF::Seconds timeout)
1422 {
1423     m_doneResetting = false;
1424     function();
1425     runUntil(m_doneResetting, timeout);
1426     return !m_doneResetting;
1427 }
1428
1429 bool TestController::handleControlCommand(const char* command)
1430 {
1431     if (!strcmp("#CHECK FOR WORLD LEAKS", command)) {
1432         if (!m_checkForWorldLeaks) {
1433             WTFLogAlways("WebKitTestRunner asked to check for world leaks, but was not run with --world-leaks");
1434             return true;
1435         }
1436         findAndDumpWorldLeaks();
1437         return true;
1438     }
1439     return false;
1440 }
1441
1442 void TestController::runTestingServerLoop()
1443 {
1444     char filenameBuffer[2048];
1445     while (fgets(filenameBuffer, sizeof(filenameBuffer), stdin)) {
1446         char* newLineCharacter = strchr(filenameBuffer, '\n');
1447         if (newLineCharacter)
1448             *newLineCharacter = '\0';
1449
1450         if (strlen(filenameBuffer) == 0)
1451             continue;
1452
1453         if (handleControlCommand(filenameBuffer))
1454             continue;
1455
1456         if (!runTest(filenameBuffer))
1457             break;
1458     }
1459 }
1460
1461 void TestController::run()
1462 {
1463     if (m_usingServerMode)
1464         runTestingServerLoop();
1465     else {
1466         for (size_t i = 0; i < m_paths.size(); ++i) {
1467             if (!runTest(m_paths[i].c_str()))
1468                 break;
1469         }
1470         if (m_checkForWorldLeaks)
1471             findAndDumpWorldLeaks();
1472     }
1473 }
1474
1475 void TestController::runUntil(bool& done, WTF::Seconds timeout)
1476 {
1477     if (m_forceNoTimeout)
1478         timeout = noTimeout;
1479
1480     platformRunUntil(done, timeout);
1481 }
1482
1483 // WKContextInjectedBundleClient
1484
1485 void TestController::didReceiveMessageFromInjectedBundle(WKContextRef context, WKStringRef messageName, WKTypeRef messageBody, const void* clientInfo)
1486 {
1487     static_cast<TestController*>(const_cast<void*>(clientInfo))->didReceiveMessageFromInjectedBundle(messageName, messageBody);
1488 }
1489
1490 void TestController::didReceiveSynchronousMessageFromInjectedBundle(WKContextRef context, WKStringRef messageName, WKTypeRef messageBody, WKTypeRef* returnData, const void* clientInfo)
1491 {
1492     *returnData = static_cast<TestController*>(const_cast<void*>(clientInfo))->didReceiveSynchronousMessageFromInjectedBundle(messageName, messageBody).leakRef();
1493 }
1494
1495 WKTypeRef TestController::getInjectedBundleInitializationUserData(WKContextRef, const void* clientInfo)
1496 {
1497     return static_cast<TestController*>(const_cast<void*>(clientInfo))->getInjectedBundleInitializationUserData().leakRef();
1498 }
1499
1500 // WKPageInjectedBundleClient
1501
1502 void TestController::didReceivePageMessageFromInjectedBundle(WKPageRef page, WKStringRef messageName, WKTypeRef messageBody, const void* clientInfo)
1503 {
1504     static_cast<TestController*>(const_cast<void*>(clientInfo))->didReceiveMessageFromInjectedBundle(messageName, messageBody);
1505 }
1506
1507 void TestController::didReceiveSynchronousPageMessageFromInjectedBundle(WKPageRef page, WKStringRef messageName, WKTypeRef messageBody, WKTypeRef* returnData, const void* clientInfo)
1508 {
1509     *returnData = static_cast<TestController*>(const_cast<void*>(clientInfo))->didReceiveSynchronousMessageFromInjectedBundle(messageName, messageBody).leakRef();
1510 }
1511
1512 void TestController::networkProcessDidCrash(WKContextRef context, const void *clientInfo)
1513 {
1514     static_cast<TestController*>(const_cast<void*>(clientInfo))->networkProcessDidCrash();
1515 }
1516
1517 void TestController::didReceiveKeyDownMessageFromInjectedBundle(WKDictionaryRef messageBodyDictionary, bool synchronous)
1518 {
1519     WKRetainPtr<WKStringRef> keyKey = adoptWK(WKStringCreateWithUTF8CString("Key"));
1520     WKStringRef key = static_cast<WKStringRef>(WKDictionaryGetItemForKey(messageBodyDictionary, keyKey.get()));
1521
1522     WKRetainPtr<WKStringRef> modifiersKey = adoptWK(WKStringCreateWithUTF8CString("Modifiers"));
1523     WKEventModifiers modifiers = static_cast<WKEventModifiers>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, modifiersKey.get()))));
1524
1525     WKRetainPtr<WKStringRef> locationKey = adoptWK(WKStringCreateWithUTF8CString("Location"));
1526     unsigned location = static_cast<unsigned>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, locationKey.get()))));
1527
1528     m_eventSenderProxy->keyDown(key, modifiers, location);
1529 }
1530
1531 void TestController::didReceiveLiveDocumentsList(WKArrayRef liveDocumentList)
1532 {
1533     auto numDocuments = WKArrayGetSize(liveDocumentList);
1534
1535     HashMap<uint64_t, String> documentInfo;
1536     for (size_t i = 0; i < numDocuments; ++i) {
1537         WKTypeRef item = WKArrayGetItemAtIndex(liveDocumentList, i);
1538         if (item && WKGetTypeID(item) == WKDictionaryGetTypeID()) {
1539             WKDictionaryRef liveDocumentItem = static_cast<WKDictionaryRef>(item);
1540
1541             WKRetainPtr<WKStringRef> idKey(AdoptWK, WKStringCreateWithUTF8CString("id"));
1542             WKUInt64Ref documentID = static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(liveDocumentItem, idKey.get()));
1543
1544             WKRetainPtr<WKStringRef> urlKey(AdoptWK, WKStringCreateWithUTF8CString("url"));
1545             WKStringRef documentURL = static_cast<WKStringRef>(WKDictionaryGetItemForKey(liveDocumentItem, urlKey.get()));
1546
1547             documentInfo.add(WKUInt64GetValue(documentID), toWTFString(documentURL));
1548         }
1549     }
1550
1551     if (!documentInfo.size()) {
1552         m_abandonedDocumentInfo.clear();
1553         return;
1554     }
1555
1556     // Remove any documents which are no longer live.
1557     m_abandonedDocumentInfo.removeIf([&](auto& keyAndValue) {
1558         return !documentInfo.contains(keyAndValue.key);
1559     });
1560     
1561     // Add newly abandoned documents.
1562     String currentTestURL = m_currentInvocation ? toWTFString(adoptWK(WKURLCopyString(m_currentInvocation->url()))) : "no test";
1563     for (const auto& it : documentInfo)
1564         m_abandonedDocumentInfo.add(it.key, AbandonedDocumentInfo(currentTestURL, it.value));
1565 }
1566
1567 void TestController::didReceiveMessageFromInjectedBundle(WKStringRef messageName, WKTypeRef messageBody)
1568 {
1569     if (WKStringIsEqualToUTF8CString(messageName, "LiveDocuments")) {
1570         ASSERT(WKGetTypeID(messageBody) == WKArrayGetTypeID());
1571         didReceiveLiveDocumentsList(static_cast<WKArrayRef>(messageBody));
1572         AsyncTask::currentTask()->taskComplete();
1573         return;
1574     }
1575
1576     if (WKStringIsEqualToUTF8CString(messageName, "EventSender")) {
1577         if (m_state != RunningTest)
1578             return;
1579
1580         ASSERT(WKGetTypeID(messageBody) == WKDictionaryGetTypeID());
1581         WKDictionaryRef messageBodyDictionary = static_cast<WKDictionaryRef>(messageBody);
1582
1583         WKRetainPtr<WKStringRef> subMessageKey(AdoptWK, WKStringCreateWithUTF8CString("SubMessage"));
1584         WKStringRef subMessageName = static_cast<WKStringRef>(WKDictionaryGetItemForKey(messageBodyDictionary, subMessageKey.get()));
1585
1586         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseDown") || WKStringIsEqualToUTF8CString(subMessageName, "MouseUp")) {
1587             WKRetainPtr<WKStringRef> buttonKey = adoptWK(WKStringCreateWithUTF8CString("Button"));
1588             unsigned button = static_cast<unsigned>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, buttonKey.get()))));
1589
1590             WKRetainPtr<WKStringRef> modifiersKey = adoptWK(WKStringCreateWithUTF8CString("Modifiers"));
1591             WKEventModifiers modifiers = static_cast<WKEventModifiers>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, modifiersKey.get()))));
1592
1593             // Forward to WebProcess
1594             if (WKStringIsEqualToUTF8CString(subMessageName, "MouseDown"))
1595                 m_eventSenderProxy->mouseDown(button, modifiers);
1596             else
1597                 m_eventSenderProxy->mouseUp(button, modifiers);
1598
1599             return;
1600         }
1601
1602         if (WKStringIsEqualToUTF8CString(subMessageName, "KeyDown")) {
1603             didReceiveKeyDownMessageFromInjectedBundle(messageBodyDictionary, false);
1604             return;
1605         }
1606
1607         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseScrollBy")) {
1608             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
1609             double x = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get())));
1610
1611             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
1612             double y = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get())));
1613
1614             // Forward to WebProcess
1615             m_eventSenderProxy->mouseScrollBy(x, y);
1616             return;
1617         }
1618
1619         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseScrollByWithWheelAndMomentumPhases")) {
1620             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
1621             double x = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get())));
1622             
1623             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
1624             double y = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get())));
1625             
1626             WKRetainPtr<WKStringRef> phaseKey = adoptWK(WKStringCreateWithUTF8CString("Phase"));
1627             int phase = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, phaseKey.get()))));
1628             WKRetainPtr<WKStringRef> momentumKey = adoptWK(WKStringCreateWithUTF8CString("Momentum"));
1629             int momentum = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, momentumKey.get()))));
1630             
1631             // Forward to WebProcess
1632             m_eventSenderProxy->mouseScrollByWithWheelAndMomentumPhases(x, y, phase, momentum);
1633
1634             return;
1635         }
1636
1637         ASSERT_NOT_REACHED();
1638     }
1639
1640     if (!m_currentInvocation)
1641         return;
1642
1643     m_currentInvocation->didReceiveMessageFromInjectedBundle(messageName, messageBody);
1644 }
1645
1646 WKRetainPtr<WKTypeRef> TestController::didReceiveSynchronousMessageFromInjectedBundle(WKStringRef messageName, WKTypeRef messageBody)
1647 {
1648     if (WKStringIsEqualToUTF8CString(messageName, "EventSender")) {
1649         if (m_state != RunningTest)
1650             return nullptr;
1651
1652         ASSERT(WKGetTypeID(messageBody) == WKDictionaryGetTypeID());
1653         WKDictionaryRef messageBodyDictionary = static_cast<WKDictionaryRef>(messageBody);
1654
1655         WKRetainPtr<WKStringRef> subMessageKey(AdoptWK, WKStringCreateWithUTF8CString("SubMessage"));
1656         WKStringRef subMessageName = static_cast<WKStringRef>(WKDictionaryGetItemForKey(messageBodyDictionary, subMessageKey.get()));
1657
1658         if (WKStringIsEqualToUTF8CString(subMessageName, "KeyDown")) {
1659             didReceiveKeyDownMessageFromInjectedBundle(messageBodyDictionary, true);
1660
1661             return 0;
1662         }
1663
1664         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseDown") || WKStringIsEqualToUTF8CString(subMessageName, "MouseUp")) {
1665             WKRetainPtr<WKStringRef> buttonKey = adoptWK(WKStringCreateWithUTF8CString("Button"));
1666             unsigned button = static_cast<unsigned>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, buttonKey.get()))));
1667
1668             WKRetainPtr<WKStringRef> modifiersKey = adoptWK(WKStringCreateWithUTF8CString("Modifiers"));
1669             WKEventModifiers modifiers = static_cast<WKEventModifiers>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, modifiersKey.get()))));
1670
1671             // Forward to WebProcess
1672             if (WKStringIsEqualToUTF8CString(subMessageName, "MouseDown"))
1673                 m_eventSenderProxy->mouseDown(button, modifiers);
1674             else
1675                 m_eventSenderProxy->mouseUp(button, modifiers);
1676             return 0;
1677         }
1678
1679         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseMoveTo")) {
1680             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
1681             double x = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get())));
1682
1683             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
1684             double y = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get())));
1685
1686             // Forward to WebProcess
1687             m_eventSenderProxy->mouseMoveTo(x, y);
1688             return 0;
1689         }
1690
1691 #if PLATFORM(MAC)
1692         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseForceClick")) {
1693             m_eventSenderProxy->mouseForceClick();
1694             return 0;
1695         }
1696
1697         if (WKStringIsEqualToUTF8CString(subMessageName, "StartAndCancelMouseForceClick")) {
1698             m_eventSenderProxy->startAndCancelMouseForceClick();
1699             return 0;
1700         }
1701
1702         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseForceDown")) {
1703             m_eventSenderProxy->mouseForceDown();
1704             return 0;
1705         }
1706
1707         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseForceUp")) {
1708             m_eventSenderProxy->mouseForceUp();
1709             return 0;
1710         }
1711
1712         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseForceChanged")) {
1713             WKRetainPtr<WKStringRef> forceKey = adoptWK(WKStringCreateWithUTF8CString("Force"));
1714             double force = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, forceKey.get())));
1715
1716             m_eventSenderProxy->mouseForceChanged(force);
1717             return 0;
1718         }
1719 #endif // PLATFORM(MAC)
1720
1721         if (WKStringIsEqualToUTF8CString(subMessageName, "ContinuousMouseScrollBy")) {
1722             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
1723             double x = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get())));
1724
1725             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
1726             double y = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get())));
1727
1728             WKRetainPtr<WKStringRef> pagedKey = adoptWK(WKStringCreateWithUTF8CString("Paged"));
1729             bool paged = static_cast<bool>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, pagedKey.get()))));
1730
1731             // Forward to WebProcess
1732             m_eventSenderProxy->continuousMouseScrollBy(x, y, paged);
1733             return 0;
1734         }
1735
1736         if (WKStringIsEqualToUTF8CString(subMessageName, "LeapForward")) {
1737             WKRetainPtr<WKStringRef> timeKey = adoptWK(WKStringCreateWithUTF8CString("TimeInMilliseconds"));
1738             unsigned time = static_cast<unsigned>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, timeKey.get()))));
1739
1740             m_eventSenderProxy->leapForward(time);
1741             return 0;
1742         }
1743
1744 #if ENABLE(TOUCH_EVENTS)
1745         if (WKStringIsEqualToUTF8CString(subMessageName, "AddTouchPoint")) {
1746             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
1747             int x = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get()))));
1748
1749             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
1750             int y = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get()))));
1751
1752             m_eventSenderProxy->addTouchPoint(x, y);
1753             return 0;
1754         }
1755
1756         if (WKStringIsEqualToUTF8CString(subMessageName, "UpdateTouchPoint")) {
1757             WKRetainPtr<WKStringRef> indexKey = adoptWK(WKStringCreateWithUTF8CString("Index"));
1758             int index = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, indexKey.get()))));
1759
1760             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
1761             int x = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get()))));
1762
1763             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
1764             int y = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get()))));
1765
1766             m_eventSenderProxy->updateTouchPoint(index, x, y);
1767             return 0;
1768         }
1769
1770         if (WKStringIsEqualToUTF8CString(subMessageName, "SetTouchModifier")) {
1771             WKRetainPtr<WKStringRef> modifierKey = adoptWK(WKStringCreateWithUTF8CString("Modifier"));
1772             WKEventModifiers modifier = static_cast<WKEventModifiers>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, modifierKey.get()))));
1773
1774             WKRetainPtr<WKStringRef> enableKey = adoptWK(WKStringCreateWithUTF8CString("Enable"));
1775             bool enable = static_cast<bool>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, enableKey.get()))));
1776
1777             m_eventSenderProxy->setTouchModifier(modifier, enable);
1778             return 0;
1779         }
1780
1781         if (WKStringIsEqualToUTF8CString(subMessageName, "SetTouchPointRadius")) {
1782             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("RadiusX"));
1783             int x = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get()))));
1784
1785             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("RadiusY"));
1786             int y = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get()))));
1787
1788             m_eventSenderProxy->setTouchPointRadius(x, y);
1789             return 0;
1790         }
1791
1792         if (WKStringIsEqualToUTF8CString(subMessageName, "TouchStart")) {
1793             m_eventSenderProxy->touchStart();
1794             return 0;
1795         }
1796
1797         if (WKStringIsEqualToUTF8CString(subMessageName, "TouchMove")) {
1798             m_eventSenderProxy->touchMove();
1799             return 0;
1800         }
1801
1802         if (WKStringIsEqualToUTF8CString(subMessageName, "TouchEnd")) {
1803             m_eventSenderProxy->touchEnd();
1804             return 0;
1805         }
1806
1807         if (WKStringIsEqualToUTF8CString(subMessageName, "TouchCancel")) {
1808             m_eventSenderProxy->touchCancel();
1809             return 0;
1810         }
1811
1812         if (WKStringIsEqualToUTF8CString(subMessageName, "ClearTouchPoints")) {
1813             m_eventSenderProxy->clearTouchPoints();
1814             return 0;
1815         }
1816
1817         if (WKStringIsEqualToUTF8CString(subMessageName, "ReleaseTouchPoint")) {
1818             WKRetainPtr<WKStringRef> indexKey = adoptWK(WKStringCreateWithUTF8CString("Index"));
1819             int index = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, indexKey.get()))));
1820             m_eventSenderProxy->releaseTouchPoint(index);
1821             return 0;
1822         }
1823
1824         if (WKStringIsEqualToUTF8CString(subMessageName, "CancelTouchPoint")) {
1825             WKRetainPtr<WKStringRef> indexKey = adoptWK(WKStringCreateWithUTF8CString("Index"));
1826             int index = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, indexKey.get()))));
1827             m_eventSenderProxy->cancelTouchPoint(index);
1828             return 0;
1829         }
1830 #endif
1831         ASSERT_NOT_REACHED();
1832     }
1833     return m_currentInvocation->didReceiveSynchronousMessageFromInjectedBundle(messageName, messageBody);
1834 }
1835
1836 WKRetainPtr<WKTypeRef> TestController::getInjectedBundleInitializationUserData()
1837 {
1838     return nullptr;
1839 }
1840
1841 // WKContextClient
1842
1843 void TestController::networkProcessDidCrash()
1844 {
1845     pid_t pid = WKContextGetNetworkProcessIdentifier(m_context.get());
1846     fprintf(stderr, "#CRASHED - %s (pid %ld)\n", networkProcessName(), static_cast<long>(pid));
1847     exit(1);
1848 }
1849
1850 // WKPageNavigationClient
1851
1852 void TestController::didCommitNavigation(WKPageRef page, WKNavigationRef navigation, WKTypeRef, const void* clientInfo)
1853 {
1854     static_cast<TestController*>(const_cast<void*>(clientInfo))->didCommitNavigation(page, navigation);
1855 }
1856
1857 void TestController::didFinishNavigation(WKPageRef page, WKNavigationRef navigation, WKTypeRef, const void* clientInfo)
1858 {
1859     static_cast<TestController*>(const_cast<void*>(clientInfo))->didFinishNavigation(page, navigation);
1860 }
1861
1862 void TestController::didReceiveServerRedirectForProvisionalNavigation(WKPageRef page, WKNavigationRef navigation, WKTypeRef userData, const void* clientInfo)
1863 {
1864     static_cast<TestController*>(const_cast<void*>(clientInfo))->didReceiveServerRedirectForProvisionalNavigation(page, navigation, userData);
1865 }
1866
1867 bool TestController::canAuthenticateAgainstProtectionSpace(WKPageRef page, WKProtectionSpaceRef protectionSpace, const void* clientInfo)
1868 {
1869     return static_cast<TestController*>(const_cast<void*>(clientInfo))->canAuthenticateAgainstProtectionSpace(page, protectionSpace);
1870 }
1871
1872 void TestController::didReceiveAuthenticationChallenge(WKPageRef page, WKAuthenticationChallengeRef authenticationChallenge, const void *clientInfo)
1873 {
1874     static_cast<TestController*>(const_cast<void*>(clientInfo))->didReceiveAuthenticationChallenge(page, /*frame,*/ authenticationChallenge);
1875 }
1876
1877 void TestController::processDidCrash(WKPageRef page, const void* clientInfo)
1878 {
1879     static_cast<TestController*>(const_cast<void*>(clientInfo))->processDidCrash();
1880 }
1881
1882 void TestController::didBeginNavigationGesture(WKPageRef page, const void *clientInfo)
1883 {
1884     static_cast<TestController*>(const_cast<void*>(clientInfo))->didBeginNavigationGesture(page);
1885 }
1886
1887 void TestController::willEndNavigationGesture(WKPageRef page, WKBackForwardListItemRef backForwardListItem, const void *clientInfo)
1888 {
1889     static_cast<TestController*>(const_cast<void*>(clientInfo))->willEndNavigationGesture(page, backForwardListItem);
1890 }
1891
1892 void TestController::didEndNavigationGesture(WKPageRef page, WKBackForwardListItemRef backForwardListItem, const void *clientInfo)
1893 {
1894     static_cast<TestController*>(const_cast<void*>(clientInfo))->didEndNavigationGesture(page, backForwardListItem);
1895 }
1896
1897 void TestController::didRemoveNavigationGestureSnapshot(WKPageRef page, const void *clientInfo)
1898 {
1899     static_cast<TestController*>(const_cast<void*>(clientInfo))->didRemoveNavigationGestureSnapshot(page);
1900 }
1901
1902 WKPluginLoadPolicy TestController::decidePolicyForPluginLoad(WKPageRef page, WKPluginLoadPolicy currentPluginLoadPolicy, WKDictionaryRef pluginInformation, WKStringRef* unavailabilityDescription, const void* clientInfo)
1903 {
1904     return static_cast<TestController*>(const_cast<void*>(clientInfo))->decidePolicyForPluginLoad(page, currentPluginLoadPolicy, pluginInformation, unavailabilityDescription);
1905 }
1906
1907 WKPluginLoadPolicy TestController::decidePolicyForPluginLoad(WKPageRef, WKPluginLoadPolicy currentPluginLoadPolicy, WKDictionaryRef pluginInformation, WKStringRef* unavailabilityDescription)
1908 {
1909     if (m_shouldBlockAllPlugins)
1910         return kWKPluginLoadPolicyBlocked;
1911
1912 #if PLATFORM(MAC)
1913     WKStringRef bundleIdentifier = (WKStringRef)WKDictionaryGetItemForKey(pluginInformation, WKPluginInformationBundleIdentifierKey());
1914     if (!bundleIdentifier)
1915         return currentPluginLoadPolicy;
1916
1917     if (WKStringIsEqualToUTF8CString(bundleIdentifier, "com.apple.QuickTime Plugin.plugin"))
1918         return currentPluginLoadPolicy;
1919
1920     if (WKStringIsEqualToUTF8CString(bundleIdentifier, "com.apple.testnetscapeplugin"))
1921         return currentPluginLoadPolicy;
1922
1923     RELEASE_ASSERT_NOT_REACHED(); // Please don't use any other plug-ins in tests, as they will not be installed on all machines.
1924 #else
1925     return currentPluginLoadPolicy;
1926 #endif
1927 }
1928
1929 void TestController::setBlockAllPlugins(bool shouldBlock)
1930 {
1931     m_shouldBlockAllPlugins = shouldBlock;
1932
1933 #if PLATFORM(MAC)
1934     auto policy = shouldBlock ? kWKPluginLoadClientPolicyBlock : kWKPluginLoadClientPolicyAllow;
1935
1936     WKRetainPtr<WKStringRef> nameNetscape = adoptWK(WKStringCreateWithUTF8CString("com.apple.testnetscapeplugin"));
1937     WKRetainPtr<WKStringRef> nameFlash = adoptWK(WKStringCreateWithUTF8CString("com.macromedia.Flash Player.plugin"));
1938     WKRetainPtr<WKStringRef> emptyString = adoptWK(WKStringCreateWithUTF8CString(""));
1939     WKContextSetPluginLoadClientPolicy(m_context.get(), policy, emptyString.get(), nameNetscape.get(), emptyString.get());
1940     WKContextSetPluginLoadClientPolicy(m_context.get(), policy, emptyString.get(), nameFlash.get(), emptyString.get());
1941 #endif
1942 }
1943
1944 void TestController::setPluginSupportedMode(const String& mode)
1945 {
1946     if (m_unsupportedPluginMode == mode)
1947         return;
1948
1949     m_unsupportedPluginMode = mode;
1950     if (m_unsupportedPluginMode.isEmpty()) {
1951         WKContextClearSupportedPlugins(m_context.get());
1952         return;
1953     }
1954
1955     WKRetainPtr<WKMutableArrayRef> emptyArray = adoptWK(WKMutableArrayCreate());
1956     WKRetainPtr<WKStringRef> allOrigins = adoptWK(WKStringCreateWithUTF8CString(""));
1957     WKRetainPtr<WKStringRef> specificOrigin = adoptWK(WKStringCreateWithUTF8CString("localhost"));
1958
1959     WKRetainPtr<WKStringRef> pdfName = adoptWK(WKStringCreateWithUTF8CString("My personal PDF"));
1960     WKContextAddSupportedPlugin(m_context.get(), allOrigins.get(), pdfName.get(), emptyArray.get(), emptyArray.get());
1961
1962     WKRetainPtr<WKStringRef> nameNetscape = adoptWK(WKStringCreateWithUTF8CString("com.apple.testnetscapeplugin"));
1963     WKRetainPtr<WKStringRef> mimeTypeNetscape = adoptWK(WKStringCreateWithUTF8CString("application/x-webkit-test-netscape"));
1964     WKRetainPtr<WKMutableArrayRef> mimeTypesNetscape = adoptWK(WKMutableArrayCreate());
1965     WKArrayAppendItem(mimeTypesNetscape.get(), mimeTypeNetscape.get());
1966
1967     WKRetainPtr<WKStringRef> namePdf = adoptWK(WKStringCreateWithUTF8CString("WebKit built-in PDF"));
1968
1969     if (m_unsupportedPluginMode == "allOrigins") {
1970         WKContextAddSupportedPlugin(m_context.get(), allOrigins.get(), nameNetscape.get(), mimeTypesNetscape.get(), emptyArray.get());
1971         WKContextAddSupportedPlugin(m_context.get(), allOrigins.get(), namePdf.get(), emptyArray.get(), emptyArray.get());
1972         return;
1973     }
1974
1975     if (m_unsupportedPluginMode == "specificOrigin") {
1976         WKContextAddSupportedPlugin(m_context.get(), specificOrigin.get(), nameNetscape.get(), mimeTypesNetscape.get(), emptyArray.get());
1977         WKContextAddSupportedPlugin(m_context.get(), specificOrigin.get(), namePdf.get(), emptyArray.get(), emptyArray.get());
1978         return;
1979     }
1980 }
1981
1982 void TestController::didCommitNavigation(WKPageRef page, WKNavigationRef navigation)
1983 {
1984     mainWebView()->focus();
1985 }
1986
1987 void TestController::didReceiveServerRedirectForProvisionalNavigation(WKPageRef page, WKNavigationRef navigation, WKTypeRef userData)
1988 {
1989     m_didReceiveServerRedirectForProvisionalNavigation = true;
1990     return;
1991 }
1992
1993 static const char* toString(WKProtectionSpaceAuthenticationScheme scheme)
1994 {
1995     switch (scheme) {
1996     case kWKProtectionSpaceAuthenticationSchemeDefault:
1997         return "ProtectionSpaceAuthenticationSchemeDefault";
1998     case kWKProtectionSpaceAuthenticationSchemeHTTPBasic:
1999         return "ProtectionSpaceAuthenticationSchemeHTTPBasic";
2000     case kWKProtectionSpaceAuthenticationSchemeHTMLForm:
2001         return "ProtectionSpaceAuthenticationSchemeHTMLForm";
2002     case kWKProtectionSpaceAuthenticationSchemeNTLM:
2003         return "ProtectionSpaceAuthenticationSchemeNTLM";
2004     case kWKProtectionSpaceAuthenticationSchemeNegotiate:
2005         return "ProtectionSpaceAuthenticationSchemeNegotiate";
2006     case kWKProtectionSpaceAuthenticationSchemeClientCertificateRequested:
2007         return "ProtectionSpaceAuthenticationSchemeClientCertificateRequested";
2008     case kWKProtectionSpaceAuthenticationSchemeServerTrustEvaluationRequested:
2009         return "ProtectionSpaceAuthenticationSchemeServerTrustEvaluationRequested";
2010     case kWKProtectionSpaceAuthenticationSchemeOAuth:
2011         return "ProtectionSpaceAuthenticationSchemeOAuth";
2012     case kWKProtectionSpaceAuthenticationSchemeUnknown:
2013         return "ProtectionSpaceAuthenticationSchemeUnknown";
2014     }
2015     ASSERT_NOT_REACHED();
2016     return "ProtectionSpaceAuthenticationSchemeUnknown";
2017 }
2018
2019 bool TestController::canAuthenticateAgainstProtectionSpace(WKPageRef page, WKProtectionSpaceRef protectionSpace)
2020 {
2021     if (m_shouldLogCanAuthenticateAgainstProtectionSpace)
2022         m_currentInvocation->outputText("canAuthenticateAgainstProtectionSpace\n");
2023     WKProtectionSpaceAuthenticationScheme authenticationScheme = WKProtectionSpaceGetAuthenticationScheme(protectionSpace);
2024     
2025     if (authenticationScheme == kWKProtectionSpaceAuthenticationSchemeServerTrustEvaluationRequested) {
2026         std::string host = toSTD(adoptWK(WKProtectionSpaceCopyHost(protectionSpace)).get());
2027         return host == "localhost" || host == "127.0.0.1" || (m_allowAnyHTTPSCertificateForAllowedHosts && m_allowedHosts.find(host) != m_allowedHosts.end());
2028     }
2029     
2030     return authenticationScheme <= kWKProtectionSpaceAuthenticationSchemeHTTPDigest || authenticationScheme == kWKProtectionSpaceAuthenticationSchemeOAuth;
2031 }
2032
2033 void TestController::didFinishNavigation(WKPageRef page, WKNavigationRef navigation)
2034 {
2035     if (m_state != Resetting)
2036         return;
2037
2038     WKRetainPtr<WKURLRef> wkURL(AdoptWK, WKFrameCopyURL(WKPageGetMainFrame(page)));
2039     if (!WKURLIsEqual(wkURL.get(), blankURL()))
2040         return;
2041
2042     m_doneResetting = true;
2043     singleton().notifyDone();
2044 }
2045
2046 void TestController::didReceiveAuthenticationChallenge(WKPageRef page, WKAuthenticationChallengeRef authenticationChallenge)
2047 {
2048     WKProtectionSpaceRef protectionSpace = WKAuthenticationChallengeGetProtectionSpace(authenticationChallenge);
2049     WKAuthenticationDecisionListenerRef decisionListener = WKAuthenticationChallengeGetDecisionListener(authenticationChallenge);
2050     WKProtectionSpaceAuthenticationScheme authenticationScheme = WKProtectionSpaceGetAuthenticationScheme(protectionSpace);
2051
2052     if (authenticationScheme == kWKProtectionSpaceAuthenticationSchemeServerTrustEvaluationRequested) {
2053         // Any non-empty credential signals to accept the server trust. Since the cross-platform API
2054         // doesn't expose a way to create a credential from server trust, we use a password credential.
2055
2056         WKRetainPtr<WKCredentialRef> credential = adoptWK(WKCredentialCreate(toWK("accept server trust").get(), toWK("").get(), kWKCredentialPersistenceNone));
2057         WKAuthenticationDecisionListenerUseCredential(decisionListener, credential.get());
2058         return;
2059     }
2060
2061     if (m_rejectsProtectionSpaceAndContinueForAuthenticationChallenges) {
2062         m_currentInvocation->outputText("Simulating reject protection space and continue for authentication challenge\n");
2063         WKAuthenticationDecisionListenerRejectProtectionSpaceAndContinue(decisionListener);
2064         return;
2065     }
2066
2067     std::string host = toSTD(adoptWK(WKProtectionSpaceCopyHost(protectionSpace)).get());
2068     int port = WKProtectionSpaceGetPort(protectionSpace);
2069     String message = String::format("%s:%d - didReceiveAuthenticationChallenge - %s - ", host.c_str(), port, toString(authenticationScheme));
2070     if (!m_handlesAuthenticationChallenges)
2071         message.append("Simulating cancelled authentication sheet\n");
2072     else
2073         message.append(String::format("Responding with %s:%s\n", m_authenticationUsername.utf8().data(), m_authenticationPassword.utf8().data()));
2074     m_currentInvocation->outputText(message);
2075
2076     if (!m_handlesAuthenticationChallenges) {
2077         WKAuthenticationDecisionListenerUseCredential(decisionListener, 0);
2078         return;
2079     }
2080     WKRetainPtr<WKStringRef> username(AdoptWK, WKStringCreateWithUTF8CString(m_authenticationUsername.utf8().data()));
2081     WKRetainPtr<WKStringRef> password(AdoptWK, WKStringCreateWithUTF8CString(m_authenticationPassword.utf8().data()));
2082     WKRetainPtr<WKCredentialRef> credential(AdoptWK, WKCredentialCreate(username.get(), password.get(), kWKCredentialPersistenceForSession));
2083     WKAuthenticationDecisionListenerUseCredential(decisionListener, credential.get());
2084 }
2085
2086     
2087 // WKContextDownloadClient
2088
2089 void TestController::downloadDidStart(WKContextRef context, WKDownloadRef download, const void* clientInfo)
2090 {
2091     static_cast<TestController*>(const_cast<void*>(clientInfo))->downloadDidStart(context, download);
2092 }
2093     
2094 WKStringRef TestController::decideDestinationWithSuggestedFilename(WKContextRef context, WKDownloadRef download, WKStringRef filename, bool* allowOverwrite, const void* clientInfo)
2095 {
2096     return static_cast<TestController*>(const_cast<void*>(clientInfo))->decideDestinationWithSuggestedFilename(context, download, filename, allowOverwrite);
2097 }
2098
2099 void TestController::downloadDidFinish(WKContextRef context, WKDownloadRef download, const void* clientInfo)
2100 {
2101     static_cast<TestController*>(const_cast<void*>(clientInfo))->downloadDidFinish(context, download);
2102 }
2103
2104 void TestController::downloadDidFail(WKContextRef context, WKDownloadRef download, WKErrorRef error, const void* clientInfo)
2105 {
2106     static_cast<TestController*>(const_cast<void*>(clientInfo))->downloadDidFail(context, download, error);
2107 }
2108
2109 void TestController::downloadDidCancel(WKContextRef context, WKDownloadRef download, const void* clientInfo)
2110 {
2111     static_cast<TestController*>(const_cast<void*>(clientInfo))->downloadDidCancel(context, download);
2112 }
2113
2114 void TestController::downloadDidReceiveServerRedirectToURL(WKContextRef context, WKDownloadRef download, WKURLRef url, const void* clientInfo)
2115 {
2116     static_cast<TestController*>(const_cast<void*>(clientInfo))->downloadDidReceiveServerRedirectToURL(context, download, url);
2117 }
2118
2119 void TestController::downloadDidStart(WKContextRef context, WKDownloadRef download)
2120 {
2121     if (m_shouldLogDownloadCallbacks)
2122         m_currentInvocation->outputText("Download started.\n");
2123 }
2124
2125 WKStringRef TestController::decideDestinationWithSuggestedFilename(WKContextRef, WKDownloadRef, WKStringRef filename, bool*& allowOverwrite)
2126 {
2127     String suggestedFilename = toWTFString(filename);
2128
2129     if (m_shouldLogDownloadCallbacks) {
2130         StringBuilder builder;
2131         builder.append("Downloading URL with suggested filename \"");
2132         builder.append(suggestedFilename);
2133         builder.append("\"\n");
2134         m_currentInvocation->outputText(builder.toString());
2135     }
2136
2137     const char* dumpRenderTreeTemp = libraryPathForTesting();
2138     if (!dumpRenderTreeTemp)
2139         return nullptr;
2140
2141     *allowOverwrite = true;
2142     String temporaryFolder = String::fromUTF8(dumpRenderTreeTemp);
2143     if (suggestedFilename.isEmpty())
2144         suggestedFilename = "Unknown";
2145
2146     return toWK(temporaryFolder + "/" + suggestedFilename).leakRef();
2147 }
2148
2149 void TestController::downloadDidFinish(WKContextRef, WKDownloadRef)
2150 {
2151     if (m_shouldLogDownloadCallbacks)
2152         m_currentInvocation->outputText("Download completed.\n");
2153     m_currentInvocation->notifyDownloadDone();
2154 }
2155
2156 void TestController::downloadDidReceiveServerRedirectToURL(WKContextRef, WKDownloadRef, WKURLRef url)
2157 {
2158     if (m_shouldLogDownloadCallbacks) {
2159         StringBuilder builder;
2160         builder.appendLiteral("Download was redirected to \"");
2161         WKRetainPtr<WKStringRef> urlStringWK = adoptWK(WKURLCopyString(url));
2162         builder.append(toSTD(urlStringWK).c_str());
2163         builder.appendLiteral("\".\n");
2164         m_currentInvocation->outputText(builder.toString());
2165     }
2166 }
2167
2168 void TestController::downloadDidFail(WKContextRef, WKDownloadRef, WKErrorRef error)
2169 {
2170     if (m_shouldLogDownloadCallbacks) {
2171         String message = String::format("Download failed.\n");
2172         m_currentInvocation->outputText(message);
2173
2174         WKRetainPtr<WKStringRef> errorDomain = adoptWK(WKErrorCopyDomain(error));
2175         WKRetainPtr<WKStringRef> errorDescription = adoptWK(WKErrorCopyLocalizedDescription(error));
2176         int errorCode = WKErrorGetErrorCode(error);
2177
2178         StringBuilder errorBuilder;
2179         errorBuilder.append("Failed: ");
2180         errorBuilder.append(toWTFString(errorDomain));
2181         errorBuilder.append(", code=");
2182         errorBuilder.appendNumber(errorCode);
2183         errorBuilder.append(", description=");
2184         errorBuilder.append(toWTFString(errorDescription));
2185         errorBuilder.append("\n");
2186
2187         m_currentInvocation->outputText(errorBuilder.toString());
2188     }
2189     m_currentInvocation->notifyDownloadDone();
2190 }
2191
2192 void TestController::downloadDidCancel(WKContextRef, WKDownloadRef)
2193 {
2194     if (m_shouldLogDownloadCallbacks)
2195         m_currentInvocation->outputText("Download cancelled.\n");
2196     m_currentInvocation->notifyDownloadDone();
2197 }
2198
2199 void TestController::processDidCrash()
2200 {
2201     // This function can be called multiple times when crash logs are being saved on Windows, so
2202     // ensure we only print the crashed message once.
2203     if (!m_didPrintWebProcessCrashedMessage) {
2204         pid_t pid = WKPageGetProcessIdentifier(m_mainWebView->page());
2205         fprintf(stderr, "#CRASHED - %s (pid %ld)\n", webProcessName(), static_cast<long>(pid));
2206         fflush(stderr);
2207         m_didPrintWebProcessCrashedMessage = true;
2208     }
2209
2210     if (m_shouldExitWhenWebProcessCrashes)
2211         exit(1);
2212 }
2213
2214 void TestController::didBeginNavigationGesture(WKPageRef)
2215 {
2216     m_currentInvocation->didBeginSwipe();
2217 }
2218
2219 void TestController::willEndNavigationGesture(WKPageRef, WKBackForwardListItemRef)
2220 {
2221     m_currentInvocation->willEndSwipe();
2222 }
2223
2224 void TestController::didEndNavigationGesture(WKPageRef, WKBackForwardListItemRef)
2225 {
2226     m_currentInvocation->didEndSwipe();
2227 }
2228
2229 void TestController::didRemoveNavigationGestureSnapshot(WKPageRef)
2230 {
2231     m_currentInvocation->didRemoveSwipeSnapshot();
2232 }
2233
2234 void TestController::simulateWebNotificationClick(uint64_t notificationID)
2235 {
2236     m_webNotificationProvider.simulateWebNotificationClick(mainWebView()->page(), notificationID);
2237 }
2238
2239 void TestController::setGeolocationPermission(bool enabled)
2240 {
2241     m_isGeolocationPermissionSet = true;
2242     m_isGeolocationPermissionAllowed = enabled;
2243     decidePolicyForGeolocationPermissionRequestIfPossible();
2244 }
2245
2246 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)
2247 {
2248     m_geolocationProvider->setPosition(latitude, longitude, accuracy, providesAltitude, altitude, providesAltitudeAccuracy, altitudeAccuracy, providesHeading, heading, providesSpeed, speed, providesFloorLevel, floorLevel);
2249 }
2250
2251 void TestController::setMockGeolocationPositionUnavailableError(WKStringRef errorMessage)
2252 {
2253     m_geolocationProvider->setPositionUnavailableError(errorMessage);
2254 }
2255
2256 void TestController::handleGeolocationPermissionRequest(WKGeolocationPermissionRequestRef geolocationPermissionRequest)
2257 {
2258     m_geolocationPermissionRequests.append(geolocationPermissionRequest);
2259     decidePolicyForGeolocationPermissionRequestIfPossible();
2260 }
2261
2262 bool TestController::isGeolocationProviderActive() const
2263 {
2264     return m_geolocationProvider->isActive();
2265 }
2266
2267 static String originUserVisibleName(WKSecurityOriginRef origin)
2268 {
2269     if (!origin)
2270         return emptyString();
2271
2272     std::string host = toSTD(adoptWK(WKSecurityOriginCopyHost(origin))).c_str();
2273     std::string protocol = toSTD(adoptWK(WKSecurityOriginCopyProtocol(origin))).c_str();
2274
2275     if (!host.length() || !protocol.length())
2276         return emptyString();
2277
2278     unsigned short port = WKSecurityOriginGetPort(origin);
2279     if (port)
2280         return String::format("%s://%s:%d", protocol.c_str(), host.c_str(), port);
2281
2282     return String::format("%s://%s", protocol.c_str(), host.c_str());
2283 }
2284
2285 static String userMediaOriginHash(WKSecurityOriginRef userMediaDocumentOrigin, WKSecurityOriginRef topLevelDocumentOrigin)
2286 {
2287     String userMediaDocumentOriginString = originUserVisibleName(userMediaDocumentOrigin);
2288     String topLevelDocumentOriginString = originUserVisibleName(topLevelDocumentOrigin);
2289
2290     if (topLevelDocumentOriginString.isEmpty())
2291         return userMediaDocumentOriginString;
2292
2293     return String::format("%s-%s", userMediaDocumentOriginString.utf8().data(), topLevelDocumentOriginString.utf8().data());
2294 }
2295
2296 static String userMediaOriginHash(WKStringRef userMediaDocumentOriginString, WKStringRef topLevelDocumentOriginString)
2297 {
2298     auto userMediaDocumentOrigin = adoptWK(WKSecurityOriginCreateFromString(userMediaDocumentOriginString));
2299     if (!WKStringGetLength(topLevelDocumentOriginString))
2300         return userMediaOriginHash(userMediaDocumentOrigin.get(), nullptr);
2301
2302     auto topLevelDocumentOrigin = adoptWK(WKSecurityOriginCreateFromString(topLevelDocumentOriginString));
2303     return userMediaOriginHash(userMediaDocumentOrigin.get(), topLevelDocumentOrigin.get());
2304 }
2305
2306 void TestController::setUserMediaPermission(bool enabled)
2307 {
2308     m_isUserMediaPermissionSet = true;
2309     m_isUserMediaPermissionAllowed = enabled;
2310     decidePolicyForUserMediaPermissionRequestIfPossible();
2311 }
2312
2313 void TestController::resetUserMediaPermission()
2314 {
2315     m_isUserMediaPermissionSet = false;
2316 }
2317
2318 class OriginSettings : public RefCounted<OriginSettings> {
2319 public:
2320     explicit OriginSettings()
2321     {
2322     }
2323
2324     bool persistentPermission() const { return m_persistentPermission; }
2325     void setPersistentPermission(bool permission) { m_persistentPermission = permission; }
2326
2327     String persistentSalt() const { return m_persistentSalt; }
2328     void setPersistentSalt(const String& salt) { m_persistentSalt = salt; }
2329
2330     HashMap<uint64_t, String>& ephemeralSalts() { return m_ephemeralSalts; }
2331
2332     void incrementRequestCount() { ++m_requestCount; }
2333     void resetRequestCount() { m_requestCount = 0; }
2334     unsigned requestCount() const { return m_requestCount; }
2335
2336 private:
2337     HashMap<uint64_t, String> m_ephemeralSalts;
2338     String m_persistentSalt;
2339     unsigned m_requestCount { 0 };
2340     bool m_persistentPermission { false };
2341 };
2342
2343 String TestController::saltForOrigin(WKFrameRef frame, String originHash)
2344 {
2345     auto& settings = settingsForOrigin(originHash);
2346     auto& ephemeralSalts = settings.ephemeralSalts();
2347     auto frameInfo = adoptWK(WKFrameCreateFrameInfo(frame));
2348     auto frameHandle = WKFrameInfoGetFrameHandleRef(frameInfo.get());
2349     uint64_t frameIdentifier = WKFrameHandleGetFrameID(frameHandle);
2350     String frameSalt = ephemeralSalts.get(frameIdentifier);
2351
2352     if (settings.persistentPermission()) {
2353         if (frameSalt.length())
2354             return frameSalt;
2355
2356         if (!settings.persistentSalt().length())
2357             settings.setPersistentSalt(createCanonicalUUIDString());
2358
2359         return settings.persistentSalt();
2360     }
2361
2362     if (!frameSalt.length()) {
2363         frameSalt = createCanonicalUUIDString();
2364         ephemeralSalts.add(frameIdentifier, frameSalt);
2365     }
2366
2367     return frameSalt;
2368 }
2369
2370 void TestController::setUserMediaPersistentPermissionForOrigin(bool permission, WKStringRef userMediaDocumentOriginString, WKStringRef topLevelDocumentOriginString)
2371 {
2372     auto originHash = userMediaOriginHash(userMediaDocumentOriginString, topLevelDocumentOriginString);
2373     auto& settings = settingsForOrigin(originHash);
2374     settings.setPersistentPermission(permission);
2375 }
2376
2377 void TestController::handleCheckOfUserMediaPermissionForOrigin(WKFrameRef frame, WKSecurityOriginRef userMediaDocumentOrigin, WKSecurityOriginRef topLevelDocumentOrigin, const WKUserMediaPermissionCheckRef& checkRequest)
2378 {
2379     auto originHash = userMediaOriginHash(userMediaDocumentOrigin, topLevelDocumentOrigin);
2380     auto salt = saltForOrigin(frame, originHash);
2381     WKRetainPtr<WKStringRef> saltString = adoptWK(WKStringCreateWithUTF8CString(salt.utf8().data()));
2382
2383     WKUserMediaPermissionCheckSetUserMediaAccessInfo(checkRequest, saltString.get(), settingsForOrigin(originHash).persistentPermission());
2384 }
2385
2386 void TestController::handleUserMediaPermissionRequest(WKFrameRef frame, WKSecurityOriginRef userMediaDocumentOrigin, WKSecurityOriginRef topLevelDocumentOrigin, WKUserMediaPermissionRequestRef request)
2387 {
2388     auto originHash = userMediaOriginHash(userMediaDocumentOrigin, topLevelDocumentOrigin);
2389     m_userMediaPermissionRequests.append(std::make_pair(originHash, request));
2390     decidePolicyForUserMediaPermissionRequestIfPossible();
2391 }
2392
2393 OriginSettings& TestController::settingsForOrigin(const String& originHash)
2394 {
2395     RefPtr<OriginSettings> settings = m_cachedUserMediaPermissions.get(originHash);
2396     if (!settings) {
2397         settings = adoptRef(*new OriginSettings());
2398         m_cachedUserMediaPermissions.add(originHash, settings);
2399     }
2400
2401     return *settings;
2402 }
2403
2404 unsigned TestController::userMediaPermissionRequestCountForOrigin(WKStringRef userMediaDocumentOriginString, WKStringRef topLevelDocumentOriginString)
2405 {
2406     auto originHash = userMediaOriginHash(userMediaDocumentOriginString, topLevelDocumentOriginString);
2407     return settingsForOrigin(originHash).requestCount();
2408 }
2409
2410 void TestController::resetUserMediaPermissionRequestCountForOrigin(WKStringRef userMediaDocumentOriginString, WKStringRef topLevelDocumentOriginString)
2411 {
2412     auto originHash = userMediaOriginHash(userMediaDocumentOriginString, topLevelDocumentOriginString);
2413     settingsForOrigin(originHash).resetRequestCount();
2414 }
2415
2416 void TestController::decidePolicyForUserMediaPermissionRequestIfPossible()
2417 {
2418     if (!m_isUserMediaPermissionSet)
2419         return;
2420
2421     for (auto& pair : m_userMediaPermissionRequests) {
2422         auto originHash = pair.first;
2423         auto request = pair.second.get();
2424
2425         auto& settings = settingsForOrigin(originHash);
2426         settings.incrementRequestCount();
2427
2428         if (!m_isUserMediaPermissionAllowed && !settings.persistentPermission()) {
2429             WKUserMediaPermissionRequestDeny(request, kWKPermissionDenied);
2430             continue;
2431         }
2432
2433         WKRetainPtr<WKArrayRef> audioDeviceUIDs = adoptWK(WKUserMediaPermissionRequestAudioDeviceUIDs(request));
2434         WKRetainPtr<WKArrayRef> videoDeviceUIDs = adoptWK(WKUserMediaPermissionRequestVideoDeviceUIDs(request));
2435
2436         if (!WKArrayGetSize(videoDeviceUIDs.get()) && !WKArrayGetSize(audioDeviceUIDs.get())) {
2437             WKUserMediaPermissionRequestDeny(request, kWKNoConstraints);
2438             continue;
2439         }
2440
2441         WKRetainPtr<WKStringRef> videoDeviceUID;
2442         if (WKArrayGetSize(videoDeviceUIDs.get()))
2443             videoDeviceUID = reinterpret_cast<WKStringRef>(WKArrayGetItemAtIndex(videoDeviceUIDs.get(), 0));
2444         else
2445             videoDeviceUID = adoptWK(WKStringCreateWithUTF8CString(""));
2446
2447         WKRetainPtr<WKStringRef> audioDeviceUID;
2448         if (WKArrayGetSize(audioDeviceUIDs.get()))
2449             audioDeviceUID = reinterpret_cast<WKStringRef>(WKArrayGetItemAtIndex(audioDeviceUIDs.get(), 0));
2450         else
2451             audioDeviceUID = adoptWK(WKStringCreateWithUTF8CString(""));
2452
2453         WKUserMediaPermissionRequestAllow(request, audioDeviceUID.get(), videoDeviceUID.get());
2454     }
2455     m_userMediaPermissionRequests.clear();
2456 }
2457
2458 void TestController::setCustomPolicyDelegate(bool enabled, bool permissive)
2459 {
2460     m_policyDelegateEnabled = enabled;
2461     m_policyDelegatePermissive = permissive;
2462 }
2463
2464 void TestController::decidePolicyForGeolocationPermissionRequestIfPossible()
2465 {
2466     if (!m_isGeolocationPermissionSet)
2467         return;
2468
2469     for (size_t i = 0; i < m_geolocationPermissionRequests.size(); ++i) {
2470         WKGeolocationPermissionRequestRef permissionRequest = m_geolocationPermissionRequests[i].get();
2471         if (m_isGeolocationPermissionAllowed)
2472             WKGeolocationPermissionRequestAllow(permissionRequest);
2473         else
2474             WKGeolocationPermissionRequestDeny(permissionRequest);
2475     }
2476     m_geolocationPermissionRequests.clear();
2477 }
2478
2479 void TestController::decidePolicyForNotificationPermissionRequest(WKPageRef page, WKSecurityOriginRef origin, WKNotificationPermissionRequestRef request, const void*)
2480 {
2481     TestController::singleton().decidePolicyForNotificationPermissionRequest(page, origin, request);
2482 }
2483
2484 void TestController::decidePolicyForNotificationPermissionRequest(WKPageRef, WKSecurityOriginRef, WKNotificationPermissionRequestRef request)
2485 {
2486     WKNotificationPermissionRequestAllow(request);
2487 }
2488
2489 void TestController::unavailablePluginButtonClicked(WKPageRef, WKPluginUnavailabilityReason, WKDictionaryRef, const void*)
2490 {
2491     printf("MISSING PLUGIN BUTTON PRESSED\n");
2492 }
2493
2494 void TestController::decidePolicyForNavigationAction(WKPageRef, WKNavigationActionRef navigationAction, WKFramePolicyListenerRef listener, WKTypeRef, const void* clientInfo)
2495 {
2496     static_cast<TestController*>(const_cast<void*>(clientInfo))->decidePolicyForNavigationAction(listener);
2497 }
2498
2499 void TestController::decidePolicyForNavigationAction(WKFramePolicyListenerRef listener)
2500 {
2501     WKRetainPtr<WKFramePolicyListenerRef> retainedListener { listener };
2502     const bool shouldIgnore { m_policyDelegateEnabled && !m_policyDelegatePermissive };
2503     auto decisionFunction = [shouldIgnore, retainedListener]() {
2504         if (shouldIgnore)
2505             WKFramePolicyListenerIgnore(retainedListener.get());
2506         else
2507             WKFramePolicyListenerUse(retainedListener.get());
2508     };
2509
2510     if (m_shouldDecideNavigationPolicyAfterDelay)
2511         RunLoop::main().dispatch(WTFMove(decisionFunction));
2512     else
2513         decisionFunction();
2514 }
2515
2516 void TestController::decidePolicyForNavigationResponse(WKPageRef, WKNavigationResponseRef navigationResponse, WKFramePolicyListenerRef listener, WKTypeRef, const void* clientInfo)
2517 {
2518     static_cast<TestController*>(const_cast<void*>(clientInfo))->decidePolicyForNavigationResponse(navigationResponse, listener);
2519 }
2520
2521 void TestController::decidePolicyForNavigationResponse(WKNavigationResponseRef navigationResponse, WKFramePolicyListenerRef listener)
2522 {
2523     WKRetainPtr<WKNavigationResponseRef> retainedNavigationResponse { navigationResponse };
2524     WKRetainPtr<WKFramePolicyListenerRef> retainedListener { listener };
2525
2526     bool shouldDownloadUndisplayableMIMETypes = m_shouldDownloadUndisplayableMIMETypes;
2527     auto decisionFunction = [shouldDownloadUndisplayableMIMETypes, retainedNavigationResponse, retainedListener]() {
2528         // Even though Response was already checked by WKBundlePagePolicyClient, the check did not include plugins
2529         // so we have to re-check again.
2530         if (WKNavigationResponseCanShowMIMEType(retainedNavigationResponse.get())) {
2531             WKFramePolicyListenerUse(retainedListener.get());
2532             return;
2533         }
2534
2535         if (shouldDownloadUndisplayableMIMETypes)
2536             WKFramePolicyListenerDownload(retainedListener.get());
2537         else
2538             WKFramePolicyListenerIgnore(retainedListener.get());
2539     };
2540
2541     if (m_shouldDecideResponsePolicyAfterDelay)
2542         RunLoop::main().dispatch(WTFMove(decisionFunction));
2543     else
2544         decisionFunction();
2545 }
2546
2547 void TestController::didNavigateWithNavigationData(WKContextRef, WKPageRef, WKNavigationDataRef navigationData, WKFrameRef frame, const void* clientInfo)
2548 {
2549     static_cast<TestController*>(const_cast<void*>(clientInfo))->didNavigateWithNavigationData(navigationData, frame);
2550 }
2551
2552 void TestController::didNavigateWithNavigationData(WKNavigationDataRef navigationData, WKFrameRef)
2553 {
2554     if (m_state != RunningTest)
2555         return;
2556
2557     if (!m_shouldLogHistoryClientCallbacks)
2558         return;
2559
2560     // URL
2561     WKRetainPtr<WKURLRef> urlWK = adoptWK(WKNavigationDataCopyURL(navigationData));
2562     WKRetainPtr<WKStringRef> urlStringWK = adoptWK(WKURLCopyString(urlWK.get()));
2563     // Title
2564     WKRetainPtr<WKStringRef> titleWK = adoptWK(WKNavigationDataCopyTitle(navigationData));
2565     // HTTP method
2566     WKRetainPtr<WKURLRequestRef> requestWK = adoptWK(WKNavigationDataCopyOriginalRequest(navigationData));
2567     WKRetainPtr<WKStringRef> methodWK = adoptWK(WKURLRequestCopyHTTPMethod(requestWK.get()));
2568
2569     // FIXME: Determine whether the navigation was successful / a client redirect rather than hard-coding the message here.
2570     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",
2571         toSTD(urlStringWK).c_str(), toSTD(titleWK).c_str(), toSTD(methodWK).c_str()));
2572 }
2573
2574 void TestController::didPerformClientRedirect(WKContextRef, WKPageRef, WKURLRef sourceURL, WKURLRef destinationURL, WKFrameRef frame, const void* clientInfo)
2575 {
2576     static_cast<TestController*>(const_cast<void*>(clientInfo))->didPerformClientRedirect(sourceURL, destinationURL, frame);
2577 }
2578
2579 void TestController::didPerformClientRedirect(WKURLRef sourceURL, WKURLRef destinationURL, WKFrameRef)
2580 {
2581     if (m_state != RunningTest)
2582         return;
2583
2584     if (!m_shouldLogHistoryClientCallbacks)
2585         return;
2586
2587     WKRetainPtr<WKStringRef> sourceStringWK = adoptWK(WKURLCopyString(sourceURL));
2588     WKRetainPtr<WKStringRef> destinationStringWK = adoptWK(WKURLCopyString(destinationURL));
2589
2590     m_currentInvocation->outputText(String::format("WebView performed a client redirect from \"%s\" to \"%s\".\n", toSTD(sourceStringWK).c_str(), toSTD(destinationStringWK).c_str()));
2591 }
2592
2593 void TestController::didPerformServerRedirect(WKContextRef, WKPageRef, WKURLRef sourceURL, WKURLRef destinationURL, WKFrameRef frame, const void* clientInfo)
2594 {
2595     static_cast<TestController*>(const_cast<void*>(clientInfo))->didPerformServerRedirect(sourceURL, destinationURL, frame);
2596 }
2597
2598 void TestController::didPerformServerRedirect(WKURLRef sourceURL, WKURLRef destinationURL, WKFrameRef)
2599 {
2600     if (m_state != RunningTest)
2601         return;
2602
2603     if (!m_shouldLogHistoryClientCallbacks)
2604         return;
2605
2606     WKRetainPtr<WKStringRef> sourceStringWK = adoptWK(WKURLCopyString(sourceURL));
2607     WKRetainPtr<WKStringRef> destinationStringWK = adoptWK(WKURLCopyString(destinationURL));
2608
2609     m_currentInvocation->outputText(String::format("WebView performed a server redirect from \"%s\" to \"%s\".\n", toSTD(sourceStringWK).c_str(), toSTD(destinationStringWK).c_str()));
2610 }
2611
2612 void TestController::didUpdateHistoryTitle(WKContextRef, WKPageRef, WKStringRef title, WKURLRef URL, WKFrameRef frame, const void* clientInfo)
2613 {
2614     static_cast<TestController*>(const_cast<void*>(clientInfo))->didUpdateHistoryTitle(title, URL, frame);
2615 }
2616
2617 void TestController::didUpdateHistoryTitle(WKStringRef title, WKURLRef URL, WKFrameRef)
2618 {
2619     if (m_state != RunningTest)
2620         return;
2621
2622     if (!m_shouldLogHistoryClientCallbacks)
2623         return;
2624
2625     WKRetainPtr<WKStringRef> urlStringWK(AdoptWK, WKURLCopyString(URL));
2626     m_currentInvocation->outputText(String::format("WebView updated the title for history URL \"%s\" to \"%s\".\n", toSTD(urlStringWK).c_str(), toSTD(title).c_str()));
2627 }
2628
2629 void TestController::setNavigationGesturesEnabled(bool value)
2630 {
2631     m_mainWebView->setNavigationGesturesEnabled(value);
2632 }
2633
2634 void TestController::setIgnoresViewportScaleLimits(bool ignoresViewportScaleLimits)
2635 {
2636     WKPageSetIgnoresViewportScaleLimits(m_mainWebView->page(), ignoresViewportScaleLimits);
2637 }
2638
2639 void TestController::terminateNetworkProcess()
2640 {
2641     WKContextTerminateNetworkProcess(platformContext());
2642 }
2643
2644 void TestController::terminateServiceWorkerProcess()
2645 {
2646     WKContextTerminateServiceWorkerProcess(platformContext());
2647 }
2648
2649 #if !PLATFORM(COCOA)
2650 void TestController::platformWillRunTest(const TestInvocation&)
2651 {
2652 }
2653
2654 void TestController::platformCreateWebView(WKPageConfigurationRef configuration, const TestOptions& options)
2655 {
2656     m_mainWebView = std::make_unique<PlatformWebView>(configuration, options);
2657 }
2658
2659 PlatformWebView* TestController::platformCreateOtherPage(PlatformWebView* parentView, WKPageConfigurationRef configuration, const TestOptions& options)
2660 {
2661     return new PlatformWebView(configuration, options);
2662 }
2663
2664 WKContextRef TestController::platformAdjustContext(WKContextRef context, WKContextConfigurationRef contextConfiguration)
2665 {
2666     auto* dataStore = WKContextGetWebsiteDataStore(context);
2667     WKWebsiteDataStoreSetResourceLoadStatisticsEnabled(dataStore, true);
2668
2669     if (const char* dumpRenderTreeTemp = libraryPathForTesting()) {
2670         String temporaryFolder = String::fromUTF8(dumpRenderTreeTemp);
2671         const char separator = '/';
2672
2673         WKWebsiteDataStoreSetServiceWorkerRegistrationDirectory(dataStore, toWK(temporaryFolder + separator + "ServiceWorkers").get());
2674     }
2675
2676     return context;
2677 }
2678
2679 void TestController::platformResetStateToConsistentValues(const TestOptions&)
2680 {
2681 }
2682
2683 unsigned TestController::imageCountInGeneralPasteboard() const
2684 {
2685     return 0;
2686 }
2687
2688 void TestController::removeAllSessionCredentials()
2689 {
2690 }
2691
2692 void TestController::getAllStorageAccessEntries()
2693 {
2694 }
2695
2696 #endif
2697
2698 struct ClearServiceWorkerRegistrationsCallbackContext {
2699     explicit ClearServiceWorkerRegistrationsCallbackContext(TestController& controller)
2700         : testController(controller)
2701     {
2702     }
2703
2704     TestController& testController;
2705     bool done { false };
2706 };
2707
2708 static void clearServiceWorkerRegistrationsCallback(void* userData)
2709 {
2710     auto* context = static_cast<ClearServiceWorkerRegistrationsCallbackContext*>(userData);
2711     context->done = true;
2712     context->testController.notifyDone();
2713 }
2714
2715 void TestController::clearServiceWorkerRegistrations()
2716 {
2717     auto websiteDataStore = WKContextGetWebsiteDataStore(platformContext());
2718     ClearServiceWorkerRegistrationsCallbackContext context(*this);
2719
2720     WKWebsiteDataStoreRemoveAllServiceWorkerRegistrations(websiteDataStore, &context, clearServiceWorkerRegistrationsCallback);
2721     runUntil(context.done, noTimeout);
2722 }
2723
2724 struct ClearDOMCacheCallbackContext {
2725     explicit ClearDOMCacheCallbackContext(TestController& controller)
2726         : testController(controller)
2727     {
2728     }
2729
2730     TestController& testController;
2731     bool done { false };
2732 };
2733
2734 static void clearDOMCacheCallback(void* userData)
2735 {
2736     auto* context = static_cast<ClearDOMCacheCallbackContext*>(userData);
2737     context->done = true;
2738     context->testController.notifyDone();
2739 }
2740
2741 void TestController::clearDOMCache(WKStringRef origin)
2742 {
2743     auto websiteDataStore = WKContextGetWebsiteDataStore(platformContext());
2744     ClearDOMCacheCallbackContext context(*this);
2745
2746     auto cacheOrigin = adoptWK(WKSecurityOriginCreateFromString(origin));
2747     WKWebsiteDataStoreRemoveFetchCacheForOrigin(websiteDataStore, cacheOrigin.get(), &context, clearDOMCacheCallback);
2748     runUntil(context.done, noTimeout);
2749 }
2750
2751 void TestController::clearDOMCaches()
2752 {
2753     auto websiteDataStore = WKContextGetWebsiteDataStore(platformContext());
2754     ClearDOMCacheCallbackContext context(*this);
2755
2756     WKWebsiteDataStoreRemoveAllFetchCaches(websiteDataStore, &context, clearDOMCacheCallback);
2757     runUntil(context.done, noTimeout);
2758 }
2759
2760 void TestController::setIDBPerOriginQuota(uint64_t quota)
2761 {
2762     WKContextSetIDBPerOriginQuota(platformContext(), quota);
2763 }
2764
2765 struct FetchCacheOriginsCallbackContext {
2766     FetchCacheOriginsCallbackContext(TestController& controller, WKStringRef origin)
2767         : testController(controller)
2768         , origin(origin)
2769     {
2770     }
2771
2772     TestController& testController;
2773     WKStringRef origin;
2774
2775     bool done { false };
2776     bool result { false };
2777 };
2778
2779 static void fetchCacheOriginsCallback(WKArrayRef origins, void* userData)
2780 {
2781     auto* context = static_cast<FetchCacheOriginsCallbackContext*>(userData);
2782     context->done = true;
2783
2784     auto size = WKArrayGetSize(origins);
2785     for (size_t index = 0; index < size && !context->result; ++index) {
2786         WKSecurityOriginRef securityOrigin = reinterpret_cast<WKSecurityOriginRef>(WKArrayGetItemAtIndex(origins, index));
2787         if (WKStringIsEqual(context->origin, adoptWK(WKSecurityOriginCopyToString(securityOrigin)).get()))
2788             context->result = true;
2789     }
2790     context->testController.notifyDone();
2791 }
2792
2793 bool TestController::hasDOMCache(WKStringRef origin)
2794 {
2795     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2796     FetchCacheOriginsCallbackContext context(*this, origin);
2797     WKWebsiteDataStoreGetFetchCacheOrigins(dataStore, &context, fetchCacheOriginsCallback);
2798     runUntil(context.done, noTimeout);
2799     return context.result;
2800 }
2801
2802 struct FetchCacheSizeForOriginCallbackContext {
2803     explicit FetchCacheSizeForOriginCallbackContext(TestController& controller)
2804         : testController(controller)
2805     {
2806     }
2807
2808     TestController& testController;
2809
2810     bool done { false };
2811     uint64_t result { 0 };
2812 };
2813
2814 static void fetchCacheSizeForOriginCallback(uint64_t size, void* userData)
2815 {
2816     auto* context = static_cast<FetchCacheSizeForOriginCallbackContext*>(userData);
2817     context->done = true;
2818     context->result = size;
2819     context->testController.notifyDone();
2820 }
2821
2822 uint64_t TestController::domCacheSize(WKStringRef origin)
2823 {
2824     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2825     FetchCacheSizeForOriginCallbackContext context(*this);
2826     WKWebsiteDataStoreGetFetchCacheSizeForOrigin(dataStore, origin, &context, fetchCacheSizeForOriginCallback);
2827     runUntil(context.done, noTimeout);
2828     return context.result;
2829 }
2830
2831 struct ResourceStatisticsCallbackContext {
2832     explicit ResourceStatisticsCallbackContext(TestController& controller)
2833         : testController(controller)
2834     {
2835     }
2836
2837     TestController& testController;
2838     bool done { false };
2839     bool result { false };
2840     WKRetainPtr<WKStringRef> resourceLoadStatisticsRepresentation;
2841 };
2842     
2843 static void resourceStatisticsStringResultCallback(WKStringRef resourceLoadStatisticsRepresentation, void* userData)
2844 {
2845     auto* context = static_cast<ResourceStatisticsCallbackContext*>(userData);
2846     context->resourceLoadStatisticsRepresentation = resourceLoadStatisticsRepresentation;
2847     context->done = true;
2848     context->testController.notifyDone();
2849 }
2850
2851 static void resourceStatisticsVoidResultCallback(void* userData)
2852 {
2853     auto* context = static_cast<ResourceStatisticsCallbackContext*>(userData);
2854     context->done = true;
2855     context->testController.notifyDone();
2856 }
2857
2858 static void resourceStatisticsBooleanResultCallback(bool result, void* userData)
2859 {
2860     auto* context = static_cast<ResourceStatisticsCallbackContext*>(userData);
2861     context->result = result;
2862     context->done = true;
2863     context->testController.notifyDone();
2864 }
2865
2866 void TestController::setStatisticsDebugMode(bool value)
2867 {
2868     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2869     ResourceStatisticsCallbackContext context(*this);
2870     WKWebsiteDataStoreSetResourceLoadStatisticsDebugModeWithCompletionHandler(dataStore, value, &context, resourceStatisticsVoidResultCallback);
2871     runUntil(context.done, noTimeout);
2872     m_currentInvocation->didSetStatisticsDebugMode();
2873 }
2874
2875 void TestController::setStatisticsPrevalentResourceForDebugMode(WKStringRef hostName)
2876 {
2877     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2878     ResourceStatisticsCallbackContext context(*this);
2879     WKWebsiteDataStoreSetResourceLoadStatisticsPrevalentResourceForDebugMode(dataStore, hostName, &context, resourceStatisticsVoidResultCallback);
2880     runUntil(context.done, noTimeout);
2881     m_currentInvocation->didSetPrevalentResourceForDebugMode();
2882 }
2883
2884 void TestController::setStatisticsLastSeen(WKStringRef host, double seconds)
2885 {
2886     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2887     ResourceStatisticsCallbackContext context(*this);
2888     WKWebsiteDataStoreSetStatisticsLastSeen(dataStore, host, seconds, &context, resourceStatisticsVoidResultCallback);
2889     runUntil(context.done, noTimeout);
2890     m_currentInvocation->didSetLastSeen();
2891 }
2892
2893 void TestController::setStatisticsPrevalentResource(WKStringRef host, bool value)
2894 {
2895     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2896     ResourceStatisticsCallbackContext context(*this);
2897     WKWebsiteDataStoreSetStatisticsPrevalentResource(dataStore, host, value, &context, resourceStatisticsVoidResultCallback);
2898     runUntil(context.done, noTimeout);
2899     m_currentInvocation->didSetPrevalentResource();
2900 }
2901
2902 void TestController::setStatisticsVeryPrevalentResource(WKStringRef host, bool value)
2903 {
2904     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2905     ResourceStatisticsCallbackContext context(*this);
2906     WKWebsiteDataStoreSetStatisticsVeryPrevalentResource(dataStore, host, value, &context, resourceStatisticsVoidResultCallback);
2907     runUntil(context.done, noTimeout);
2908     m_currentInvocation->didSetVeryPrevalentResource();
2909 }
2910     
2911 String TestController::dumpResourceLoadStatistics()
2912 {
2913     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2914     ResourceStatisticsCallbackContext context(*this);
2915     WKWebsiteDataStoreDumpResourceLoadStatistics(dataStore, &context, resourceStatisticsStringResultCallback);
2916     runUntil(context.done, noTimeout);
2917     return toWTFString(context.resourceLoadStatisticsRepresentation.get());
2918 }
2919
2920 bool TestController::isStatisticsPrevalentResource(WKStringRef host)
2921 {
2922     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2923     ResourceStatisticsCallbackContext context(*this);
2924     WKWebsiteDataStoreIsStatisticsPrevalentResource(dataStore, host, &context, resourceStatisticsBooleanResultCallback);
2925     runUntil(context.done, noTimeout);
2926     return context.result;
2927 }
2928
2929 bool TestController::isStatisticsVeryPrevalentResource(WKStringRef host)
2930 {
2931     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2932     ResourceStatisticsCallbackContext context(*this);
2933     WKWebsiteDataStoreIsStatisticsVeryPrevalentResource(dataStore, host, &context, resourceStatisticsBooleanResultCallback);
2934     runUntil(context.done, noTimeout);
2935     return context.result;
2936 }
2937
2938 bool TestController::isStatisticsRegisteredAsSubresourceUnder(WKStringRef subresourceHost, WKStringRef topFrameHost)
2939 {
2940     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2941     ResourceStatisticsCallbackContext context(*this);
2942     WKWebsiteDataStoreIsStatisticsRegisteredAsSubresourceUnder(dataStore, subresourceHost, topFrameHost, &context, resourceStatisticsBooleanResultCallback);
2943     runUntil(context.done, noTimeout);
2944     return context.result;
2945 }
2946
2947 bool TestController::isStatisticsRegisteredAsSubFrameUnder(WKStringRef subFrameHost, WKStringRef topFrameHost)
2948 {
2949     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2950     ResourceStatisticsCallbackContext context(*this);
2951     WKWebsiteDataStoreIsStatisticsRegisteredAsSubFrameUnder(dataStore, subFrameHost, topFrameHost, &context, resourceStatisticsBooleanResultCallback);
2952     runUntil(context.done, noTimeout);
2953     return context.result;
2954 }
2955
2956 bool TestController::isStatisticsRegisteredAsRedirectingTo(WKStringRef hostRedirectedFrom, WKStringRef hostRedirectedTo)
2957 {
2958     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2959     ResourceStatisticsCallbackContext context(*this);
2960     WKWebsiteDataStoreIsStatisticsRegisteredAsRedirectingTo(dataStore, hostRedirectedFrom, hostRedirectedTo, &context, resourceStatisticsBooleanResultCallback);
2961     runUntil(context.done, noTimeout);
2962     return context.result;
2963 }
2964
2965 void TestController::setStatisticsHasHadUserInteraction(WKStringRef host, bool value)
2966 {
2967     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2968     ResourceStatisticsCallbackContext context(*this);
2969     WKWebsiteDataStoreSetStatisticsHasHadUserInteraction(dataStore, host, value, &context, resourceStatisticsVoidResultCallback);
2970     runUntil(context.done, noTimeout);
2971     m_currentInvocation->didSetHasHadUserInteraction();
2972 }
2973
2974 bool TestController::isStatisticsHasHadUserInteraction(WKStringRef host)
2975 {
2976     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2977     ResourceStatisticsCallbackContext context(*this);
2978     WKWebsiteDataStoreIsStatisticsHasHadUserInteraction(dataStore, host, &context, resourceStatisticsBooleanResultCallback);
2979     runUntil(context.done, noTimeout);
2980     return context.result;
2981 }
2982
2983 void TestController::setStatisticsGrandfathered(WKStringRef host, bool value)
2984 {
2985     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2986     WKWebsiteDataStoreSetStatisticsGrandfathered(dataStore, host, value);
2987 }
2988
2989 bool TestController::isStatisticsGrandfathered(WKStringRef host)
2990 {
2991     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2992     ResourceStatisticsCallbackContext context(*this);
2993     WKWebsiteDataStoreIsStatisticsGrandfathered(dataStore, host, &context, resourceStatisticsBooleanResultCallback);
2994     runUntil(context.done, noTimeout);
2995     return context.result;
2996 }
2997
2998 void TestController::setStatisticsSubframeUnderTopFrameOrigin(WKStringRef host, WKStringRef topFrameHost)
2999 {
3000     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3001     WKWebsiteDataStoreSetStatisticsSubframeUnderTopFrameOrigin(dataStore, host, topFrameHost);
3002 }
3003
3004 void TestController::setStatisticsSubresourceUnderTopFrameOrigin(WKStringRef host, WKStringRef topFrameHost)
3005 {
3006     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3007     WKWebsiteDataStoreSetStatisticsSubresourceUnderTopFrameOrigin(dataStore, host, topFrameHost);
3008 }
3009
3010 void TestController::setStatisticsSubresourceUniqueRedirectTo(WKStringRef host, WKStringRef hostRedirectedTo)
3011 {
3012     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3013     WKWebsiteDataStoreSetStatisticsSubresourceUniqueRedirectTo(dataStore, host, hostRedirectedTo);
3014 }
3015
3016 void TestController::setStatisticsSubresourceUniqueRedirectFrom(WKStringRef host, WKStringRef hostRedirectedFrom)
3017 {
3018     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3019     WKWebsiteDataStoreSetStatisticsSubresourceUniqueRedirectFrom(dataStore, host, hostRedirectedFrom);
3020 }
3021
3022 void TestController::setStatisticsTopFrameUniqueRedirectTo(WKStringRef host, WKStringRef hostRedirectedTo)
3023 {
3024     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3025     WKWebsiteDataStoreSetStatisticsTopFrameUniqueRedirectTo(dataStore, host, hostRedirectedTo);
3026 }
3027
3028 void TestController::setStatisticsTopFrameUniqueRedirectFrom(WKStringRef host, WKStringRef hostRedirectedFrom)
3029 {
3030     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3031     WKWebsiteDataStoreSetStatisticsTopFrameUniqueRedirectFrom(dataStore, host, hostRedirectedFrom);
3032 }
3033
3034 void TestController::setStatisticsTimeToLiveUserInteraction(double seconds)
3035 {
3036     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3037     WKWebsiteDataStoreSetStatisticsTimeToLiveUserInteraction(dataStore, seconds);
3038 }
3039
3040 void TestController::statisticsProcessStatisticsAndDataRecords()
3041 {
3042     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3043     WKWebsiteDataStoreStatisticsProcessStatisticsAndDataRecords(dataStore);
3044 }
3045
3046 void TestController::statisticsUpdateCookieBlocking()
3047 {
3048     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3049     ResourceStatisticsCallbackContext context(*this);
3050     WKWebsiteDataStoreStatisticsUpdateCookieBlocking(dataStore, &context, resourceStatisticsVoidResultCallback);
3051     runUntil(context.done, noTimeout);
3052     m_currentInvocation->didSetBlockCookiesForHost();
3053 }
3054
3055 void TestController::statisticsSubmitTelemetry()
3056 {
3057     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3058     WKWebsiteDataStoreStatisticsSubmitTelemetry(dataStore);
3059 }
3060
3061 void TestController::setStatisticsNotifyPagesWhenDataRecordsWereScanned(bool value)
3062 {
3063     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3064     WKWebsiteDataStoreSetStatisticsNotifyPagesWhenDataRecordsWereScanned(dataStore, value);
3065 }
3066
3067 void TestController::setStatisticsShouldClassifyResourcesBeforeDataRecordsRemoval(bool value)
3068 {
3069     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3070     WKWebsiteDataStoreSetStatisticsShouldClassifyResourcesBeforeDataRecordsRemoval(dataStore, value);
3071 }
3072
3073 void TestController::setStatisticsNotifyPagesWhenTelemetryWasCaptured(bool value)
3074 {
3075     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3076     WKWebsiteDataStoreSetStatisticsNotifyPagesWhenTelemetryWasCaptured(dataStore, value);
3077 }
3078
3079 void TestController::setStatisticsMinimumTimeBetweenDataRecordsRemoval(double seconds)
3080 {
3081     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3082     WKWebsiteDataStoreSetStatisticsMinimumTimeBetweenDataRecordsRemoval(dataStore, seconds);
3083 }
3084
3085 void TestController::setStatisticsGrandfatheringTime(double seconds)
3086 {
3087     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3088     WKWebsiteDataStoreSetStatisticsGrandfatheringTime(dataStore, seconds);
3089 }
3090
3091 void TestController::setStatisticsMaxStatisticsEntries(unsigned entries)
3092 {
3093     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3094     WKWebsiteDataStoreSetStatisticsMaxStatisticsEntries(dataStore, entries);
3095 }
3096
3097 void TestController::setStatisticsPruneEntriesDownTo(unsigned entries)
3098 {
3099     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3100     WKWebsiteDataStoreSetStatisticsPruneEntriesDownTo(dataStore, entries);
3101 }
3102
3103 void TestController::statisticsClearInMemoryAndPersistentStore()
3104 {
3105     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3106     ResourceStatisticsCallbackContext context(*this);
3107     WKWebsiteDataStoreStatisticsClearInMemoryAndPersistentStore(dataStore, &context, resourceStatisticsVoidResultCallback);
3108     runUntil(context.done, noTimeout);
3109     m_currentInvocation->didClearStatisticsThroughWebsiteDataRemoval();
3110 }
3111
3112 void TestController::statisticsClearInMemoryAndPersistentStoreModifiedSinceHours(unsigned hours)
3113 {
3114     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3115     ResourceStatisticsCallbackContext context(*this);
3116     WKWebsiteDataStoreStatisticsClearInMemoryAndPersistentStoreModifiedSinceHours(dataStore, hours, &context, resourceStatisticsVoidResultCallback);
3117     runUntil(context.done, noTimeout);
3118     m_currentInvocation->didClearStatisticsThroughWebsiteDataRemoval();
3119 }
3120
3121 void TestController::statisticsClearThroughWebsiteDataRemoval()
3122 {
3123     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3124     ResourceStatisticsCallbackContext context(*this);
3125     WKWebsiteDataStoreStatisticsClearThroughWebsiteDataRemoval(dataStore, &context, resourceStatisticsVoidResultCallback);
3126     runUntil(context.done, noTimeout);
3127     m_currentInvocation->didClearStatisticsThroughWebsiteDataRemoval();
3128 }
3129
3130 void TestController::setStatisticsCacheMaxAgeCap(double seconds)
3131 {
3132     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3133     ResourceStatisticsCallbackContext context(*this);
3134     WKWebsiteDataStoreSetStatisticsCacheMaxAgeCap(dataStore, seconds, &context, resourceStatisticsVoidResultCallback);
3135     runUntil(context.done, noTimeout);
3136 }
3137
3138 void TestController::statisticsResetToConsistentState()
3139 {
3140     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3141     ResourceStatisticsCallbackContext context(*this);
3142     WKWebsiteDataStoreStatisticsResetToConsistentState(dataStore, &context, resourceStatisticsVoidResultCallback);
3143     runUntil(context.done, noTimeout);
3144     m_currentInvocation->didResetStatisticsToConsistentState();
3145 }
3146
3147 void TestController::addMockMediaDevice(WKStringRef persistentID, WKStringRef label, WKStringRef type)
3148 {
3149     WKAddMockMediaDevice(platformContext(), persistentID, label, type);
3150 }
3151
3152 void TestController::clearMockMediaDevices()
3153 {
3154     WKClearMockMediaDevices(platformContext());
3155 }
3156
3157 void TestController::removeMockMediaDevice(WKStringRef persistentID)
3158 {
3159     WKRemoveMockMediaDevice(platformContext(), persistentID);
3160 }
3161
3162 void TestController::resetMockMediaDevices()
3163 {
3164     WKResetMockMediaDevices(platformContext());
3165 }
3166
3167 #if !PLATFORM(COCOA)
3168 void TestController::platformAddTestOptions(TestOptions&) const
3169 {
3170 }
3171
3172 void TestController::injectUserScript(WKStringRef)
3173 {
3174 }
3175
3176 void TestController::addTestKeyToKeychain(const String&, const String&, const String&)
3177 {
3178 }
3179
3180 void TestController::cleanUpKeychain(const String&)
3181 {
3182 }
3183
3184 bool TestController::keyExistsInKeychain(const String&, const String&)
3185 {
3186     return false;
3187 }
3188 #endif
3189
3190 void TestController::sendDisplayConfigurationChangedMessageForTesting()
3191 {
3192     WKSendDisplayConfigurationChangedMessageForTesting(platformContext());
3193 }
3194
3195 void TestController::setWebAuthenticationMockConfiguration(WKDictionaryRef configuration)
3196 {
3197     WKWebsiteDataStoreSetWebAuthenticationMockConfiguration(WKContextGetWebsiteDataStore(platformContext()), configuration);
3198 }
3199
3200 } // namespace WTR