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