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