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