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