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