Clean up IndexedDB files between tests
[WebKit-https.git] / Tools / WebKitTestRunner / TestController.cpp
1 /*
2  * Copyright (C) 2010-2018 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "TestController.h"
28
29 #include "EventSenderProxy.h"
30 #include "Options.h"
31 #include "PlatformWebView.h"
32 #include "StringFunctions.h"
33 #include "TestInvocation.h"
34 #include "WebCoreTestSupport.h"
35 #include <JavaScriptCore/InitializeThreading.h>
36 #include <WebKit/WKArray.h>
37 #include <WebKit/WKAuthenticationChallenge.h>
38 #include <WebKit/WKAuthenticationDecisionListener.h>
39 #include <WebKit/WKContextConfigurationRef.h>
40 #include <WebKit/WKContextPrivate.h>
41 #include <WebKit/WKCookieManager.h>
42 #include <WebKit/WKCredential.h>
43 #include <WebKit/WKFrameHandleRef.h>
44 #include <WebKit/WKFrameInfoRef.h>
45 #include <WebKit/WKIconDatabase.h>
46 #include <WebKit/WKMockDisplay.h>
47 #include <WebKit/WKMockMediaDevice.h>
48 #include <WebKit/WKNavigationResponseRef.h>
49 #include <WebKit/WKNotification.h>
50 #include <WebKit/WKNotificationManager.h>
51 #include <WebKit/WKNotificationPermissionRequest.h>
52 #include <WebKit/WKNumber.h>
53 #include <WebKit/WKOpenPanelResultListener.h>
54 #include <WebKit/WKPageGroup.h>
55 #include <WebKit/WKPageInjectedBundleClient.h>
56 #include <WebKit/WKPagePrivate.h>
57 #include <WebKit/WKPluginInformation.h>
58 #include <WebKit/WKPreferencesRefPrivate.h>
59 #include <WebKit/WKProtectionSpace.h>
60 #include <WebKit/WKRetainPtr.h>
61 #include <WebKit/WKSecurityOriginRef.h>
62 #include <WebKit/WKTextChecker.h>
63 #include <WebKit/WKUserMediaPermissionCheck.h>
64 #include <WebKit/WKWebsiteDataStoreRef.h>
65 #include <algorithm>
66 #include <cstdio>
67 #include <ctype.h>
68 #include <fstream>
69 #include <stdlib.h>
70 #include <string>
71 #include <wtf/AutodrainedPool.h>
72 #include <wtf/CryptographicallyRandomNumber.h>
73 #include <wtf/HexNumber.h>
74 #include <wtf/MainThread.h>
75 #include <wtf/ProcessPrivilege.h>
76 #include <wtf/RefCounted.h>
77 #include <wtf/RunLoop.h>
78 #include <wtf/SetForScope.h>
79 #include <wtf/UUID.h>
80 #include <wtf/text/CString.h>
81 #include <wtf/text/WTFString.h>
82
83 #if PLATFORM(COCOA)
84 #include <WebKit/WKContextPrivateMac.h>
85 #include <WebKit/WKPagePrivateMac.h>
86 #endif
87
88 #if PLATFORM(WIN)
89 #include <direct.h>
90 #define getcwd _getcwd
91 #define PATH_MAX _MAX_PATH
92 #else
93 #include <unistd.h>
94 #endif
95
96 namespace WTR {
97
98 const unsigned TestController::viewWidth = 800;
99 const unsigned TestController::viewHeight = 600;
100
101 const unsigned TestController::w3cSVGViewWidth = 480;
102 const unsigned TestController::w3cSVGViewHeight = 360;
103
104 const WTF::Seconds TestController::defaultShortTimeout = 5_s;
105 const WTF::Seconds TestController::noTimeout = -1_s;
106
107 static WKURLRef blankURL()
108 {
109     static WKURLRef staticBlankURL = WKURLCreateWithUTF8CString("about:blank");
110     return staticBlankURL;
111 }
112
113 static WKDataRef copyWebCryptoMasterKey(WKPageRef, const void*)
114 {
115     // Any 128 bit key would do, all we need for testing is to implement the callback.
116     return WKDataCreate((const uint8_t*)"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f", 16);
117 }
118
119 static WKStringRef copySignedPublicKeyAndChallengeString(WKPageRef, const void*)
120 {
121     // Any fake response would do, all we need for testing is to implement the callback.
122     return WKStringCreateWithUTF8CString("MIHFMHEwXDANBgkqhkiG9w0BAQEFAANLADBIAkEAnX0TILJrOMUue%2BPtwBRE6XfV%0AWtKQbsshxk5ZhcUwcwyvcnIq9b82QhJdoACdD34rqfCAIND46fXKQUnb0mvKzQID%0AAQABFhFNb3ppbGxhSXNNeUZyaWVuZDANBgkqhkiG9w0BAQQFAANBAAKv2Eex2n%2FS%0Ar%2F7iJNroWlSzSMtTiQTEB%2BADWHGj9u1xrUrOilq%2Fo2cuQxIfZcNZkYAkWP4DubqW%0Ai0%2F%2FrgBvmco%3D");
123 }
124
125 AsyncTask* AsyncTask::m_currentTask;
126
127 bool AsyncTask::run()
128 {
129     m_currentTask = this;
130     m_task();
131     TestController::singleton().runUntil(m_taskDone, m_timeout);
132     m_currentTask = nullptr;
133     return m_taskDone;
134 }
135
136 AsyncTask* AsyncTask::currentTask()
137 {
138     return m_currentTask;
139 }
140
141 static TestController* controller;
142
143 TestController& TestController::singleton()
144 {
145     ASSERT(controller);
146     return *controller;
147 }
148
149 TestController::TestController(int argc, const char* argv[])
150 {
151     initialize(argc, argv);
152     controller = this;
153     run();
154     controller = nullptr;
155 }
156
157 TestController::~TestController()
158 {
159     // The context will be null if WebKitTestRunner was in server mode, but ran no tests.
160     if (m_context)
161         WKIconDatabaseClose(WKContextGetIconDatabase(m_context.get()));
162
163     platformDestroy();
164 }
165
166 static WKRect getWindowFrame(WKPageRef page, const void* clientInfo)
167 {
168     PlatformWebView* view = static_cast<PlatformWebView*>(const_cast<void*>(clientInfo));
169     return view->windowFrame();
170 }
171
172 static void setWindowFrame(WKPageRef page, WKRect frame, const void* clientInfo)
173 {
174     PlatformWebView* view = static_cast<PlatformWebView*>(const_cast<void*>(clientInfo));
175     view->setWindowFrame(frame);
176 }
177
178 static bool runBeforeUnloadConfirmPanel(WKPageRef page, WKStringRef message, WKFrameRef frame, const void*)
179 {
180     printf("CONFIRM NAVIGATION: %s\n", toSTD(message).c_str());
181     return TestController::singleton().beforeUnloadReturnValue();
182 }
183
184 static void runOpenPanel(WKPageRef page, WKFrameRef frame, WKOpenPanelParametersRef parameters, WKOpenPanelResultListenerRef resultListenerRef, const void*)
185 {
186     printf("OPEN FILE PANEL\n");
187     if (WKOpenPanelParametersGetAllowsDirectories(parameters))
188         printf("-> DIRECTORIES ARE ALLOWED\n");
189     WKArrayRef fileURLs = TestController::singleton().openPanelFileURLs();
190     if (!fileURLs || !WKArrayGetSize(fileURLs)) {
191         WKOpenPanelResultListenerCancel(resultListenerRef);
192         return;
193     }
194
195     if (WKOpenPanelParametersGetAllowsMultipleFiles(parameters)) {
196         WKOpenPanelResultListenerChooseFiles(resultListenerRef, fileURLs);
197         return;
198     }
199
200     WKTypeRef firstItem = WKArrayGetItemAtIndex(fileURLs, 0);
201     WKOpenPanelResultListenerChooseFiles(resultListenerRef, adoptWK(WKArrayCreate(&firstItem, 1)).get());
202 }
203
204 void TestController::runModal(WKPageRef page, const void* clientInfo)
205 {
206     PlatformWebView* view = static_cast<PlatformWebView*>(const_cast<void*>(clientInfo));
207     view->setWindowIsKey(false);
208     runModal(view);
209     view->setWindowIsKey(true);
210 }
211
212 static void closeOtherPage(WKPageRef page, const void* clientInfo)
213 {
214     WKPageClose(page);
215     PlatformWebView* view = static_cast<PlatformWebView*>(const_cast<void*>(clientInfo));
216     delete view;
217 }
218
219 static void focus(WKPageRef page, const void* clientInfo)
220 {
221     PlatformWebView* view = static_cast<PlatformWebView*>(const_cast<void*>(clientInfo));
222     view->focus();
223     view->setWindowIsKey(true);
224 }
225
226 static void unfocus(WKPageRef page, const void* clientInfo)
227 {
228     PlatformWebView* view = static_cast<PlatformWebView*>(const_cast<void*>(clientInfo));
229     view->setWindowIsKey(false);
230 }
231
232 static void decidePolicyForGeolocationPermissionRequest(WKPageRef, WKFrameRef, WKSecurityOriginRef, WKGeolocationPermissionRequestRef permissionRequest, const void* clientInfo)
233 {
234     TestController::singleton().handleGeolocationPermissionRequest(permissionRequest);
235 }
236
237 static void decidePolicyForUserMediaPermissionRequest(WKPageRef, WKFrameRef frame, WKSecurityOriginRef userMediaDocumentOrigin, WKSecurityOriginRef topLevelDocumentOrigin, WKUserMediaPermissionRequestRef permissionRequest, const void* clientInfo)
238 {
239     TestController::singleton().handleUserMediaPermissionRequest(frame, userMediaDocumentOrigin, topLevelDocumentOrigin, permissionRequest);
240 }
241
242 static void checkUserMediaPermissionForOrigin(WKPageRef, WKFrameRef frame, WKSecurityOriginRef userMediaDocumentOrigin, WKSecurityOriginRef topLevelDocumentOrigin, WKUserMediaPermissionCheckRef checkRequest, const void*)
243 {
244     TestController::singleton().handleCheckOfUserMediaPermissionForOrigin(frame, userMediaDocumentOrigin, topLevelDocumentOrigin, checkRequest);
245 }
246
247 static void requestPointerLock(WKPageRef page, const void*)
248 {
249     WKPageDidAllowPointerLock(page);
250 }
251
252 WKPageRef TestController::createOtherPage(WKPageRef, WKPageConfigurationRef configuration, WKNavigationActionRef navigationAction, WKWindowFeaturesRef windowFeatures, const void *clientInfo)
253 {
254     PlatformWebView* parentView = static_cast<PlatformWebView*>(const_cast<void*>(clientInfo));
255     return TestController::singleton().createOtherPage(parentView, configuration, navigationAction, windowFeatures);
256 }
257
258 WKPageRef TestController::createOtherPage(PlatformWebView* parentView, WKPageConfigurationRef configuration, WKNavigationActionRef navigationAction, WKWindowFeaturesRef windowFeatures)
259 {
260     // The test needs to call testRunner.setCanOpenWindows() to open new windows.
261     if (!m_currentInvocation->canOpenWindows())
262         return nullptr;
263
264     PlatformWebView* view = platformCreateOtherPage(parentView, configuration, parentView->options());
265     WKPageRef newPage = view->page();
266
267     view->resizeTo(800, 600);
268
269     WKPageUIClientV8 otherPageUIClient = {
270         { 8, view },
271         0, // createNewPage_deprecatedForUseWithV0
272         0, // showPage
273         closeOtherPage,
274         0, // takeFocus
275         focus,
276         unfocus,
277         0, // runJavaScriptAlert_deprecatedForUseWithV0
278         0, // runJavaScriptAlert_deprecatedForUseWithV0
279         0, // runJavaScriptAlert_deprecatedForUseWithV0
280         0, // setStatusText
281         0, // mouseDidMoveOverElement_deprecatedForUseWithV0
282         0, // missingPluginButtonClicked
283         0, // didNotHandleKeyEvent
284         0, // didNotHandleWheelEvent
285         0, // toolbarsAreVisible
286         0, // setToolbarsAreVisible
287         0, // menuBarIsVisible
288         0, // setMenuBarIsVisible
289         0, // statusBarIsVisible
290         0, // setStatusBarIsVisible
291         0, // isResizable
292         0, // setIsResizable
293         getWindowFrame,
294         setWindowFrame,
295         runBeforeUnloadConfirmPanel,
296         0, // didDraw
297         0, // pageDidScroll
298         0, // exceededDatabaseQuota
299         runOpenPanel,
300         decidePolicyForGeolocationPermissionRequest,
301         0, // headerHeight
302         0, // footerHeight
303         0, // drawHeader
304         0, // drawFooter
305         0, // printFrame
306         runModal,
307         0, // didCompleteRubberBandForMainFrame
308         0, // saveDataToFileInDownloadsFolder
309         0, // shouldInterruptJavaScript
310         0, // createNewPage_deprecatedForUseWithV1
311         0, // mouseDidMoveOverElement
312         0, // decidePolicyForNotificationPermissionRequest
313         0, // unavailablePluginButtonClicked_deprecatedForUseWithV1
314         0, // showColorPicker
315         0, // hideColorPicker
316         0, // unavailablePluginButtonClicked
317         0, // pinnedStateDidChange
318         0, // didBeginTrackingPotentialLongMousePress
319         0, // didRecognizeLongMousePress
320         0, // didCancelTrackingPotentialLongMousePress
321         0, // isPlayingAudioDidChange
322         decidePolicyForUserMediaPermissionRequest,
323         0, // didClickAutofillButton
324         0, // runJavaScriptAlert
325         0, // runJavaScriptConfirm
326         0, // runJavaScriptPrompt
327         0, // mediaSessionMetadataDidChange
328         createOtherPage,
329         0, // runJavaScriptAlert
330         0, // runJavaScriptConfirm
331         0, // runJavaScriptPrompt
332         checkUserMediaPermissionForOrigin,
333         0, // runBeforeUnloadConfirmPanel
334         0, // fullscreenMayReturnToInline
335         requestPointerLock,
336         0,
337     };
338     WKPageSetPageUIClient(newPage, &otherPageUIClient.base);
339     
340     WKPageNavigationClientV3 pageNavigationClient = {
341         { 3, &TestController::singleton() },
342         decidePolicyForNavigationAction,
343         decidePolicyForNavigationResponse,
344         decidePolicyForPluginLoad,
345         0, // didStartProvisionalNavigation
346         didReceiveServerRedirectForProvisionalNavigation,
347         0, // didFailProvisionalNavigation
348         0, // didCommitNavigation
349         0, // didFinishNavigation
350         0, // didFailNavigation
351         0, // didFailProvisionalLoadInSubframe
352         0, // didFinishDocumentLoad
353         0, // didSameDocumentNavigation
354         0, // renderingProgressDidChange
355         canAuthenticateAgainstProtectionSpace,
356         didReceiveAuthenticationChallenge,
357         processDidCrash,
358         copyWebCryptoMasterKey,
359         didBeginNavigationGesture,
360         willEndNavigationGesture,
361         didEndNavigationGesture,
362         didRemoveNavigationGestureSnapshot,
363         0, // webProcessDidTerminate
364         0, // contentRuleListNotification
365         copySignedPublicKeyAndChallengeString
366     };
367     WKPageSetPageNavigationClient(newPage, &pageNavigationClient.base);
368
369     view->didInitializeClients();
370
371     TestController::singleton().updateWindowScaleForTest(view, *TestController::singleton().m_currentInvocation);
372
373     WKRetain(newPage);
374     return newPage;
375 }
376
377 const char* TestController::libraryPathForTesting()
378 {
379     // FIXME: This may not be sufficient to prevent interactions/crashes
380     // when running more than one copy of DumpRenderTree.
381     // See https://bugs.webkit.org/show_bug.cgi?id=10906
382     char* dumpRenderTreeTemp = getenv("DUMPRENDERTREE_TEMP");
383     if (dumpRenderTreeTemp)
384         return dumpRenderTreeTemp;
385     return platformLibraryPathForTesting();
386 }
387
388 void TestController::initialize(int argc, const char* argv[])
389 {
390     JSC::initializeThreading();
391     RunLoop::initializeMainRunLoop();
392     WTF::setProcessPrivileges(allPrivileges());
393
394     platformInitialize();
395
396     Options options;
397     OptionsHandler optionsHandler(options);
398
399     if (argc < 2) {
400         optionsHandler.printHelp();
401         exit(1);
402     }
403     if (!optionsHandler.parse(argc, argv))
404         exit(1);
405
406     m_useWaitToDumpWatchdogTimer = options.useWaitToDumpWatchdogTimer;
407     m_forceNoTimeout = options.forceNoTimeout;
408     m_verbose = options.verbose;
409     m_gcBetweenTests = options.gcBetweenTests;
410     m_shouldDumpPixelsForAllTests = options.shouldDumpPixelsForAllTests;
411     m_forceComplexText = options.forceComplexText;
412     m_shouldUseAcceleratedDrawing = options.shouldUseAcceleratedDrawing;
413     m_shouldUseRemoteLayerTree = options.shouldUseRemoteLayerTree;
414     m_paths = options.paths;
415     m_allowedHosts = options.allowedHosts;
416     m_shouldShowWebView = options.shouldShowWebView;
417     m_shouldShowTouches = options.shouldShowTouches;
418     m_checkForWorldLeaks = options.checkForWorldLeaks;
419     m_allowAnyHTTPSCertificateForAllowedHosts = options.allowAnyHTTPSCertificateForAllowedHosts;
420
421     if (options.printSupportedFeatures) {
422         // FIXME: On Windows, DumpRenderTree uses this to expose whether it supports 3d
423         // transforms and accelerated compositing. When we support those features, we
424         // should match DRT's behavior.
425         exit(0);
426     }
427
428     m_usingServerMode = (m_paths.size() == 1 && m_paths[0] == "-");
429     if (m_usingServerMode)
430         m_printSeparators = true;
431     else
432         m_printSeparators = m_paths.size() > 1;
433
434     initializeInjectedBundlePath();
435     initializeTestPluginDirectory();
436
437 #if PLATFORM(MAC)
438     WebCoreTestSupport::installMockGamepadProvider();
439 #endif
440
441     WKRetainPtr<WKStringRef> pageGroupIdentifier(AdoptWK, WKStringCreateWithUTF8CString("WebKitTestRunnerPageGroup"));
442     m_pageGroup.adopt(WKPageGroupCreateWithIdentifier(pageGroupIdentifier.get()));
443 }
444
445 WKRetainPtr<WKContextConfigurationRef> TestController::generateContextConfiguration() const
446 {
447     auto configuration = adoptWK(WKContextConfigurationCreate());
448     WKContextConfigurationSetInjectedBundlePath(configuration.get(), injectedBundlePath());
449     WKContextConfigurationSetFullySynchronousModeIsAllowedForTesting(configuration.get(), true);
450
451     if (const char* dumpRenderTreeTemp = libraryPathForTesting()) {
452         String temporaryFolder = String::fromUTF8(dumpRenderTreeTemp);
453
454         const char separator = '/';
455
456         WKContextConfigurationSetApplicationCacheDirectory(configuration.get(), toWK(temporaryFolder + separator + "ApplicationCache").get());
457         WKContextConfigurationSetDiskCacheDirectory(configuration.get(), toWK(temporaryFolder + separator + "Cache").get());
458         WKContextConfigurationSetIndexedDBDatabaseDirectory(configuration.get(), toWK(temporaryFolder + separator + "Databases" + separator + "IndexedDB").get());
459         WKContextConfigurationSetLocalStorageDirectory(configuration.get(), toWK(temporaryFolder + separator + "LocalStorage").get());
460         WKContextConfigurationSetWebSQLDatabaseDirectory(configuration.get(), toWK(temporaryFolder + separator + "Databases" + separator + "WebSQL").get());
461         WKContextConfigurationSetMediaKeysStorageDirectory(configuration.get(), toWK(temporaryFolder + separator + "MediaKeys").get());
462         WKContextConfigurationSetResourceLoadStatisticsDirectory(configuration.get(), toWK(temporaryFolder + separator + "ResourceLoadStatistics").get());
463     }
464     return configuration;
465 }
466
467 WKRetainPtr<WKPageConfigurationRef> TestController::generatePageConfiguration(WKContextConfigurationRef configuration)
468 {
469     m_context = platformAdjustContext(adoptWK(WKContextCreateWithConfiguration(configuration)).get(), configuration);
470
471     m_geolocationProvider = std::make_unique<GeolocationProviderMock>(m_context.get());
472
473     if (const char* dumpRenderTreeTemp = libraryPathForTesting()) {
474         String temporaryFolder = String::fromUTF8(dumpRenderTreeTemp);
475
476         // FIXME: This should be migrated to WKContextConfigurationRef.
477         // Disable icon database to avoid fetching <http://127.0.0.1:8000/favicon.ico> and making tests flaky.
478         // Invividual tests can enable it using testRunner.setIconDatabaseEnabled, although it's not currently supported in WebKitTestRunner.
479         WKContextSetIconDatabasePath(m_context.get(), toWK(emptyString()).get());
480     }
481
482     WKContextSetDiskCacheSpeculativeValidationEnabled(m_context.get(), true);
483     WKContextUseTestingNetworkSession(m_context.get());
484     WKContextSetCacheModel(m_context.get(), kWKCacheModelDocumentBrowser);
485
486     auto* websiteDataStore = WKContextGetWebsiteDataStore(m_context.get());
487     WKWebsiteDataStoreSetCacheStoragePerOriginQuota(websiteDataStore, 400 * 1024);
488     
489     platformInitializeContext();
490
491     WKContextInjectedBundleClientV1 injectedBundleClient = {
492         { 1, this },
493         didReceiveMessageFromInjectedBundle,
494         didReceiveSynchronousMessageFromInjectedBundle,
495         getInjectedBundleInitializationUserData,
496     };
497     WKContextSetInjectedBundleClient(m_context.get(), &injectedBundleClient.base);
498
499     WKContextClientV2 contextClient = {
500         { 2, this },
501         0, // plugInAutoStartOriginHashesChanged
502         networkProcessDidCrash,
503         0, // plugInInformationBecameAvailable
504         0, // copyWebCryptoMasterKey
505     };
506     WKContextSetClient(m_context.get(), &contextClient.base);
507
508     WKContextHistoryClientV0 historyClient = {
509         { 0, this },
510         didNavigateWithNavigationData,
511         didPerformClientRedirect,
512         didPerformServerRedirect,
513         didUpdateHistoryTitle,
514         0, // populateVisitedLinks
515     };
516     WKContextSetHistoryClient(m_context.get(), &historyClient.base);
517
518     WKNotificationManagerRef notificationManager = WKContextGetNotificationManager(m_context.get());
519     WKNotificationProviderV0 notificationKit = m_webNotificationProvider.provider();
520     WKNotificationManagerSetProvider(notificationManager, &notificationKit.base);
521
522     if (testPluginDirectory())
523         WKContextSetAdditionalPluginsDirectory(m_context.get(), testPluginDirectory());
524
525     if (m_forceComplexText)
526         WKContextSetAlwaysUsesComplexTextCodePath(m_context.get(), true);
527
528     auto pageConfiguration = adoptWK(WKPageConfigurationCreate());
529     WKPageConfigurationSetContext(pageConfiguration.get(), m_context.get());
530     WKPageConfigurationSetPageGroup(pageConfiguration.get(), m_pageGroup.get());
531     WKPageConfigurationSetUserContentController(pageConfiguration.get(), adoptWK(WKUserContentControllerCreate()).get());
532     return pageConfiguration;
533 }
534
535 void TestController::createWebViewWithOptions(const TestOptions& options)
536 {
537     auto contextConfiguration = generateContextConfiguration();
538
539     WKRetainPtr<WKMutableArrayRef> overrideLanguages = adoptWK(WKMutableArrayCreate());
540     for (auto& language : options.overrideLanguages)
541         WKArrayAppendItem(overrideLanguages.get(), adoptWK(WKStringCreateWithUTF8CString(language.utf8().data())).get());
542     WKContextConfigurationSetOverrideLanguages(contextConfiguration.get(), overrideLanguages.get());
543
544     if (options.shouldEnableProcessSwapOnNavigation()) {
545         WKContextConfigurationSetProcessSwapsOnNavigation(contextConfiguration.get(), true);
546         if (options.enableProcessSwapOnWindowOpen)
547             WKContextConfigurationSetProcessSwapsOnWindowOpenWithOpener(contextConfiguration.get(), true);
548     }
549
550     auto configuration = generatePageConfiguration(contextConfiguration.get());
551
552     // Some preferences (notably mock scroll bars setting) currently cannot be re-applied to an existing view, so we need to set them now.
553     // FIXME: Migrate these preferences to WKContextConfigurationRef.
554     resetPreferencesToConsistentValues(options);
555
556     platformCreateWebView(configuration.get(), options);
557     WKPageUIClientV8 pageUIClient = {
558         { 8, m_mainWebView.get() },
559         0, // createNewPage_deprecatedForUseWithV0
560         0, // showPage
561         0, // close
562         0, // takeFocus
563         focus,
564         unfocus,
565         0, // runJavaScriptAlert_deprecatedForUseWithV0
566         0, // runJavaScriptAlert_deprecatedForUseWithV0
567         0, // runJavaScriptAlert_deprecatedForUseWithV0
568         0, // setStatusText
569         0, // mouseDidMoveOverElement_deprecatedForUseWithV0
570         0, // missingPluginButtonClicked
571         0, // didNotHandleKeyEvent
572         0, // didNotHandleWheelEvent
573         0, // toolbarsAreVisible
574         0, // setToolbarsAreVisible
575         0, // menuBarIsVisible
576         0, // setMenuBarIsVisible
577         0, // statusBarIsVisible
578         0, // setStatusBarIsVisible
579         0, // isResizable
580         0, // setIsResizable
581         getWindowFrame,
582         setWindowFrame,
583         runBeforeUnloadConfirmPanel,
584         0, // didDraw
585         0, // pageDidScroll
586         0, // exceededDatabaseQuota,
587         runOpenPanel,
588         decidePolicyForGeolocationPermissionRequest,
589         0, // headerHeight
590         0, // footerHeight
591         0, // drawHeader
592         0, // drawFooter
593         0, // printFrame
594         runModal,
595         0, // didCompleteRubberBandForMainFrame
596         0, // saveDataToFileInDownloadsFolder
597         0, // shouldInterruptJavaScript
598         0, // createNewPage_deprecatedForUseWithV1
599         0, // mouseDidMoveOverElement
600         decidePolicyForNotificationPermissionRequest, // decidePolicyForNotificationPermissionRequest
601         0, // unavailablePluginButtonClicked_deprecatedForUseWithV1
602         0, // showColorPicker
603         0, // hideColorPicker
604         unavailablePluginButtonClicked,
605         0, // pinnedStateDidChange
606         0, // didBeginTrackingPotentialLongMousePress
607         0, // didRecognizeLongMousePress
608         0, // didCancelTrackingPotentialLongMousePress
609         0, // isPlayingAudioDidChange
610         decidePolicyForUserMediaPermissionRequest,
611         0, // didClickAutofillButton
612         0, // runJavaScriptAlert
613         0, // runJavaScriptConfirm
614         0, // runJavaScriptPrompt
615         0, // mediaSessionMetadataDidChange
616         createOtherPage,
617         0, // runJavaScriptAlert
618         0, // runJavaScriptConfirm
619         0, // runJavaScriptPrompt
620         checkUserMediaPermissionForOrigin,
621         0, // runBeforeUnloadConfirmPanel
622         0, // fullscreenMayReturnToInline
623         requestPointerLock,
624         0,
625     };
626     WKPageSetPageUIClient(m_mainWebView->page(), &pageUIClient.base);
627
628     WKPageNavigationClientV3 pageNavigationClient = {
629         { 3, this },
630         decidePolicyForNavigationAction,
631         decidePolicyForNavigationResponse,
632         decidePolicyForPluginLoad,
633         0, // didStartProvisionalNavigation
634         didReceiveServerRedirectForProvisionalNavigation,
635         0, // didFailProvisionalNavigation
636         didCommitNavigation,
637         didFinishNavigation,
638         0, // didFailNavigation
639         0, // didFailProvisionalLoadInSubframe
640         0, // didFinishDocumentLoad
641         0, // didSameDocumentNavigation
642         0, // renderingProgressDidChange
643         canAuthenticateAgainstProtectionSpace,
644         didReceiveAuthenticationChallenge,
645         processDidCrash,
646         copyWebCryptoMasterKey,
647         didBeginNavigationGesture,
648         willEndNavigationGesture,
649         didEndNavigationGesture,
650         didRemoveNavigationGestureSnapshot,
651         0, // webProcessDidTerminate
652         0, // contentRuleListNotification
653         copySignedPublicKeyAndChallengeString
654     };
655     WKPageSetPageNavigationClient(m_mainWebView->page(), &pageNavigationClient.base);
656
657     WKContextDownloadClientV1 downloadClient = {
658         { 1, this },
659         downloadDidStart,
660         0, // didReceiveAuthenticationChallenge
661         0, // didReceiveResponse
662         0, // didReceiveData
663         0, // shouldDecodeSourceDataOfMIMEType
664         decideDestinationWithSuggestedFilename,
665         0, // didCreateDestination
666         downloadDidFinish,
667         downloadDidFail,
668         downloadDidCancel,
669         0, // processDidCrash;
670         downloadDidReceiveServerRedirectToURL
671     };
672     WKContextSetDownloadClient(context(), &downloadClient.base);
673     
674     // this should just be done on the page?
675     WKPageInjectedBundleClientV0 injectedBundleClient = {
676         { 0, this },
677         didReceivePageMessageFromInjectedBundle,
678         didReceiveSynchronousPageMessageFromInjectedBundle
679     };
680     WKPageSetPageInjectedBundleClient(m_mainWebView->page(), &injectedBundleClient.base);
681
682     m_mainWebView->didInitializeClients();
683
684     // Generally, the tests should default to running at 1x. updateWindowScaleForTest() will adjust the scale to
685     // something else for specific tests that need to run at a different window scale.
686     m_mainWebView->changeWindowScaleIfNeeded(1);
687 }
688
689 void TestController::ensureViewSupportsOptionsForTest(const TestInvocation& test)
690 {
691     auto options = test.options();
692
693     if (m_mainWebView) {
694         if (m_mainWebView->viewSupportsOptions(options))
695             return;
696
697         willDestroyWebView();
698
699         WKPageSetPageUIClient(m_mainWebView->page(), nullptr);
700         WKPageSetPageNavigationClient(m_mainWebView->page(), nullptr);
701         WKPageClose(m_mainWebView->page());
702
703         m_mainWebView = nullptr;
704     }
705
706     createWebViewWithOptions(options);
707
708     if (!resetStateToConsistentValues(options, ResetStage::BeforeTest))
709         TestInvocation::dumpWebProcessUnresponsiveness("<unknown> - TestController::run - Failed to reset state to consistent values\n");
710 }
711
712 void TestController::resetPreferencesToConsistentValues(const TestOptions& options)
713 {
714     // Reset preferences
715     WKPreferencesRef preferences = platformPreferences();
716     WKPreferencesResetTestRunnerOverrides(preferences);
717
718     WKPreferencesEnableAllExperimentalFeatures(preferences);
719     for (const auto& experimentalFeature : options.experimentalFeatures)
720         WKPreferencesSetExperimentalFeatureForKey(preferences, experimentalFeature.value, toWK(experimentalFeature.key).get());
721
722     WKPreferencesResetAllInternalDebugFeatures(preferences);
723     for (const auto& internalDebugFeature : options.internalDebugFeatures)
724         WKPreferencesSetInternalDebugFeatureForKey(preferences, internalDebugFeature.value, toWK(internalDebugFeature.key).get());
725
726     WKPreferencesSetProcessSwapOnNavigationEnabled(preferences, options.shouldEnableProcessSwapOnNavigation());
727     WKPreferencesSetPageVisibilityBasedProcessSuppressionEnabled(preferences, false);
728     WKPreferencesSetOfflineWebApplicationCacheEnabled(preferences, true);
729     WKPreferencesSetSubpixelAntialiasedLayerTextEnabled(preferences, false);
730     WKPreferencesSetXSSAuditorEnabled(preferences, false);
731     WKPreferencesSetWebAudioEnabled(preferences, true);
732     WKPreferencesSetMediaDevicesEnabled(preferences, true);
733     WKPreferencesSetWebRTCMDNSICECandidatesEnabled(preferences, false);
734     WKPreferencesSetDeveloperExtrasEnabled(preferences, true);
735     WKPreferencesSetJavaScriptRuntimeFlags(preferences, kWKJavaScriptRuntimeFlagsAllEnabled);
736     WKPreferencesSetJavaScriptCanOpenWindowsAutomatically(preferences, true);
737     WKPreferencesSetJavaScriptCanAccessClipboard(preferences, true);
738     WKPreferencesSetDOMPasteAllowed(preferences, true);
739     WKPreferencesSetUniversalAccessFromFileURLsAllowed(preferences, true);
740     WKPreferencesSetFileAccessFromFileURLsAllowed(preferences, true);
741 #if ENABLE(FULLSCREEN_API)
742     WKPreferencesSetFullScreenEnabled(preferences, true);
743 #endif
744     WKPreferencesSetPageCacheEnabled(preferences, false);
745     WKPreferencesSetAsynchronousPluginInitializationEnabled(preferences, false);
746     WKPreferencesSetAsynchronousPluginInitializationEnabledForAllPlugins(preferences, false);
747     WKPreferencesSetArtificialPluginInitializationDelayEnabled(preferences, false);
748     WKPreferencesSetTabToLinksEnabled(preferences, false);
749     WKPreferencesSetInteractiveFormValidationEnabled(preferences, true);
750     WKPreferencesSetDataTransferItemsEnabled(preferences, true);
751     WKPreferencesSetCustomPasteboardDataEnabled(preferences, true);
752
753     WKPreferencesSetMockScrollbarsEnabled(preferences, options.useMockScrollbars);
754     WKPreferencesSetNeedsSiteSpecificQuirks(preferences, options.needsSiteSpecificQuirks);
755     WKPreferencesSetAttachmentElementEnabled(preferences, options.enableAttachmentElement);
756     WKPreferencesSetMenuItemElementEnabled(preferences, options.enableMenuItemElement);
757     WKPreferencesSetModernMediaControlsEnabled(preferences, options.enableModernMediaControls);
758     WKPreferencesSetWebAuthenticationEnabled(preferences, options.enableWebAuthentication);
759     WKPreferencesSetWebAuthenticationLocalAuthenticatorEnabled(preferences, options.enableWebAuthenticationLocalAuthenticator);
760     WKPreferencesSetIsSecureContextAttributeEnabled(preferences, options.enableIsSecureContextAttribute);
761     WKPreferencesSetAllowCrossOriginSubresourcesToAskForCredentials(preferences, options.allowCrossOriginSubresourcesToAskForCredentials);
762     WKPreferencesSetColorFilterEnabled(preferences, options.enableColorFilter);
763     WKPreferencesSetPunchOutWhiteBackgroundsInDarkMode(preferences, options.punchOutWhiteBackgroundsInDarkMode);
764
765     static WKStringRef defaultTextEncoding = WKStringCreateWithUTF8CString("ISO-8859-1");
766     WKPreferencesSetDefaultTextEncodingName(preferences, defaultTextEncoding);
767
768     static WKStringRef standardFontFamily = WKStringCreateWithUTF8CString("Times");
769     static WKStringRef cursiveFontFamily = WKStringCreateWithUTF8CString("Apple Chancery");
770     static WKStringRef fantasyFontFamily = WKStringCreateWithUTF8CString("Papyrus");
771     static WKStringRef fixedFontFamily = WKStringCreateWithUTF8CString("Courier");
772     static WKStringRef pictographFontFamily = WKStringCreateWithUTF8CString("Apple Color Emoji");
773     static WKStringRef sansSerifFontFamily = WKStringCreateWithUTF8CString("Helvetica");
774     static WKStringRef serifFontFamily = WKStringCreateWithUTF8CString("Times");
775
776     WKPreferencesSetMinimumFontSize(preferences, 0);
777     WKPreferencesSetStandardFontFamily(preferences, standardFontFamily);
778     WKPreferencesSetCursiveFontFamily(preferences, cursiveFontFamily);
779     WKPreferencesSetFantasyFontFamily(preferences, fantasyFontFamily);
780     WKPreferencesSetFixedFontFamily(preferences, fixedFontFamily);
781     WKPreferencesSetPictographFontFamily(preferences, pictographFontFamily);
782     WKPreferencesSetSansSerifFontFamily(preferences, sansSerifFontFamily);
783     WKPreferencesSetSerifFontFamily(preferences, serifFontFamily);
784     WKPreferencesSetAsynchronousSpellCheckingEnabled(preferences, false);
785 #if ENABLE(MEDIA_SOURCE)
786     WKPreferencesSetMediaSourceEnabled(preferences, true);
787     WKPreferencesSetSourceBufferChangeTypeEnabled(preferences, true);
788 #endif
789
790     WKPreferencesSetHiddenPageDOMTimerThrottlingEnabled(preferences, false);
791     WKPreferencesSetHiddenPageCSSAnimationSuspensionEnabled(preferences, false);
792
793     WKPreferencesSetAcceleratedDrawingEnabled(preferences, m_shouldUseAcceleratedDrawing || options.useAcceleratedDrawing);
794     // FIXME: We should be testing the default.
795     WKPreferencesSetStorageBlockingPolicy(preferences, kWKAllowAllStorage);
796
797     WKPreferencesSetFetchAPIKeepAliveEnabled(preferences, true);
798     WKPreferencesSetResourceTimingEnabled(preferences, true);
799     WKPreferencesSetUserTimingEnabled(preferences, true);
800     WKPreferencesSetMediaPreloadingEnabled(preferences, true);
801     WKPreferencesSetMediaPlaybackAllowsInline(preferences, true);
802     WKPreferencesSetInlineMediaPlaybackRequiresPlaysInlineAttribute(preferences, false);
803     WKPreferencesSetBeaconAPIEnabled(preferences, true);
804     WKPreferencesSetDirectoryUploadEnabled(preferences, true);
805
806     WKCookieManagerDeleteAllCookies(WKContextGetCookieManager(m_context.get()));
807
808     WKPreferencesSetMockCaptureDevicesEnabled(preferences, true);
809     
810     WKPreferencesSetLargeImageAsyncDecodingEnabled(preferences, false);
811
812     WKPreferencesSetInspectorAdditionsEnabled(preferences, options.enableInspectorAdditions);
813
814     WKPreferencesSetStorageAccessAPIEnabled(preferences, true);
815     
816     WKPreferencesSetAccessibilityObjectModelEnabled(preferences, true);
817     WKPreferencesSetAriaReflectionEnabled(preferences, true);
818     WKPreferencesSetCSSOMViewScrollingAPIEnabled(preferences, true);
819     WKPreferencesSetMediaCapabilitiesEnabled(preferences, true);
820
821     WKPreferencesSetRestrictedHTTPResponseAccess(preferences, true);
822
823     WKPreferencesSetServerTimingEnabled(preferences, true);
824
825     WKPreferencesSetWebSQLDisabled(preferences, false);
826
827     platformResetPreferencesToConsistentValues();
828 }
829
830 bool TestController::resetStateToConsistentValues(const TestOptions& options, ResetStage resetStage)
831 {
832     SetForScope<State> changeState(m_state, Resetting);
833     m_beforeUnloadReturnValue = true;
834
835     // This setting differs between the antique and modern Mac WebKit2 API.
836     // For now, maintain the antique behavior, because some tests depend on it!
837     // FIXME: We should be testing the default.
838     WKPageSetBackgroundExtendsBeyondPage(m_mainWebView->page(), false);
839
840     WKPageSetCustomUserAgent(m_mainWebView->page(), nullptr);
841
842     WKRetainPtr<WKStringRef> messageName = adoptWK(WKStringCreateWithUTF8CString("Reset"));
843     WKRetainPtr<WKMutableDictionaryRef> resetMessageBody = adoptWK(WKMutableDictionaryCreate());
844
845     WKRetainPtr<WKStringRef> shouldGCKey = adoptWK(WKStringCreateWithUTF8CString("ShouldGC"));
846     WKRetainPtr<WKBooleanRef> shouldGCValue = adoptWK(WKBooleanCreate(m_gcBetweenTests));
847     WKDictionarySetItem(resetMessageBody.get(), shouldGCKey.get(), shouldGCValue.get());
848
849     WKRetainPtr<WKStringRef> allowedHostsKey = adoptWK(WKStringCreateWithUTF8CString("AllowedHosts"));
850     WKRetainPtr<WKMutableArrayRef> allowedHostsValue = adoptWK(WKMutableArrayCreate());
851     for (auto& host : m_allowedHosts) {
852         WKRetainPtr<WKStringRef> wkHost = adoptWK(WKStringCreateWithUTF8CString(host.c_str()));
853         WKArrayAppendItem(allowedHostsValue.get(), wkHost.get());
854     }
855     WKDictionarySetItem(resetMessageBody.get(), allowedHostsKey.get(), allowedHostsValue.get());
856
857     if (options.jscOptions.length()) {
858         WKRetainPtr<WKStringRef> jscOptionsKey = adoptWK(WKStringCreateWithUTF8CString("JSCOptions"));
859         WKRetainPtr<WKStringRef> jscOptionsValue = adoptWK(WKStringCreateWithUTF8CString(options.jscOptions.c_str()));
860         WKDictionarySetItem(resetMessageBody.get(), jscOptionsKey.get(), jscOptionsValue.get());
861     }
862
863     WKPagePostMessageToInjectedBundle(TestController::singleton().mainWebView()->page(), messageName.get(), resetMessageBody.get());
864
865     WKContextSetShouldUseFontSmoothing(TestController::singleton().context(), false);
866
867     WKContextSetCacheModel(TestController::singleton().context(), kWKCacheModelDocumentBrowser);
868
869     WKContextClearCachedCredentials(TestController::singleton().context());
870
871     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 = String::format("%s:%d - didReceiveAuthenticationChallenge - %s - ", host.c_str(), port, toString(authenticationScheme));
2077     if (!m_handlesAuthenticationChallenges)
2078         message.append("Simulating cancelled authentication sheet\n");
2079     else
2080         message.append(String::format("Responding with %s:%s\n", m_authenticationUsername.utf8().data(), m_authenticationPassword.utf8().data()));
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         String message = String::format("Download failed.\n");
2179         m_currentInvocation->outputText(message);
2180
2181         WKRetainPtr<WKStringRef> errorDomain = adoptWK(WKErrorCopyDomain(error));
2182         WKRetainPtr<WKStringRef> errorDescription = adoptWK(WKErrorCopyLocalizedDescription(error));
2183         int errorCode = WKErrorGetErrorCode(error);
2184
2185         StringBuilder errorBuilder;
2186         errorBuilder.append("Failed: ");
2187         errorBuilder.append(toWTFString(errorDomain));
2188         errorBuilder.append(", code=");
2189         errorBuilder.appendNumber(errorCode);
2190         errorBuilder.append(", description=");
2191         errorBuilder.append(toWTFString(errorDescription));
2192         errorBuilder.append("\n");
2193
2194         m_currentInvocation->outputText(errorBuilder.toString());
2195     }
2196     m_currentInvocation->notifyDownloadDone();
2197 }
2198
2199 void TestController::downloadDidCancel(WKContextRef, WKDownloadRef)
2200 {
2201     if (m_shouldLogDownloadCallbacks)
2202         m_currentInvocation->outputText("Download cancelled.\n");
2203     m_currentInvocation->notifyDownloadDone();
2204 }
2205
2206 void TestController::processDidCrash()
2207 {
2208     // This function can be called multiple times when crash logs are being saved on Windows, so
2209     // ensure we only print the crashed message once.
2210     if (!m_didPrintWebProcessCrashedMessage) {
2211         pid_t pid = WKPageGetProcessIdentifier(m_mainWebView->page());
2212         fprintf(stderr, "#CRASHED - %s (pid %ld)\n", webProcessName(), static_cast<long>(pid));
2213         fflush(stderr);
2214         m_didPrintWebProcessCrashedMessage = true;
2215     }
2216
2217     if (m_shouldExitWhenWebProcessCrashes)
2218         exit(1);
2219 }
2220
2221 void TestController::didBeginNavigationGesture(WKPageRef)
2222 {
2223     m_currentInvocation->didBeginSwipe();
2224 }
2225
2226 void TestController::willEndNavigationGesture(WKPageRef, WKBackForwardListItemRef)
2227 {
2228     m_currentInvocation->willEndSwipe();
2229 }
2230
2231 void TestController::didEndNavigationGesture(WKPageRef, WKBackForwardListItemRef)
2232 {
2233     m_currentInvocation->didEndSwipe();
2234 }
2235
2236 void TestController::didRemoveNavigationGestureSnapshot(WKPageRef)
2237 {
2238     m_currentInvocation->didRemoveSwipeSnapshot();
2239 }
2240
2241 void TestController::simulateWebNotificationClick(uint64_t notificationID)
2242 {
2243     m_webNotificationProvider.simulateWebNotificationClick(mainWebView()->page(), notificationID);
2244 }
2245
2246 void TestController::setGeolocationPermission(bool enabled)
2247 {
2248     m_isGeolocationPermissionSet = true;
2249     m_isGeolocationPermissionAllowed = enabled;
2250     decidePolicyForGeolocationPermissionRequestIfPossible();
2251 }
2252
2253 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)
2254 {
2255     m_geolocationProvider->setPosition(latitude, longitude, accuracy, providesAltitude, altitude, providesAltitudeAccuracy, altitudeAccuracy, providesHeading, heading, providesSpeed, speed, providesFloorLevel, floorLevel);
2256 }
2257
2258 void TestController::setMockGeolocationPositionUnavailableError(WKStringRef errorMessage)
2259 {
2260     m_geolocationProvider->setPositionUnavailableError(errorMessage);
2261 }
2262
2263 void TestController::handleGeolocationPermissionRequest(WKGeolocationPermissionRequestRef geolocationPermissionRequest)
2264 {
2265     m_geolocationPermissionRequests.append(geolocationPermissionRequest);
2266     decidePolicyForGeolocationPermissionRequestIfPossible();
2267 }
2268
2269 bool TestController::isGeolocationProviderActive() const
2270 {
2271     return m_geolocationProvider->isActive();
2272 }
2273
2274 static String originUserVisibleName(WKSecurityOriginRef origin)
2275 {
2276     if (!origin)
2277         return emptyString();
2278
2279     std::string host = toSTD(adoptWK(WKSecurityOriginCopyHost(origin))).c_str();
2280     std::string protocol = toSTD(adoptWK(WKSecurityOriginCopyProtocol(origin))).c_str();
2281
2282     if (!host.length() || !protocol.length())
2283         return emptyString();
2284
2285     unsigned short port = WKSecurityOriginGetPort(origin);
2286     if (port)
2287         return String::format("%s://%s:%d", protocol.c_str(), host.c_str(), port);
2288
2289     return String::format("%s://%s", protocol.c_str(), host.c_str());
2290 }
2291
2292 static String userMediaOriginHash(WKSecurityOriginRef userMediaDocumentOrigin, WKSecurityOriginRef topLevelDocumentOrigin)
2293 {
2294     String userMediaDocumentOriginString = originUserVisibleName(userMediaDocumentOrigin);
2295     String topLevelDocumentOriginString = originUserVisibleName(topLevelDocumentOrigin);
2296
2297     if (topLevelDocumentOriginString.isEmpty())
2298         return userMediaDocumentOriginString;
2299
2300     return String::format("%s-%s", userMediaDocumentOriginString.utf8().data(), topLevelDocumentOriginString.utf8().data());
2301 }
2302
2303 static String userMediaOriginHash(WKStringRef userMediaDocumentOriginString, WKStringRef topLevelDocumentOriginString)
2304 {
2305     auto userMediaDocumentOrigin = adoptWK(WKSecurityOriginCreateFromString(userMediaDocumentOriginString));
2306     if (!WKStringGetLength(topLevelDocumentOriginString))
2307         return userMediaOriginHash(userMediaDocumentOrigin.get(), nullptr);
2308
2309     auto topLevelDocumentOrigin = adoptWK(WKSecurityOriginCreateFromString(topLevelDocumentOriginString));
2310     return userMediaOriginHash(userMediaDocumentOrigin.get(), topLevelDocumentOrigin.get());
2311 }
2312
2313 void TestController::setUserMediaPermission(bool enabled)
2314 {
2315     m_isUserMediaPermissionSet = true;
2316     m_isUserMediaPermissionAllowed = enabled;
2317     decidePolicyForUserMediaPermissionRequestIfPossible();
2318 }
2319
2320 void TestController::resetUserMediaPermission()
2321 {
2322     m_isUserMediaPermissionSet = false;
2323 }
2324
2325 class OriginSettings : public RefCounted<OriginSettings> {
2326 public:
2327     explicit OriginSettings()
2328     {
2329     }
2330
2331     bool persistentPermission() const { return m_persistentPermission; }
2332     void setPersistentPermission(bool permission) { m_persistentPermission = permission; }
2333
2334     String persistentSalt() const { return m_persistentSalt; }
2335     void setPersistentSalt(const String& salt) { m_persistentSalt = salt; }
2336
2337     HashMap<uint64_t, String>& ephemeralSalts() { return m_ephemeralSalts; }
2338
2339     void incrementRequestCount() { ++m_requestCount; }
2340     void resetRequestCount() { m_requestCount = 0; }
2341     unsigned requestCount() const { return m_requestCount; }
2342
2343 private:
2344     HashMap<uint64_t, String> m_ephemeralSalts;
2345     String m_persistentSalt;
2346     unsigned m_requestCount { 0 };
2347     bool m_persistentPermission { false };
2348 };
2349
2350 String TestController::saltForOrigin(WKFrameRef frame, String originHash)
2351 {
2352     auto& settings = settingsForOrigin(originHash);
2353     auto& ephemeralSalts = settings.ephemeralSalts();
2354     auto frameInfo = adoptWK(WKFrameCreateFrameInfo(frame));
2355     auto frameHandle = WKFrameInfoGetFrameHandleRef(frameInfo.get());
2356     uint64_t frameIdentifier = WKFrameHandleGetFrameID(frameHandle);
2357     String frameSalt = ephemeralSalts.get(frameIdentifier);
2358
2359     if (settings.persistentPermission()) {
2360         if (frameSalt.length())
2361             return frameSalt;
2362
2363         if (!settings.persistentSalt().length())
2364             settings.setPersistentSalt(createCanonicalUUIDString());
2365
2366         return settings.persistentSalt();
2367     }
2368
2369     if (!frameSalt.length()) {
2370         frameSalt = createCanonicalUUIDString();
2371         ephemeralSalts.add(frameIdentifier, frameSalt);
2372     }
2373
2374     return frameSalt;
2375 }
2376
2377 void TestController::setUserMediaPersistentPermissionForOrigin(bool permission, WKStringRef userMediaDocumentOriginString, WKStringRef topLevelDocumentOriginString)
2378 {
2379     auto originHash = userMediaOriginHash(userMediaDocumentOriginString, topLevelDocumentOriginString);
2380     auto& settings = settingsForOrigin(originHash);
2381     settings.setPersistentPermission(permission);
2382 }
2383
2384 void TestController::handleCheckOfUserMediaPermissionForOrigin(WKFrameRef frame, WKSecurityOriginRef userMediaDocumentOrigin, WKSecurityOriginRef topLevelDocumentOrigin, const WKUserMediaPermissionCheckRef& checkRequest)
2385 {
2386     auto originHash = userMediaOriginHash(userMediaDocumentOrigin, topLevelDocumentOrigin);
2387     auto salt = saltForOrigin(frame, originHash);
2388     WKRetainPtr<WKStringRef> saltString = adoptWK(WKStringCreateWithUTF8CString(salt.utf8().data()));
2389
2390     WKUserMediaPermissionCheckSetUserMediaAccessInfo(checkRequest, saltString.get(), settingsForOrigin(originHash).persistentPermission());
2391 }
2392
2393 void TestController::handleUserMediaPermissionRequest(WKFrameRef frame, WKSecurityOriginRef userMediaDocumentOrigin, WKSecurityOriginRef topLevelDocumentOrigin, WKUserMediaPermissionRequestRef request)
2394 {
2395     auto originHash = userMediaOriginHash(userMediaDocumentOrigin, topLevelDocumentOrigin);
2396     m_userMediaPermissionRequests.append(std::make_pair(originHash, request));
2397     decidePolicyForUserMediaPermissionRequestIfPossible();
2398 }
2399
2400 OriginSettings& TestController::settingsForOrigin(const String& originHash)
2401 {
2402     RefPtr<OriginSettings> settings = m_cachedUserMediaPermissions.get(originHash);
2403     if (!settings) {
2404         settings = adoptRef(*new OriginSettings());
2405         m_cachedUserMediaPermissions.add(originHash, settings);
2406     }
2407
2408     return *settings;
2409 }
2410
2411 unsigned TestController::userMediaPermissionRequestCountForOrigin(WKStringRef userMediaDocumentOriginString, WKStringRef topLevelDocumentOriginString)
2412 {
2413     auto originHash = userMediaOriginHash(userMediaDocumentOriginString, topLevelDocumentOriginString);
2414     return settingsForOrigin(originHash).requestCount();
2415 }
2416
2417 void TestController::resetUserMediaPermissionRequestCountForOrigin(WKStringRef userMediaDocumentOriginString, WKStringRef topLevelDocumentOriginString)
2418 {
2419     auto originHash = userMediaOriginHash(userMediaDocumentOriginString, topLevelDocumentOriginString);
2420     settingsForOrigin(originHash).resetRequestCount();
2421 }
2422
2423 void TestController::decidePolicyForUserMediaPermissionRequestIfPossible()
2424 {
2425     if (!m_isUserMediaPermissionSet)
2426         return;
2427
2428     for (auto& pair : m_userMediaPermissionRequests) {
2429         auto originHash = pair.first;
2430         auto request = pair.second.get();
2431
2432         auto& settings = settingsForOrigin(originHash);
2433         settings.incrementRequestCount();
2434
2435         if (!m_isUserMediaPermissionAllowed && !settings.persistentPermission()) {
2436             WKUserMediaPermissionRequestDeny(request, kWKPermissionDenied);
2437             continue;
2438         }
2439
2440         WKRetainPtr<WKArrayRef> audioDeviceUIDs = adoptWK(WKUserMediaPermissionRequestAudioDeviceUIDs(request));
2441         WKRetainPtr<WKArrayRef> videoDeviceUIDs = adoptWK(WKUserMediaPermissionRequestVideoDeviceUIDs(request));
2442
2443         if (!WKArrayGetSize(videoDeviceUIDs.get()) && !WKArrayGetSize(audioDeviceUIDs.get())) {
2444             WKUserMediaPermissionRequestDeny(request, kWKNoConstraints);
2445             continue;
2446         }
2447
2448         WKRetainPtr<WKStringRef> videoDeviceUID;
2449         if (WKArrayGetSize(videoDeviceUIDs.get()))
2450             videoDeviceUID = reinterpret_cast<WKStringRef>(WKArrayGetItemAtIndex(videoDeviceUIDs.get(), 0));
2451         else
2452             videoDeviceUID = adoptWK(WKStringCreateWithUTF8CString(""));
2453
2454         WKRetainPtr<WKStringRef> audioDeviceUID;
2455         if (WKArrayGetSize(audioDeviceUIDs.get()))
2456             audioDeviceUID = reinterpret_cast<WKStringRef>(WKArrayGetItemAtIndex(audioDeviceUIDs.get(), 0));
2457         else
2458             audioDeviceUID = adoptWK(WKStringCreateWithUTF8CString(""));
2459
2460         WKUserMediaPermissionRequestAllow(request, audioDeviceUID.get(), videoDeviceUID.get());
2461     }
2462     m_userMediaPermissionRequests.clear();
2463 }
2464
2465 void TestController::setCustomPolicyDelegate(bool enabled, bool permissive)
2466 {
2467     m_policyDelegateEnabled = enabled;
2468     m_policyDelegatePermissive = permissive;
2469 }
2470
2471 void TestController::decidePolicyForGeolocationPermissionRequestIfPossible()
2472 {
2473     if (!m_isGeolocationPermissionSet)
2474         return;
2475
2476     for (size_t i = 0; i < m_geolocationPermissionRequests.size(); ++i) {
2477         WKGeolocationPermissionRequestRef permissionRequest = m_geolocationPermissionRequests[i].get();
2478         if (m_isGeolocationPermissionAllowed)
2479             WKGeolocationPermissionRequestAllow(permissionRequest);
2480         else
2481             WKGeolocationPermissionRequestDeny(permissionRequest);
2482     }
2483     m_geolocationPermissionRequests.clear();
2484 }
2485
2486 void TestController::decidePolicyForNotificationPermissionRequest(WKPageRef page, WKSecurityOriginRef origin, WKNotificationPermissionRequestRef request, const void*)
2487 {
2488     TestController::singleton().decidePolicyForNotificationPermissionRequest(page, origin, request);
2489 }
2490
2491 void TestController::decidePolicyForNotificationPermissionRequest(WKPageRef, WKSecurityOriginRef, WKNotificationPermissionRequestRef request)
2492 {
2493     WKNotificationPermissionRequestAllow(request);
2494 }
2495
2496 void TestController::unavailablePluginButtonClicked(WKPageRef, WKPluginUnavailabilityReason, WKDictionaryRef, const void*)
2497 {
2498     printf("MISSING PLUGIN BUTTON PRESSED\n");
2499 }
2500
2501 void TestController::decidePolicyForNavigationAction(WKPageRef, WKNavigationActionRef navigationAction, WKFramePolicyListenerRef listener, WKTypeRef, const void* clientInfo)
2502 {
2503     static_cast<TestController*>(const_cast<void*>(clientInfo))->decidePolicyForNavigationAction(listener);
2504 }
2505
2506 void TestController::decidePolicyForNavigationAction(WKFramePolicyListenerRef listener)
2507 {
2508     WKRetainPtr<WKFramePolicyListenerRef> retainedListener { listener };
2509     const bool shouldIgnore { m_policyDelegateEnabled && !m_policyDelegatePermissive };
2510     auto decisionFunction = [shouldIgnore, retainedListener]() {
2511         if (shouldIgnore)
2512             WKFramePolicyListenerIgnore(retainedListener.get());
2513         else
2514             WKFramePolicyListenerUse(retainedListener.get());
2515     };
2516
2517     if (m_shouldDecideNavigationPolicyAfterDelay)
2518         RunLoop::main().dispatch(WTFMove(decisionFunction));
2519     else
2520         decisionFunction();
2521 }
2522
2523 void TestController::decidePolicyForNavigationResponse(WKPageRef, WKNavigationResponseRef navigationResponse, WKFramePolicyListenerRef listener, WKTypeRef, const void* clientInfo)
2524 {
2525     static_cast<TestController*>(const_cast<void*>(clientInfo))->decidePolicyForNavigationResponse(navigationResponse, listener);
2526 }
2527
2528 void TestController::decidePolicyForNavigationResponse(WKNavigationResponseRef navigationResponse, WKFramePolicyListenerRef listener)
2529 {
2530     WKRetainPtr<WKNavigationResponseRef> retainedNavigationResponse { navigationResponse };
2531     WKRetainPtr<WKFramePolicyListenerRef> retainedListener { listener };
2532
2533     bool shouldDownloadUndisplayableMIMETypes = m_shouldDownloadUndisplayableMIMETypes;
2534     auto decisionFunction = [shouldDownloadUndisplayableMIMETypes, retainedNavigationResponse, retainedListener]() {
2535         // Even though Response was already checked by WKBundlePagePolicyClient, the check did not include plugins
2536         // so we have to re-check again.
2537         if (WKNavigationResponseCanShowMIMEType(retainedNavigationResponse.get())) {
2538             WKFramePolicyListenerUse(retainedListener.get());
2539             return;
2540         }
2541
2542         if (shouldDownloadUndisplayableMIMETypes)
2543             WKFramePolicyListenerDownload(retainedListener.get());
2544         else
2545             WKFramePolicyListenerIgnore(retainedListener.get());
2546     };
2547
2548     if (m_shouldDecideResponsePolicyAfterDelay)
2549         RunLoop::main().dispatch(WTFMove(decisionFunction));
2550     else
2551         decisionFunction();
2552 }
2553
2554 void TestController::didNavigateWithNavigationData(WKContextRef, WKPageRef, WKNavigationDataRef navigationData, WKFrameRef frame, const void* clientInfo)
2555 {
2556     static_cast<TestController*>(const_cast<void*>(clientInfo))->didNavigateWithNavigationData(navigationData, frame);
2557 }
2558
2559 void TestController::didNavigateWithNavigationData(WKNavigationDataRef navigationData, WKFrameRef)
2560 {
2561     if (m_state != RunningTest)
2562         return;
2563
2564     if (!m_shouldLogHistoryClientCallbacks)
2565         return;
2566
2567     // URL
2568     WKRetainPtr<WKURLRef> urlWK = adoptWK(WKNavigationDataCopyURL(navigationData));
2569     WKRetainPtr<WKStringRef> urlStringWK = adoptWK(WKURLCopyString(urlWK.get()));
2570     // Title
2571     WKRetainPtr<WKStringRef> titleWK = adoptWK(WKNavigationDataCopyTitle(navigationData));
2572     // HTTP method
2573     WKRetainPtr<WKURLRequestRef> requestWK = adoptWK(WKNavigationDataCopyOriginalRequest(navigationData));
2574     WKRetainPtr<WKStringRef> methodWK = adoptWK(WKURLRequestCopyHTTPMethod(requestWK.get()));
2575
2576     // FIXME: Determine whether the navigation was successful / a client redirect rather than hard-coding the message here.
2577     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",
2578         toSTD(urlStringWK).c_str(), toSTD(titleWK).c_str(), toSTD(methodWK).c_str()));
2579 }
2580
2581 void TestController::didPerformClientRedirect(WKContextRef, WKPageRef, WKURLRef sourceURL, WKURLRef destinationURL, WKFrameRef frame, const void* clientInfo)
2582 {
2583     static_cast<TestController*>(const_cast<void*>(clientInfo))->didPerformClientRedirect(sourceURL, destinationURL, frame);
2584 }
2585
2586 void TestController::didPerformClientRedirect(WKURLRef sourceURL, WKURLRef destinationURL, WKFrameRef)
2587 {
2588     if (m_state != RunningTest)
2589         return;
2590
2591     if (!m_shouldLogHistoryClientCallbacks)
2592         return;
2593
2594     WKRetainPtr<WKStringRef> sourceStringWK = adoptWK(WKURLCopyString(sourceURL));
2595     WKRetainPtr<WKStringRef> destinationStringWK = adoptWK(WKURLCopyString(destinationURL));
2596
2597     m_currentInvocation->outputText(String::format("WebView performed a client redirect from \"%s\" to \"%s\".\n", toSTD(sourceStringWK).c_str(), toSTD(destinationStringWK).c_str()));
2598 }
2599
2600 void TestController::didPerformServerRedirect(WKContextRef, WKPageRef, WKURLRef sourceURL, WKURLRef destinationURL, WKFrameRef frame, const void* clientInfo)
2601 {
2602     static_cast<TestController*>(const_cast<void*>(clientInfo))->didPerformServerRedirect(sourceURL, destinationURL, frame);
2603 }
2604
2605 void TestController::didPerformServerRedirect(WKURLRef sourceURL, WKURLRef destinationURL, WKFrameRef)
2606 {
2607     if (m_state != RunningTest)
2608         return;
2609
2610     if (!m_shouldLogHistoryClientCallbacks)
2611         return;
2612
2613     WKRetainPtr<WKStringRef> sourceStringWK = adoptWK(WKURLCopyString(sourceURL));
2614     WKRetainPtr<WKStringRef> destinationStringWK = adoptWK(WKURLCopyString(destinationURL));
2615
2616     m_currentInvocation->outputText(String::format("WebView performed a server redirect from \"%s\" to \"%s\".\n", toSTD(sourceStringWK).c_str(), toSTD(destinationStringWK).c_str()));
2617 }
2618
2619 void TestController::didUpdateHistoryTitle(WKContextRef, WKPageRef, WKStringRef title, WKURLRef URL, WKFrameRef frame, const void* clientInfo)
2620 {
2621     static_cast<TestController*>(const_cast<void*>(clientInfo))->didUpdateHistoryTitle(title, URL, frame);
2622 }
2623
2624 void TestController::didUpdateHistoryTitle(WKStringRef title, WKURLRef URL, WKFrameRef)
2625 {
2626     if (m_state != RunningTest)
2627         return;
2628
2629     if (!m_shouldLogHistoryClientCallbacks)
2630         return;
2631
2632     WKRetainPtr<WKStringRef> urlStringWK(AdoptWK, WKURLCopyString(URL));
2633     m_currentInvocation->outputText(String::format("WebView updated the title for history URL \"%s\" to \"%s\".\n", toSTD(urlStringWK).c_str(), toSTD(title).c_str()));
2634 }
2635
2636 void TestController::setNavigationGesturesEnabled(bool value)
2637 {
2638     m_mainWebView->setNavigationGesturesEnabled(value);
2639 }
2640
2641 void TestController::setIgnoresViewportScaleLimits(bool ignoresViewportScaleLimits)
2642 {
2643     WKPageSetIgnoresViewportScaleLimits(m_mainWebView->page(), ignoresViewportScaleLimits);
2644 }
2645
2646 void TestController::terminateNetworkProcess()
2647 {
2648     WKContextTerminateNetworkProcess(platformContext());
2649 }
2650
2651 void TestController::terminateServiceWorkerProcess()
2652 {
2653     WKContextTerminateServiceWorkerProcess(platformContext());
2654 }
2655
2656 #if !PLATFORM(COCOA)
2657 void TestController::platformWillRunTest(const TestInvocation&)
2658 {
2659 }
2660
2661 void TestController::platformCreateWebView(WKPageConfigurationRef configuration, const TestOptions& options)
2662 {
2663     m_mainWebView = std::make_unique<PlatformWebView>(configuration, options);
2664 }
2665
2666 PlatformWebView* TestController::platformCreateOtherPage(PlatformWebView* parentView, WKPageConfigurationRef configuration, const TestOptions& options)
2667 {
2668     return new PlatformWebView(configuration, options);
2669 }
2670
2671 WKContextRef TestController::platformAdjustContext(WKContextRef context, WKContextConfigurationRef contextConfiguration)
2672 {
2673     auto* dataStore = WKContextGetWebsiteDataStore(context);
2674     WKWebsiteDataStoreSetResourceLoadStatisticsEnabled(dataStore, true);
2675
2676     if (const char* dumpRenderTreeTemp = libraryPathForTesting()) {
2677         String temporaryFolder = String::fromUTF8(dumpRenderTreeTemp);
2678         const char separator = '/';
2679
2680         WKWebsiteDataStoreSetServiceWorkerRegistrationDirectory(dataStore, toWK(temporaryFolder + separator + "ServiceWorkers").get());
2681     }
2682
2683     return context;
2684 }
2685
2686 void TestController::platformResetStateToConsistentValues(const TestOptions&)
2687 {
2688 }
2689
2690 unsigned TestController::imageCountInGeneralPasteboard() const
2691 {
2692     return 0;
2693 }
2694
2695 void TestController::removeAllSessionCredentials()
2696 {
2697 }
2698
2699 void TestController::getAllStorageAccessEntries()
2700 {
2701 }
2702
2703 #endif
2704
2705 struct ClearServiceWorkerRegistrationsCallbackContext {
2706     explicit ClearServiceWorkerRegistrationsCallbackContext(TestController& controller)
2707         : testController(controller)
2708     {
2709     }
2710
2711     TestController& testController;
2712     bool done { false };
2713 };
2714
2715 static void clearServiceWorkerRegistrationsCallback(void* userData)
2716 {
2717     auto* context = static_cast<ClearServiceWorkerRegistrationsCallbackContext*>(userData);
2718     context->done = true;
2719     context->testController.notifyDone();
2720 }
2721
2722 void TestController::clearServiceWorkerRegistrations()
2723 {
2724     auto websiteDataStore = WKContextGetWebsiteDataStore(platformContext());
2725     ClearServiceWorkerRegistrationsCallbackContext context(*this);
2726
2727     WKWebsiteDataStoreRemoveAllServiceWorkerRegistrations(websiteDataStore, &context, clearServiceWorkerRegistrationsCallback);
2728     runUntil(context.done, noTimeout);
2729 }
2730
2731 struct ClearDOMCacheCallbackContext {
2732     explicit ClearDOMCacheCallbackContext(TestController& controller)
2733         : testController(controller)
2734     {
2735     }
2736
2737     TestController& testController;
2738     bool done { false };
2739 };
2740
2741 static void clearDOMCacheCallback(void* userData)
2742 {
2743     auto* context = static_cast<ClearDOMCacheCallbackContext*>(userData);
2744     context->done = true;
2745     context->testController.notifyDone();
2746 }
2747
2748 void TestController::clearDOMCache(WKStringRef origin)
2749 {
2750     auto websiteDataStore = WKContextGetWebsiteDataStore(platformContext());
2751     ClearDOMCacheCallbackContext context(*this);
2752
2753     auto cacheOrigin = adoptWK(WKSecurityOriginCreateFromString(origin));
2754     WKWebsiteDataStoreRemoveFetchCacheForOrigin(websiteDataStore, cacheOrigin.get(), &context, clearDOMCacheCallback);
2755     runUntil(context.done, noTimeout);
2756 }
2757
2758 void TestController::clearDOMCaches()
2759 {
2760     auto websiteDataStore = WKContextGetWebsiteDataStore(platformContext());
2761     ClearDOMCacheCallbackContext context(*this);
2762
2763     WKWebsiteDataStoreRemoveAllFetchCaches(websiteDataStore, &context, clearDOMCacheCallback);
2764     runUntil(context.done, noTimeout);
2765 }
2766
2767 void TestController::setIDBPerOriginQuota(uint64_t quota)
2768 {
2769     WKContextSetIDBPerOriginQuota(platformContext(), quota);
2770 }
2771
2772 struct RemoveAllIndexedDatabasesCallbackContext {
2773     explicit RemoveAllIndexedDatabasesCallbackContext(TestController& controller)
2774         : testController(controller)
2775     {
2776     }
2777
2778     TestController& testController;
2779     bool done { false };
2780 };
2781
2782 static void RemoveAllIndexedDatabasesCallback(void* userData)
2783 {
2784     auto* context = static_cast<RemoveAllIndexedDatabasesCallbackContext*>(userData);
2785     context->done = true;
2786     context->testController.notifyDone();
2787 }
2788
2789 void TestController::ClearIndexedDatabases()
2790 {
2791     auto websiteDataStore = WKContextGetWebsiteDataStore(platformContext());
2792     RemoveAllIndexedDatabasesCallbackContext context(*this);
2793     WKWebsiteDataStoreRemoveAllIndexedDatabases(websiteDataStore, &context, RemoveAllIndexedDatabasesCallback);
2794     runUntil(context.done, noTimeout);
2795 }
2796
2797 struct FetchCacheOriginsCallbackContext {
2798     FetchCacheOriginsCallbackContext(TestController& controller, WKStringRef origin)
2799         : testController(controller)
2800         , origin(origin)
2801     {
2802     }
2803
2804     TestController& testController;
2805     WKStringRef origin;
2806
2807     bool done { false };
2808     bool result { false };
2809 };
2810
2811 static void fetchCacheOriginsCallback(WKArrayRef origins, void* userData)
2812 {
2813     auto* context = static_cast<FetchCacheOriginsCallbackContext*>(userData);
2814     context->done = true;
2815
2816     auto size = WKArrayGetSize(origins);
2817     for (size_t index = 0; index < size && !context->result; ++index) {
2818         WKSecurityOriginRef securityOrigin = reinterpret_cast<WKSecurityOriginRef>(WKArrayGetItemAtIndex(origins, index));
2819         if (WKStringIsEqual(context->origin, adoptWK(WKSecurityOriginCopyToString(securityOrigin)).get()))
2820             context->result = true;
2821     }
2822     context->testController.notifyDone();
2823 }
2824
2825 bool TestController::hasDOMCache(WKStringRef origin)
2826 {
2827     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2828     FetchCacheOriginsCallbackContext context(*this, origin);
2829     WKWebsiteDataStoreGetFetchCacheOrigins(dataStore, &context, fetchCacheOriginsCallback);
2830     runUntil(context.done, noTimeout);
2831     return context.result;
2832 }
2833
2834 struct FetchCacheSizeForOriginCallbackContext {
2835     explicit FetchCacheSizeForOriginCallbackContext(TestController& controller)
2836         : testController(controller)
2837     {
2838     }
2839
2840     TestController& testController;
2841
2842     bool done { false };
2843     uint64_t result { 0 };
2844 };
2845
2846 static void fetchCacheSizeForOriginCallback(uint64_t size, void* userData)
2847 {
2848     auto* context = static_cast<FetchCacheSizeForOriginCallbackContext*>(userData);
2849     context->done = true;
2850     context->result = size;
2851     context->testController.notifyDone();
2852 }
2853
2854 uint64_t TestController::domCacheSize(WKStringRef origin)
2855 {
2856     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2857     FetchCacheSizeForOriginCallbackContext context(*this);
2858     WKWebsiteDataStoreGetFetchCacheSizeForOrigin(dataStore, origin, &context, fetchCacheSizeForOriginCallback);
2859     runUntil(context.done, noTimeout);
2860     return context.result;
2861 }
2862
2863 #if !PLATFORM(COCOA)
2864 void TestController::allowCacheStorageQuotaIncrease()
2865 {
2866     // FIXME: To implement.
2867 }
2868 #endif
2869
2870 struct ResourceStatisticsCallbackContext {
2871     explicit ResourceStatisticsCallbackContext(TestController& controller)
2872         : testController(controller)
2873     {
2874     }
2875
2876     TestController& testController;
2877     bool done { false };
2878     bool result { false };
2879     WKRetainPtr<WKStringRef> resourceLoadStatisticsRepresentation;
2880 };
2881     
2882 static void resourceStatisticsStringResultCallback(WKStringRef resourceLoadStatisticsRepresentation, void* userData)
2883 {
2884     auto* context = static_cast<ResourceStatisticsCallbackContext*>(userData);
2885     context->resourceLoadStatisticsRepresentation = resourceLoadStatisticsRepresentation;
2886     context->done = true;
2887     context->testController.notifyDone();
2888 }
2889
2890 static void resourceStatisticsVoidResultCallback(void* userData)
2891 {
2892     auto* context = static_cast<ResourceStatisticsCallbackContext*>(userData);
2893     context->done = true;
2894     context->testController.notifyDone();
2895 }
2896
2897 static void resourceStatisticsBooleanResultCallback(bool result, void* userData)
2898 {
2899     auto* context = static_cast<ResourceStatisticsCallbackContext*>(userData);
2900     context->result = result;
2901     context->done = true;
2902     context->testController.notifyDone();
2903 }
2904
2905 void TestController::setStatisticsDebugMode(bool value)
2906 {
2907     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2908     ResourceStatisticsCallbackContext context(*this);
2909     WKWebsiteDataStoreSetResourceLoadStatisticsDebugModeWithCompletionHandler(dataStore, value, &context, resourceStatisticsVoidResultCallback);
2910     runUntil(context.done, noTimeout);
2911     m_currentInvocation->didSetStatisticsDebugMode();
2912 }
2913
2914 void TestController::setStatisticsPrevalentResourceForDebugMode(WKStringRef hostName)
2915 {
2916     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2917     ResourceStatisticsCallbackContext context(*this);
2918     WKWebsiteDataStoreSetResourceLoadStatisticsPrevalentResourceForDebugMode(dataStore, hostName, &context, resourceStatisticsVoidResultCallback);
2919     runUntil(context.done, noTimeout);
2920     m_currentInvocation->didSetPrevalentResourceForDebugMode();
2921 }
2922
2923 void TestController::setStatisticsLastSeen(WKStringRef host, double seconds)
2924 {
2925     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2926     ResourceStatisticsCallbackContext context(*this);
2927     WKWebsiteDataStoreSetStatisticsLastSeen(dataStore, host, seconds, &context, resourceStatisticsVoidResultCallback);
2928     runUntil(context.done, noTimeout);
2929     m_currentInvocation->didSetLastSeen();
2930 }
2931
2932 void TestController::setStatisticsPrevalentResource(WKStringRef host, bool value)
2933 {
2934     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2935     ResourceStatisticsCallbackContext context(*this);
2936     WKWebsiteDataStoreSetStatisticsPrevalentResource(dataStore, host, value, &context, resourceStatisticsVoidResultCallback);
2937     runUntil(context.done, noTimeout);
2938     m_currentInvocation->didSetPrevalentResource();
2939 }
2940
2941 void TestController::setStatisticsVeryPrevalentResource(WKStringRef host, bool value)
2942 {
2943     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2944     ResourceStatisticsCallbackContext context(*this);
2945     WKWebsiteDataStoreSetStatisticsVeryPrevalentResource(dataStore, host, value, &context, resourceStatisticsVoidResultCallback);
2946     runUntil(context.done, noTimeout);
2947     m_currentInvocation->didSetVeryPrevalentResource();
2948 }
2949     
2950 String TestController::dumpResourceLoadStatistics()
2951 {
2952     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2953     ResourceStatisticsCallbackContext context(*this);
2954     WKWebsiteDataStoreDumpResourceLoadStatistics(dataStore, &context, resourceStatisticsStringResultCallback);
2955     runUntil(context.done, noTimeout);
2956     return toWTFString(context.resourceLoadStatisticsRepresentation.get());
2957 }
2958
2959 bool TestController::isStatisticsPrevalentResource(WKStringRef host)
2960 {
2961     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2962     ResourceStatisticsCallbackContext context(*this);
2963     WKWebsiteDataStoreIsStatisticsPrevalentResource(dataStore, host, &context, resourceStatisticsBooleanResultCallback);
2964     runUntil(context.done, noTimeout);
2965     return context.result;
2966 }
2967
2968 bool TestController::isStatisticsVeryPrevalentResource(WKStringRef host)
2969 {
2970     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2971     ResourceStatisticsCallbackContext context(*this);
2972     WKWebsiteDataStoreIsStatisticsVeryPrevalentResource(dataStore, host, &context, resourceStatisticsBooleanResultCallback);
2973     runUntil(context.done, noTimeout);
2974     return context.result;
2975 }
2976
2977 bool TestController::isStatisticsRegisteredAsSubresourceUnder(WKStringRef subresourceHost, WKStringRef topFrameHost)
2978 {
2979     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2980     ResourceStatisticsCallbackContext context(*this);
2981     WKWebsiteDataStoreIsStatisticsRegisteredAsSubresourceUnder(dataStore, subresourceHost, topFrameHost, &context, resourceStatisticsBooleanResultCallback);
2982     runUntil(context.done, noTimeout);
2983     return context.result;
2984 }
2985
2986 bool TestController::isStatisticsRegisteredAsSubFrameUnder(WKStringRef subFrameHost, WKStringRef topFrameHost)
2987 {
2988     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2989     ResourceStatisticsCallbackContext context(*this);
2990     WKWebsiteDataStoreIsStatisticsRegisteredAsSubFrameUnder(dataStore, subFrameHost, topFrameHost, &context, resourceStatisticsBooleanResultCallback);
2991     runUntil(context.done, noTimeout);
2992     return context.result;
2993 }
2994
2995 bool TestController::isStatisticsRegisteredAsRedirectingTo(WKStringRef hostRedirectedFrom, WKStringRef hostRedirectedTo)
2996 {
2997     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2998     ResourceStatisticsCallbackContext context(*this);
2999     WKWebsiteDataStoreIsStatisticsRegisteredAsRedirectingTo(dataStore, hostRedirectedFrom, hostRedirectedTo, &context, resourceStatisticsBooleanResultCallback);
3000     runUntil(context.done, noTimeout);
3001     return context.result;
3002 }
3003
3004 void TestController::setStatisticsHasHadUserInteraction(WKStringRef host, bool value)
3005 {
3006     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3007     ResourceStatisticsCallbackContext context(*this);
3008     WKWebsiteDataStoreSetStatisticsHasHadUserInteraction(dataStore, host, value, &context, resourceStatisticsVoidResultCallback);
3009     runUntil(context.done, noTimeout);
3010     m_currentInvocation->didSetHasHadUserInteraction();
3011 }
3012
3013 bool TestController::isStatisticsHasHadUserInteraction(WKStringRef host)
3014 {
3015     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3016     ResourceStatisticsCallbackContext context(*this);
3017     WKWebsiteDataStoreIsStatisticsHasHadUserInteraction(dataStore, host, &context, resourceStatisticsBooleanResultCallback);
3018     runUntil(context.done, noTimeout);
3019     return context.result;
3020 }
3021
3022 void TestController::setStatisticsGrandfathered(WKStringRef host, bool value)
3023 {
3024     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3025     WKWebsiteDataStoreSetStatisticsGrandfathered(dataStore, host, value);
3026 }
3027
3028 bool TestController::isStatisticsGrandfathered(WKStringRef host)
3029 {
3030     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3031     ResourceStatisticsCallbackContext context(*this);
3032     WKWebsiteDataStoreIsStatisticsGrandfathered(dataStore, host, &context, resourceStatisticsBooleanResultCallback);
3033     runUntil(context.done, noTimeout);
3034     return context.result;
3035 }
3036
3037 void TestController::setStatisticsSubframeUnderTopFrameOrigin(WKStringRef host, WKStringRef topFrameHost)
3038 {
3039     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3040     WKWebsiteDataStoreSetStatisticsSubframeUnderTopFrameOrigin(dataStore, host, topFrameHost);
3041 }
3042
3043 void TestController::setStatisticsSubresourceUnderTopFrameOrigin(WKStringRef host, WKStringRef topFrameHost)
3044 {
3045     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3046     WKWebsiteDataStoreSetStatisticsSubresourceUnderTopFrameOrigin(dataStore, host, topFrameHost);
3047 }
3048
3049 void TestController::setStatisticsSubresourceUniqueRedirectTo(WKStringRef host, WKStringRef hostRedirectedTo)
3050 {
3051     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3052     WKWebsiteDataStoreSetStatisticsSubresourceUniqueRedirectTo(dataStore, host, hostRedirectedTo);
3053 }
3054
3055 void TestController::setStatisticsSubresourceUniqueRedirectFrom(WKStringRef host, WKStringRef hostRedirectedFrom)
3056 {
3057     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3058     WKWebsiteDataStoreSetStatisticsSubresourceUniqueRedirectFrom(dataStore, host, hostRedirectedFrom);
3059 }
3060
3061 void TestController::setStatisticsTopFrameUniqueRedirectTo(WKStringRef host, WKStringRef hostRedirectedTo)
3062 {
3063     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3064     WKWebsiteDataStoreSetStatisticsTopFrameUniqueRedirectTo(dataStore, host, hostRedirectedTo);
3065 }
3066
3067 void TestController::setStatisticsTopFrameUniqueRedirectFrom(WKStringRef host, WKStringRef hostRedirectedFrom)
3068 {
3069     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3070     WKWebsiteDataStoreSetStatisticsTopFrameUniqueRedirectFrom(dataStore, host, hostRedirectedFrom);
3071 }
3072
3073 void TestController::setStatisticsTimeToLiveUserInteraction(double seconds)
3074 {
3075     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3076     WKWebsiteDataStoreSetStatisticsTimeToLiveUserInteraction(dataStore, seconds);
3077 }
3078
3079 void TestController::statisticsProcessStatisticsAndDataRecords()
3080 {
3081     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3082     WKWebsiteDataStoreStatisticsProcessStatisticsAndDataRecords(dataStore);
3083 }
3084
3085 void TestController::statisticsUpdateCookieBlocking()
3086 {
3087     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3088     ResourceStatisticsCallbackContext context(*this);
3089     WKWebsiteDataStoreStatisticsUpdateCookieBlocking(dataStore, &context, resourceStatisticsVoidResultCallback);
3090     runUntil(context.done, noTimeout);
3091     m_currentInvocation->didSetBlockCookiesForHost();
3092 }
3093
3094 void TestController::statisticsSubmitTelemetry()
3095 {
3096     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3097     WKWebsiteDataStoreStatisticsSubmitTelemetry(dataStore);
3098 }
3099
3100 void TestController::setStatisticsNotifyPagesWhenDataRecordsWereScanned(bool value)
3101 {
3102     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3103     WKWebsiteDataStoreSetStatisticsNotifyPagesWhenDataRecordsWereScanned(dataStore, value);
3104 }
3105
3106 void TestController::setStatisticsShouldClassifyResourcesBeforeDataRecordsRemoval(bool value)
3107 {
3108     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3109     WKWebsiteDataStoreSetStatisticsShouldClassifyResourcesBeforeDataRecordsRemoval(dataStore, value);
3110 }
3111
3112 void TestController::setStatisticsNotifyPagesWhenTelemetryWasCaptured(bool value)
3113 {
3114     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3115     WKWebsiteDataStoreSetStatisticsNotifyPagesWhenTelemetryWasCaptured(dataStore, value);
3116 }
3117
3118 void TestController::setStatisticsMinimumTimeBetweenDataRecordsRemoval(double seconds)
3119 {
3120     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3121     WKWebsiteDataStoreSetStatisticsMinimumTimeBetweenDataRecordsRemoval(dataStore, seconds);
3122 }
3123
3124 void TestController::setStatisticsGrandfatheringTime(double seconds)
3125 {
3126     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3127     WKWebsiteDataStoreSetStatisticsGrandfatheringTime(dataStore, seconds);
3128 }
3129
3130 void TestController::setStatisticsMaxStatisticsEntries(unsigned entries)
3131 {
3132     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3133     WKWebsiteDataStoreSetStatisticsMaxStatisticsEntries(dataStore, entries);
3134 }
3135
3136 void TestController::setStatisticsPruneEntriesDownTo(unsigned entries)
3137 {
3138     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3139     WKWebsiteDataStoreSetStatisticsPruneEntriesDownTo(dataStore, entries);
3140 }
3141
3142 void TestController::statisticsClearInMemoryAndPersistentStore()
3143 {
3144     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3145     ResourceStatisticsCallbackContext context(*this);
3146     WKWebsiteDataStoreStatisticsClearInMemoryAndPersistentStore(dataStore, &context, resourceStatisticsVoidResultCallback);
3147     runUntil(context.done, noTimeout);
3148     m_currentInvocation->didClearStatisticsThroughWebsiteDataRemoval();
3149 }
3150
3151 void TestController::statisticsClearInMemoryAndPersistentStoreModifiedSinceHours(unsigned hours)
3152 {
3153     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3154     ResourceStatisticsCallbackContext context(*this);
3155     WKWebsiteDataStoreStatisticsClearInMemoryAndPersistentStoreModifiedSinceHours(dataStore, hours, &context, resourceStatisticsVoidResultCallback);
3156     runUntil(context.done, noTimeout);
3157     m_currentInvocation->didClearStatisticsThroughWebsiteDataRemoval();
3158 }
3159
3160 void TestController::statisticsClearThroughWebsiteDataRemoval()
3161 {
3162     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3163     ResourceStatisticsCallbackContext context(*this);
3164     WKWebsiteDataStoreStatisticsClearThroughWebsiteDataRemoval(dataStore, &context, resourceStatisticsVoidResultCallback);
3165     runUntil(context.done, noTimeout);
3166     m_currentInvocation->didClearStatisticsThroughWebsiteDataRemoval();
3167 }
3168
3169 void TestController::setStatisticsCacheMaxAgeCap(double seconds)
3170 {
3171     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3172     ResourceStatisticsCallbackContext context(*this);
3173     WKWebsiteDataStoreSetStatisticsCacheMaxAgeCap(dataStore, seconds, &context, resourceStatisticsVoidResultCallback);
3174     runUntil(context.done, noTimeout);
3175 }
3176
3177 void TestController::statisticsResetToConsistentState()
3178 {
3179     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
3180     ResourceStatisticsCallbackContext context(*this);
3181     WKWebsiteDataStoreStatisticsResetToConsistentState(dataStore, &context, resourceStatisticsVoidResultCallback);
3182     runUntil(context.done, noTimeout);
3183     m_currentInvocation->didResetStatisticsToConsistentState();
3184 }
3185
3186 void TestController::addMockMediaDevice(WKStringRef persistentID, WKStringRef label, WKStringRef type)
3187 {
3188     WKAddMockMediaDevice(platformContext(), persistentID, label, type);
3189 }
3190
3191 void TestController::clearMockMediaDevices()
3192 {
3193     WKClearMockMediaDevices(platformContext());
3194 }
3195
3196 void TestController::removeMockMediaDevice(WKStringRef persistentID)
3197 {
3198     WKRemoveMockMediaDevice(platformContext(), persistentID);
3199 }
3200
3201 void TestController::resetMockMediaDevices()
3202 {
3203     WKResetMockMediaDevices(platformContext());
3204 }
3205
3206 #if !PLATFORM(COCOA)
3207 void TestController::platformAddTestOptions(TestOptions&) const
3208 {
3209 }
3210
3211 void TestController::injectUserScript(WKStringRef)
3212 {
3213 }
3214
3215 void TestController::addTestKeyToKeychain(const String&, const String&, const String&)
3216 {
3217 }
3218
3219 void TestController::cleanUpKeychain(const String&)
3220 {
3221 }
3222
3223 bool TestController::keyExistsInKeychain(const String&, const String&)
3224 {
3225     return false;
3226 }
3227 #endif
3228
3229 void TestController::sendDisplayConfigurationChangedMessageForTesting()
3230 {
3231     WKSendDisplayConfigurationChangedMessageForTesting(platformContext());
3232 }
3233
3234 void TestController::setWebAuthenticationMockConfiguration(WKDictionaryRef configuration)
3235 {
3236     WKWebsiteDataStoreSetWebAuthenticationMockConfiguration(WKContextGetWebsiteDataStore(platformContext()), configuration);
3237 }
3238
3239 } // namespace WTR