ee6b0859c584f43b0ec31d0afa665f91e325b498
[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
1142     return options;
1143 }
1144
1145 void TestController::updateWebViewSizeForTest(const TestInvocation& test)
1146 {
1147     unsigned width = viewWidth;
1148     unsigned height = viewHeight;
1149     if (test.options().isSVGTest) {
1150         width = w3cSVGViewWidth;
1151         height = w3cSVGViewHeight;
1152     }
1153
1154     mainWebView()->resizeTo(width, height);
1155 }
1156
1157 void TestController::updateWindowScaleForTest(PlatformWebView* view, const TestInvocation& test)
1158 {
1159     view->changeWindowScaleIfNeeded(test.options().deviceScaleFactor);
1160 }
1161
1162 void TestController::configureViewForTest(const TestInvocation& test)
1163 {
1164     ensureViewSupportsOptionsForTest(test);
1165     updateWebViewSizeForTest(test);
1166     updateWindowScaleForTest(mainWebView(), test);
1167
1168     platformConfigureViewForTest(test);
1169 }
1170
1171 class CommandTokenizer {
1172 public:
1173     explicit CommandTokenizer(const std::string& input)
1174         : m_input(input)
1175         , m_posNextSeparator(0)
1176     {
1177         pump();
1178     }
1179
1180     bool hasNext() const;
1181     std::string next();
1182
1183 private:
1184     void pump();
1185     static const char kSeparator = '\'';
1186     const std::string& m_input;
1187     std::string m_next;
1188     size_t m_posNextSeparator;
1189 };
1190
1191 void CommandTokenizer::pump()
1192 {
1193     if (m_posNextSeparator == std::string::npos || m_posNextSeparator == m_input.size()) {
1194         m_next = std::string();
1195         return;
1196     }
1197     size_t start = m_posNextSeparator ? m_posNextSeparator + 1 : 0;
1198     m_posNextSeparator = m_input.find(kSeparator, start);
1199     size_t size = m_posNextSeparator == std::string::npos ? std::string::npos : m_posNextSeparator - start;
1200     m_next = std::string(m_input, start, size);
1201 }
1202
1203 std::string CommandTokenizer::next()
1204 {
1205     ASSERT(hasNext());
1206
1207     std::string oldNext = m_next;
1208     pump();
1209     return oldNext;
1210 }
1211
1212 bool CommandTokenizer::hasNext() const
1213 {
1214     return !m_next.empty();
1215 }
1216
1217 NO_RETURN static void die(const std::string& inputLine)
1218 {
1219     fprintf(stderr, "Unexpected input line: %s\n", inputLine.c_str());
1220     exit(1);
1221 }
1222
1223 TestCommand parseInputLine(const std::string& inputLine)
1224 {
1225     TestCommand result;
1226     CommandTokenizer tokenizer(inputLine);
1227     if (!tokenizer.hasNext())
1228         die(inputLine);
1229
1230     std::string arg = tokenizer.next();
1231     result.pathOrURL = arg;
1232     while (tokenizer.hasNext()) {
1233         arg = tokenizer.next();
1234         if (arg == std::string("--timeout")) {
1235             std::string timeoutToken = tokenizer.next();
1236             result.timeout = atoi(timeoutToken.c_str());
1237         } else if (arg == std::string("-p") || arg == std::string("--pixel-test")) {
1238             result.shouldDumpPixels = true;
1239             if (tokenizer.hasNext())
1240                 result.expectedPixelHash = tokenizer.next();
1241         } else if (arg == std::string("--dump-jsconsolelog-in-stderr"))
1242             result.dumpJSConsoleLogInStdErr = true;
1243         else if (arg == std::string("--absolutePath"))
1244             result.absolutePath = tokenizer.next();
1245         else
1246             die(inputLine);
1247     }
1248     return result;
1249 }
1250
1251 bool TestController::runTest(const char* inputLine)
1252 {
1253     AutodrainedPool pool;
1254     
1255     WKTextCheckerSetTestingMode(true);
1256     TestCommand command = parseInputLine(std::string(inputLine));
1257
1258     m_state = RunningTest;
1259     
1260     TestOptions options = testOptionsForTest(command);
1261
1262     WKRetainPtr<WKURLRef> wkURL(AdoptWK, createTestURL(command.pathOrURL.c_str()));
1263     m_currentInvocation = std::make_unique<TestInvocation>(wkURL.get(), options);
1264
1265     if (command.shouldDumpPixels || m_shouldDumpPixelsForAllTests)
1266         m_currentInvocation->setIsPixelTest(command.expectedPixelHash);
1267     if (command.timeout > 0)
1268         m_currentInvocation->setCustomTimeout(command.timeout);
1269     m_currentInvocation->setDumpJSConsoleLogInStdErr(command.dumpJSConsoleLogInStdErr || options.dumpJSConsoleLogInStdErr);
1270
1271     platformWillRunTest(*m_currentInvocation);
1272
1273     m_currentInvocation->invoke();
1274     m_currentInvocation = nullptr;
1275
1276     return true;
1277 }
1278
1279 void TestController::runTestingServerLoop()
1280 {
1281     char filenameBuffer[2048];
1282     while (fgets(filenameBuffer, sizeof(filenameBuffer), stdin)) {
1283         char* newLineCharacter = strchr(filenameBuffer, '\n');
1284         if (newLineCharacter)
1285             *newLineCharacter = '\0';
1286
1287         if (strlen(filenameBuffer) == 0)
1288             continue;
1289
1290         if (!runTest(filenameBuffer))
1291             break;
1292     }
1293 }
1294
1295 void TestController::run()
1296 {
1297     if (m_usingServerMode)
1298         runTestingServerLoop();
1299     else {
1300         for (size_t i = 0; i < m_paths.size(); ++i) {
1301             if (!runTest(m_paths[i].c_str()))
1302                 break;
1303         }
1304     }
1305 }
1306
1307 void TestController::runUntil(bool& done, double timeout)
1308 {
1309     if (m_forceNoTimeout)
1310         timeout = noTimeout;
1311
1312     platformRunUntil(done, timeout);
1313 }
1314
1315 // WKContextInjectedBundleClient
1316
1317 void TestController::didReceiveMessageFromInjectedBundle(WKContextRef context, WKStringRef messageName, WKTypeRef messageBody, const void* clientInfo)
1318 {
1319     static_cast<TestController*>(const_cast<void*>(clientInfo))->didReceiveMessageFromInjectedBundle(messageName, messageBody);
1320 }
1321
1322 void TestController::didReceiveSynchronousMessageFromInjectedBundle(WKContextRef context, WKStringRef messageName, WKTypeRef messageBody, WKTypeRef* returnData, const void* clientInfo)
1323 {
1324     *returnData = static_cast<TestController*>(const_cast<void*>(clientInfo))->didReceiveSynchronousMessageFromInjectedBundle(messageName, messageBody).leakRef();
1325 }
1326
1327 WKTypeRef TestController::getInjectedBundleInitializationUserData(WKContextRef, const void* clientInfo)
1328 {
1329     return static_cast<TestController*>(const_cast<void*>(clientInfo))->getInjectedBundleInitializationUserData().leakRef();
1330 }
1331
1332 // WKPageInjectedBundleClient
1333
1334 void TestController::didReceivePageMessageFromInjectedBundle(WKPageRef page, WKStringRef messageName, WKTypeRef messageBody, const void* clientInfo)
1335 {
1336     static_cast<TestController*>(const_cast<void*>(clientInfo))->didReceiveMessageFromInjectedBundle(messageName, messageBody);
1337 }
1338
1339 void TestController::didReceiveSynchronousPageMessageFromInjectedBundle(WKPageRef page, WKStringRef messageName, WKTypeRef messageBody, WKTypeRef* returnData, const void* clientInfo)
1340 {
1341     *returnData = static_cast<TestController*>(const_cast<void*>(clientInfo))->didReceiveSynchronousMessageFromInjectedBundle(messageName, messageBody).leakRef();
1342 }
1343
1344 void TestController::networkProcessDidCrash(WKContextRef context, const void *clientInfo)
1345 {
1346     static_cast<TestController*>(const_cast<void*>(clientInfo))->networkProcessDidCrash();
1347 }
1348
1349 void TestController::databaseProcessDidCrash(WKContextRef context, const void *clientInfo)
1350 {
1351     static_cast<TestController*>(const_cast<void*>(clientInfo))->databaseProcessDidCrash();
1352 }
1353
1354 void TestController::didReceiveKeyDownMessageFromInjectedBundle(WKDictionaryRef messageBodyDictionary, bool synchronous)
1355 {
1356     WKRetainPtr<WKStringRef> keyKey = adoptWK(WKStringCreateWithUTF8CString("Key"));
1357     WKStringRef key = static_cast<WKStringRef>(WKDictionaryGetItemForKey(messageBodyDictionary, keyKey.get()));
1358
1359     WKRetainPtr<WKStringRef> modifiersKey = adoptWK(WKStringCreateWithUTF8CString("Modifiers"));
1360     WKEventModifiers modifiers = static_cast<WKEventModifiers>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, modifiersKey.get()))));
1361
1362     WKRetainPtr<WKStringRef> locationKey = adoptWK(WKStringCreateWithUTF8CString("Location"));
1363     unsigned location = static_cast<unsigned>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, locationKey.get()))));
1364
1365     m_eventSenderProxy->keyDown(key, modifiers, location);
1366 }
1367
1368 void TestController::didReceiveMessageFromInjectedBundle(WKStringRef messageName, WKTypeRef messageBody)
1369 {
1370     if (WKStringIsEqualToUTF8CString(messageName, "EventSender")) {
1371         if (m_state != RunningTest)
1372             return;
1373
1374         ASSERT(WKGetTypeID(messageBody) == WKDictionaryGetTypeID());
1375         WKDictionaryRef messageBodyDictionary = static_cast<WKDictionaryRef>(messageBody);
1376
1377         WKRetainPtr<WKStringRef> subMessageKey(AdoptWK, WKStringCreateWithUTF8CString("SubMessage"));
1378         WKStringRef subMessageName = static_cast<WKStringRef>(WKDictionaryGetItemForKey(messageBodyDictionary, subMessageKey.get()));
1379
1380         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseDown") || WKStringIsEqualToUTF8CString(subMessageName, "MouseUp")) {
1381             WKRetainPtr<WKStringRef> buttonKey = adoptWK(WKStringCreateWithUTF8CString("Button"));
1382             unsigned button = static_cast<unsigned>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, buttonKey.get()))));
1383
1384             WKRetainPtr<WKStringRef> modifiersKey = adoptWK(WKStringCreateWithUTF8CString("Modifiers"));
1385             WKEventModifiers modifiers = static_cast<WKEventModifiers>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, modifiersKey.get()))));
1386
1387             // Forward to WebProcess
1388             if (WKStringIsEqualToUTF8CString(subMessageName, "MouseDown"))
1389                 m_eventSenderProxy->mouseDown(button, modifiers);
1390             else
1391                 m_eventSenderProxy->mouseUp(button, modifiers);
1392
1393             return;
1394         }
1395
1396         if (WKStringIsEqualToUTF8CString(subMessageName, "KeyDown")) {
1397             didReceiveKeyDownMessageFromInjectedBundle(messageBodyDictionary, false);
1398
1399             return;
1400         }
1401
1402         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseScrollBy")) {
1403             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
1404             double x = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get())));
1405
1406             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
1407             double y = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get())));
1408
1409             // Forward to WebProcess
1410             m_eventSenderProxy->mouseScrollBy(x, y);
1411             return;
1412         }
1413
1414         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseScrollByWithWheelAndMomentumPhases")) {
1415             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
1416             double x = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get())));
1417             
1418             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
1419             double y = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get())));
1420             
1421             WKRetainPtr<WKStringRef> phaseKey = adoptWK(WKStringCreateWithUTF8CString("Phase"));
1422             int phase = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, phaseKey.get()))));
1423             WKRetainPtr<WKStringRef> momentumKey = adoptWK(WKStringCreateWithUTF8CString("Momentum"));
1424             int momentum = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, momentumKey.get()))));
1425             
1426             // Forward to WebProcess
1427             m_eventSenderProxy->mouseScrollByWithWheelAndMomentumPhases(x, y, phase, momentum);
1428
1429             return;
1430         }
1431
1432         ASSERT_NOT_REACHED();
1433     }
1434
1435     if (!m_currentInvocation)
1436         return;
1437
1438     m_currentInvocation->didReceiveMessageFromInjectedBundle(messageName, messageBody);
1439 }
1440
1441 WKRetainPtr<WKTypeRef> TestController::didReceiveSynchronousMessageFromInjectedBundle(WKStringRef messageName, WKTypeRef messageBody)
1442 {
1443     if (WKStringIsEqualToUTF8CString(messageName, "EventSender")) {
1444         if (m_state != RunningTest)
1445             return nullptr;
1446
1447         ASSERT(WKGetTypeID(messageBody) == WKDictionaryGetTypeID());
1448         WKDictionaryRef messageBodyDictionary = static_cast<WKDictionaryRef>(messageBody);
1449
1450         WKRetainPtr<WKStringRef> subMessageKey(AdoptWK, WKStringCreateWithUTF8CString("SubMessage"));
1451         WKStringRef subMessageName = static_cast<WKStringRef>(WKDictionaryGetItemForKey(messageBodyDictionary, subMessageKey.get()));
1452
1453         if (WKStringIsEqualToUTF8CString(subMessageName, "KeyDown")) {
1454             didReceiveKeyDownMessageFromInjectedBundle(messageBodyDictionary, true);
1455
1456             return 0;
1457         }
1458
1459         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseDown") || WKStringIsEqualToUTF8CString(subMessageName, "MouseUp")) {
1460             WKRetainPtr<WKStringRef> buttonKey = adoptWK(WKStringCreateWithUTF8CString("Button"));
1461             unsigned button = static_cast<unsigned>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, buttonKey.get()))));
1462
1463             WKRetainPtr<WKStringRef> modifiersKey = adoptWK(WKStringCreateWithUTF8CString("Modifiers"));
1464             WKEventModifiers modifiers = static_cast<WKEventModifiers>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, modifiersKey.get()))));
1465
1466             // Forward to WebProcess
1467             if (WKStringIsEqualToUTF8CString(subMessageName, "MouseDown"))
1468                 m_eventSenderProxy->mouseDown(button, modifiers);
1469             else
1470                 m_eventSenderProxy->mouseUp(button, modifiers);
1471             return 0;
1472         }
1473
1474         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseMoveTo")) {
1475             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
1476             double x = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get())));
1477
1478             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
1479             double y = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get())));
1480
1481             // Forward to WebProcess
1482             m_eventSenderProxy->mouseMoveTo(x, y);
1483             return 0;
1484         }
1485
1486 #if PLATFORM(MAC)
1487         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseForceClick")) {
1488             m_eventSenderProxy->mouseForceClick();
1489             return 0;
1490         }
1491
1492         if (WKStringIsEqualToUTF8CString(subMessageName, "StartAndCancelMouseForceClick")) {
1493             m_eventSenderProxy->startAndCancelMouseForceClick();
1494             return 0;
1495         }
1496
1497         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseForceDown")) {
1498             m_eventSenderProxy->mouseForceDown();
1499             return 0;
1500         }
1501
1502         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseForceUp")) {
1503             m_eventSenderProxy->mouseForceUp();
1504             return 0;
1505         }
1506
1507         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseForceChanged")) {
1508             WKRetainPtr<WKStringRef> forceKey = adoptWK(WKStringCreateWithUTF8CString("Force"));
1509             double force = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, forceKey.get())));
1510
1511             m_eventSenderProxy->mouseForceChanged(force);
1512             return 0;
1513         }
1514 #endif // PLATFORM(MAC)
1515
1516         if (WKStringIsEqualToUTF8CString(subMessageName, "ContinuousMouseScrollBy")) {
1517             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
1518             double x = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get())));
1519
1520             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
1521             double y = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get())));
1522
1523             WKRetainPtr<WKStringRef> pagedKey = adoptWK(WKStringCreateWithUTF8CString("Paged"));
1524             bool paged = static_cast<bool>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, pagedKey.get()))));
1525
1526             // Forward to WebProcess
1527             m_eventSenderProxy->continuousMouseScrollBy(x, y, paged);
1528             return 0;
1529         }
1530
1531         if (WKStringIsEqualToUTF8CString(subMessageName, "LeapForward")) {
1532             WKRetainPtr<WKStringRef> timeKey = adoptWK(WKStringCreateWithUTF8CString("TimeInMilliseconds"));
1533             unsigned time = static_cast<unsigned>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, timeKey.get()))));
1534
1535             m_eventSenderProxy->leapForward(time);
1536             return 0;
1537         }
1538
1539 #if ENABLE(TOUCH_EVENTS)
1540         if (WKStringIsEqualToUTF8CString(subMessageName, "AddTouchPoint")) {
1541             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
1542             int x = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get()))));
1543
1544             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
1545             int y = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get()))));
1546
1547             m_eventSenderProxy->addTouchPoint(x, y);
1548             return 0;
1549         }
1550
1551         if (WKStringIsEqualToUTF8CString(subMessageName, "UpdateTouchPoint")) {
1552             WKRetainPtr<WKStringRef> indexKey = adoptWK(WKStringCreateWithUTF8CString("Index"));
1553             int index = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, indexKey.get()))));
1554
1555             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
1556             int x = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get()))));
1557
1558             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
1559             int y = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get()))));
1560
1561             m_eventSenderProxy->updateTouchPoint(index, x, y);
1562             return 0;
1563         }
1564
1565         if (WKStringIsEqualToUTF8CString(subMessageName, "SetTouchModifier")) {
1566             WKRetainPtr<WKStringRef> modifierKey = adoptWK(WKStringCreateWithUTF8CString("Modifier"));
1567             WKEventModifiers modifier = static_cast<WKEventModifiers>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, modifierKey.get()))));
1568
1569             WKRetainPtr<WKStringRef> enableKey = adoptWK(WKStringCreateWithUTF8CString("Enable"));
1570             bool enable = static_cast<bool>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, enableKey.get()))));
1571
1572             m_eventSenderProxy->setTouchModifier(modifier, enable);
1573             return 0;
1574         }
1575
1576         if (WKStringIsEqualToUTF8CString(subMessageName, "SetTouchPointRadius")) {
1577             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("RadiusX"));
1578             int x = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get()))));
1579
1580             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("RadiusY"));
1581             int y = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get()))));
1582
1583             m_eventSenderProxy->setTouchPointRadius(x, y);
1584             return 0;
1585         }
1586
1587         if (WKStringIsEqualToUTF8CString(subMessageName, "TouchStart")) {
1588             m_eventSenderProxy->touchStart();
1589             return 0;
1590         }
1591
1592         if (WKStringIsEqualToUTF8CString(subMessageName, "TouchMove")) {
1593             m_eventSenderProxy->touchMove();
1594             return 0;
1595         }
1596
1597         if (WKStringIsEqualToUTF8CString(subMessageName, "TouchEnd")) {
1598             m_eventSenderProxy->touchEnd();
1599             return 0;
1600         }
1601
1602         if (WKStringIsEqualToUTF8CString(subMessageName, "TouchCancel")) {
1603             m_eventSenderProxy->touchCancel();
1604             return 0;
1605         }
1606
1607         if (WKStringIsEqualToUTF8CString(subMessageName, "ClearTouchPoints")) {
1608             m_eventSenderProxy->clearTouchPoints();
1609             return 0;
1610         }
1611
1612         if (WKStringIsEqualToUTF8CString(subMessageName, "ReleaseTouchPoint")) {
1613             WKRetainPtr<WKStringRef> indexKey = adoptWK(WKStringCreateWithUTF8CString("Index"));
1614             int index = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, indexKey.get()))));
1615             m_eventSenderProxy->releaseTouchPoint(index);
1616             return 0;
1617         }
1618
1619         if (WKStringIsEqualToUTF8CString(subMessageName, "CancelTouchPoint")) {
1620             WKRetainPtr<WKStringRef> indexKey = adoptWK(WKStringCreateWithUTF8CString("Index"));
1621             int index = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, indexKey.get()))));
1622             m_eventSenderProxy->cancelTouchPoint(index);
1623             return 0;
1624         }
1625 #endif
1626         ASSERT_NOT_REACHED();
1627     }
1628     return m_currentInvocation->didReceiveSynchronousMessageFromInjectedBundle(messageName, messageBody);
1629 }
1630
1631 WKRetainPtr<WKTypeRef> TestController::getInjectedBundleInitializationUserData()
1632 {
1633     return nullptr;
1634 }
1635
1636 // WKContextClient
1637
1638 void TestController::networkProcessDidCrash()
1639 {
1640     pid_t pid = WKContextGetNetworkProcessIdentifier(m_context.get());
1641     fprintf(stderr, "#CRASHED - %s (pid %ld)\n", networkProcessName(), static_cast<long>(pid));
1642     exit(1);
1643 }
1644
1645 void TestController::databaseProcessDidCrash()
1646 {
1647     pid_t pid = WKContextGetDatabaseProcessIdentifier(m_context.get());
1648     fprintf(stderr, "#CRASHED - %s (pid %ld)\n", databaseProcessName(), static_cast<long>(pid));
1649     exit(1);
1650 }
1651
1652 // WKPageNavigationClient
1653
1654 void TestController::didCommitNavigation(WKPageRef page, WKNavigationRef navigation, WKTypeRef, const void* clientInfo)
1655 {
1656     static_cast<TestController*>(const_cast<void*>(clientInfo))->didCommitNavigation(page, navigation);
1657 }
1658
1659 void TestController::didFinishNavigation(WKPageRef page, WKNavigationRef navigation, WKTypeRef, const void* clientInfo)
1660 {
1661     static_cast<TestController*>(const_cast<void*>(clientInfo))->didFinishNavigation(page, navigation);
1662 }
1663
1664 void TestController::didReceiveServerRedirectForProvisionalNavigation(WKPageRef page, WKNavigationRef navigation, WKTypeRef userData, const void* clientInfo)
1665 {
1666     static_cast<TestController*>(const_cast<void*>(clientInfo))->didReceiveServerRedirectForProvisionalNavigation(page, navigation, userData);
1667 }
1668
1669 bool TestController::canAuthenticateAgainstProtectionSpace(WKPageRef page, WKProtectionSpaceRef protectionSpace, const void* clientInfo)
1670 {
1671     return static_cast<TestController*>(const_cast<void*>(clientInfo))->canAuthenticateAgainstProtectionSpace(page, protectionSpace);
1672 }
1673
1674 void TestController::didReceiveAuthenticationChallenge(WKPageRef page, WKAuthenticationChallengeRef authenticationChallenge, const void *clientInfo)
1675 {
1676     static_cast<TestController*>(const_cast<void*>(clientInfo))->didReceiveAuthenticationChallenge(page, /*frame,*/ authenticationChallenge);
1677 }
1678
1679 void TestController::processDidCrash(WKPageRef page, const void* clientInfo)
1680 {
1681     static_cast<TestController*>(const_cast<void*>(clientInfo))->processDidCrash();
1682 }
1683
1684 void TestController::didBeginNavigationGesture(WKPageRef page, const void *clientInfo)
1685 {
1686     static_cast<TestController*>(const_cast<void*>(clientInfo))->didBeginNavigationGesture(page);
1687 }
1688
1689 void TestController::willEndNavigationGesture(WKPageRef page, WKBackForwardListItemRef backForwardListItem, const void *clientInfo)
1690 {
1691     static_cast<TestController*>(const_cast<void*>(clientInfo))->willEndNavigationGesture(page, backForwardListItem);
1692 }
1693
1694 void TestController::didEndNavigationGesture(WKPageRef page, WKBackForwardListItemRef backForwardListItem, const void *clientInfo)
1695 {
1696     static_cast<TestController*>(const_cast<void*>(clientInfo))->didEndNavigationGesture(page, backForwardListItem);
1697 }
1698
1699 void TestController::didRemoveNavigationGestureSnapshot(WKPageRef page, const void *clientInfo)
1700 {
1701     static_cast<TestController*>(const_cast<void*>(clientInfo))->didRemoveNavigationGestureSnapshot(page);
1702 }
1703
1704 WKPluginLoadPolicy TestController::decidePolicyForPluginLoad(WKPageRef page, WKPluginLoadPolicy currentPluginLoadPolicy, WKDictionaryRef pluginInformation, WKStringRef* unavailabilityDescription, const void* clientInfo)
1705 {
1706     return static_cast<TestController*>(const_cast<void*>(clientInfo))->decidePolicyForPluginLoad(page, currentPluginLoadPolicy, pluginInformation, unavailabilityDescription);
1707 }
1708
1709 WKPluginLoadPolicy TestController::decidePolicyForPluginLoad(WKPageRef, WKPluginLoadPolicy currentPluginLoadPolicy, WKDictionaryRef pluginInformation, WKStringRef* unavailabilityDescription)
1710 {
1711     if (m_shouldBlockAllPlugins)
1712         return kWKPluginLoadPolicyBlocked;
1713
1714 #if PLATFORM(MAC)
1715     WKStringRef bundleIdentifier = (WKStringRef)WKDictionaryGetItemForKey(pluginInformation, WKPluginInformationBundleIdentifierKey());
1716     if (!bundleIdentifier)
1717         return currentPluginLoadPolicy;
1718
1719     if (WKStringIsEqualToUTF8CString(bundleIdentifier, "com.apple.QuickTime Plugin.plugin"))
1720         return currentPluginLoadPolicy;
1721
1722     if (WKStringIsEqualToUTF8CString(bundleIdentifier, "com.apple.testnetscapeplugin"))
1723         return currentPluginLoadPolicy;
1724
1725     RELEASE_ASSERT_NOT_REACHED(); // Please don't use any other plug-ins in tests, as they will not be installed on all machines.
1726 #else
1727     return currentPluginLoadPolicy;
1728 #endif
1729 }
1730
1731 void TestController::setPluginSupportedMode(const String& mode)
1732 {
1733     if (m_unsupportedPluginMode == mode)
1734         return;
1735
1736     m_unsupportedPluginMode = mode;
1737     if (m_unsupportedPluginMode.isEmpty()) {
1738         WKContextClearSupportedPlugins(m_context.get());
1739         return;
1740     }
1741
1742     WKRetainPtr<WKMutableArrayRef> emptyArray = adoptWK(WKMutableArrayCreate());
1743     WKRetainPtr<WKStringRef> allOrigins = adoptWK(WKStringCreateWithUTF8CString(""));
1744     WKRetainPtr<WKStringRef> specificOrigin = adoptWK(WKStringCreateWithUTF8CString("localhost"));
1745
1746     WKRetainPtr<WKStringRef> pdfName = adoptWK(WKStringCreateWithUTF8CString("My personal PDF"));
1747     WKContextAddSupportedPlugin(m_context.get(), allOrigins.get(), pdfName.get(), emptyArray.get(), emptyArray.get());
1748
1749     WKRetainPtr<WKStringRef> nameNetscape = adoptWK(WKStringCreateWithUTF8CString("com.apple.testnetscapeplugin"));
1750     WKRetainPtr<WKStringRef> mimeTypeNetscape = adoptWK(WKStringCreateWithUTF8CString("application/x-webkit-test-netscape"));
1751     WKRetainPtr<WKMutableArrayRef> mimeTypesNetscape = adoptWK(WKMutableArrayCreate());
1752     WKArrayAppendItem(mimeTypesNetscape.get(), mimeTypeNetscape.get());
1753
1754     WKRetainPtr<WKStringRef> namePdf = adoptWK(WKStringCreateWithUTF8CString("WebKit built-in PDF"));
1755
1756     if (m_unsupportedPluginMode == "allOrigins") {
1757         WKContextAddSupportedPlugin(m_context.get(), allOrigins.get(), nameNetscape.get(), mimeTypesNetscape.get(), emptyArray.get());
1758         WKContextAddSupportedPlugin(m_context.get(), allOrigins.get(), namePdf.get(), emptyArray.get(), emptyArray.get());
1759         return;
1760     }
1761
1762     if (m_unsupportedPluginMode == "specificOrigin") {
1763         WKContextAddSupportedPlugin(m_context.get(), specificOrigin.get(), nameNetscape.get(), mimeTypesNetscape.get(), emptyArray.get());
1764         WKContextAddSupportedPlugin(m_context.get(), specificOrigin.get(), namePdf.get(), emptyArray.get(), emptyArray.get());
1765         return;
1766     }
1767 }
1768
1769 void TestController::didCommitNavigation(WKPageRef page, WKNavigationRef navigation)
1770 {
1771     mainWebView()->focus();
1772 }
1773
1774 void TestController::didReceiveServerRedirectForProvisionalNavigation(WKPageRef page, WKNavigationRef navigation, WKTypeRef userData)
1775 {
1776     m_didReceiveServerRedirectForProvisionalNavigation = true;
1777     return;
1778 }
1779
1780 bool TestController::canAuthenticateAgainstProtectionSpace(WKPageRef page, WKProtectionSpaceRef protectionSpace)
1781 {
1782     if (m_shouldLogCanAuthenticateAgainstProtectionSpace)
1783         m_currentInvocation->outputText("canAuthenticateAgainstProtectionSpace\n");
1784     WKProtectionSpaceAuthenticationScheme authenticationScheme = WKProtectionSpaceGetAuthenticationScheme(protectionSpace);
1785     
1786     if (authenticationScheme == kWKProtectionSpaceAuthenticationSchemeServerTrustEvaluationRequested) {
1787         std::string host = toSTD(adoptWK(WKProtectionSpaceCopyHost(protectionSpace)).get());
1788         return host == "localhost" || host == "127.0.0.1" || (m_allowAnyHTTPSCertificateForAllowedHosts && m_allowedHosts.find(host) != m_allowedHosts.end());
1789     }
1790     
1791     return authenticationScheme <= kWKProtectionSpaceAuthenticationSchemeHTTPDigest;
1792 }
1793
1794 void TestController::didFinishNavigation(WKPageRef page, WKNavigationRef navigation)
1795 {
1796     if (m_state != Resetting)
1797         return;
1798
1799     WKRetainPtr<WKURLRef> wkURL(AdoptWK, WKFrameCopyURL(WKPageGetMainFrame(page)));
1800     if (!WKURLIsEqual(wkURL.get(), blankURL()))
1801         return;
1802
1803     m_doneResetting = true;
1804     singleton().notifyDone();
1805 }
1806
1807 void TestController::didReceiveAuthenticationChallenge(WKPageRef page, WKAuthenticationChallengeRef authenticationChallenge)
1808 {
1809     WKProtectionSpaceRef protectionSpace = WKAuthenticationChallengeGetProtectionSpace(authenticationChallenge);
1810     WKAuthenticationDecisionListenerRef decisionListener = WKAuthenticationChallengeGetDecisionListener(authenticationChallenge);
1811
1812     if (WKProtectionSpaceGetAuthenticationScheme(protectionSpace) == kWKProtectionSpaceAuthenticationSchemeServerTrustEvaluationRequested) {
1813         // Any non-empty credential signals to accept the server trust. Since the cross-platform API
1814         // doesn't expose a way to create a credential from server trust, we use a password credential.
1815
1816         WKRetainPtr<WKCredentialRef> credential = adoptWK(WKCredentialCreate(toWK("accept server trust").get(), toWK("").get(), kWKCredentialPersistenceNone));
1817         WKAuthenticationDecisionListenerUseCredential(decisionListener, credential.get());
1818         return;
1819     }
1820
1821     if (m_rejectsProtectionSpaceAndContinueForAuthenticationChallenges) {
1822         m_currentInvocation->outputText("Simulating reject protection space and continue for authentication challenge\n");
1823         WKAuthenticationDecisionListenerRejectProtectionSpaceAndContinue(decisionListener);
1824         return;
1825     }
1826
1827     std::string host = toSTD(adoptWK(WKProtectionSpaceCopyHost(protectionSpace)).get());
1828     int port = WKProtectionSpaceGetPort(protectionSpace);
1829     String message = String::format("%s:%d - didReceiveAuthenticationChallenge - ", host.c_str(), port);
1830     if (!m_handlesAuthenticationChallenges)
1831         message.append("Simulating cancelled authentication sheet\n");
1832     else
1833         message.append(String::format("Responding with %s:%s\n", m_authenticationUsername.utf8().data(), m_authenticationPassword.utf8().data()));
1834     m_currentInvocation->outputText(message);
1835
1836     if (!m_handlesAuthenticationChallenges) {
1837         WKAuthenticationDecisionListenerUseCredential(decisionListener, 0);
1838         return;
1839     }
1840     WKRetainPtr<WKStringRef> username(AdoptWK, WKStringCreateWithUTF8CString(m_authenticationUsername.utf8().data()));
1841     WKRetainPtr<WKStringRef> password(AdoptWK, WKStringCreateWithUTF8CString(m_authenticationPassword.utf8().data()));
1842     WKRetainPtr<WKCredentialRef> credential(AdoptWK, WKCredentialCreate(username.get(), password.get(), kWKCredentialPersistenceForSession));
1843     WKAuthenticationDecisionListenerUseCredential(decisionListener, credential.get());
1844 }
1845
1846     
1847 // WKContextDownloadClient
1848
1849 void TestController::downloadDidStart(WKContextRef context, WKDownloadRef download, const void* clientInfo)
1850 {
1851     static_cast<TestController*>(const_cast<void*>(clientInfo))->downloadDidStart(context, download);
1852 }
1853     
1854 WKStringRef TestController::decideDestinationWithSuggestedFilename(WKContextRef context, WKDownloadRef download, WKStringRef filename, bool* allowOverwrite, const void* clientInfo)
1855 {
1856     return static_cast<TestController*>(const_cast<void*>(clientInfo))->decideDestinationWithSuggestedFilename(context, download, filename, allowOverwrite);
1857 }
1858
1859 void TestController::downloadDidFinish(WKContextRef context, WKDownloadRef download, const void* clientInfo)
1860 {
1861     static_cast<TestController*>(const_cast<void*>(clientInfo))->downloadDidFinish(context, download);
1862 }
1863
1864 void TestController::downloadDidFail(WKContextRef context, WKDownloadRef download, WKErrorRef error, const void* clientInfo)
1865 {
1866     static_cast<TestController*>(const_cast<void*>(clientInfo))->downloadDidFail(context, download, error);
1867 }
1868
1869 void TestController::downloadDidCancel(WKContextRef context, WKDownloadRef download, const void* clientInfo)
1870 {
1871     static_cast<TestController*>(const_cast<void*>(clientInfo))->downloadDidCancel(context, download);
1872 }
1873
1874 void TestController::downloadDidReceiveServerRedirectToURL(WKContextRef context, WKDownloadRef download, WKURLRef url, const void* clientInfo)
1875 {
1876     static_cast<TestController*>(const_cast<void*>(clientInfo))->downloadDidReceiveServerRedirectToURL(context, download, url);
1877 }
1878
1879 void TestController::downloadDidStart(WKContextRef context, WKDownloadRef download)
1880 {
1881     if (m_shouldLogDownloadCallbacks)
1882         m_currentInvocation->outputText("Download started.\n");
1883 }
1884
1885 WKStringRef TestController::decideDestinationWithSuggestedFilename(WKContextRef, WKDownloadRef, WKStringRef filename, bool*& allowOverwrite)
1886 {
1887     String suggestedFilename = toWTFString(filename);
1888
1889     if (m_shouldLogDownloadCallbacks) {
1890         StringBuilder builder;
1891         builder.append("Downloading URL with suggested filename \"");
1892         builder.append(suggestedFilename);
1893         builder.append("\"\n");
1894         m_currentInvocation->outputText(builder.toString());
1895     }
1896
1897     const char* dumpRenderTreeTemp = libraryPathForTesting();
1898     if (!dumpRenderTreeTemp)
1899         return nullptr;
1900
1901     *allowOverwrite = true;
1902     String temporaryFolder = String::fromUTF8(dumpRenderTreeTemp);
1903     if (suggestedFilename.isEmpty())
1904         suggestedFilename = "Unknown";
1905
1906     return toWK(temporaryFolder + "/" + suggestedFilename).leakRef();
1907 }
1908
1909 void TestController::downloadDidFinish(WKContextRef, WKDownloadRef)
1910 {
1911     if (m_shouldLogDownloadCallbacks)
1912         m_currentInvocation->outputText("Download completed.\n");
1913     m_currentInvocation->notifyDownloadDone();
1914 }
1915
1916 void TestController::downloadDidReceiveServerRedirectToURL(WKContextRef, WKDownloadRef, WKURLRef url)
1917 {
1918     if (m_shouldLogDownloadCallbacks) {
1919         StringBuilder builder;
1920         builder.appendLiteral("Download was redirected to \"");
1921         WKRetainPtr<WKStringRef> urlStringWK = adoptWK(WKURLCopyString(url));
1922         builder.append(toSTD(urlStringWK).c_str());
1923         builder.appendLiteral("\".\n");
1924         m_currentInvocation->outputText(builder.toString());
1925     }
1926 }
1927
1928 void TestController::downloadDidFail(WKContextRef, WKDownloadRef, WKErrorRef error)
1929 {
1930     if (m_shouldLogDownloadCallbacks) {
1931         String message = String::format("Download failed.\n");
1932         m_currentInvocation->outputText(message);
1933
1934         WKRetainPtr<WKStringRef> errorDomain = adoptWK(WKErrorCopyDomain(error));
1935         WKRetainPtr<WKStringRef> errorDescription = adoptWK(WKErrorCopyLocalizedDescription(error));
1936         int errorCode = WKErrorGetErrorCode(error);
1937
1938         StringBuilder errorBuilder;
1939         errorBuilder.append("Failed: ");
1940         errorBuilder.append(toWTFString(errorDomain));
1941         errorBuilder.append(", code=");
1942         errorBuilder.appendNumber(errorCode);
1943         errorBuilder.append(", description=");
1944         errorBuilder.append(toWTFString(errorDescription));
1945         errorBuilder.append("\n");
1946
1947         m_currentInvocation->outputText(errorBuilder.toString());
1948     }
1949     m_currentInvocation->notifyDownloadDone();
1950 }
1951
1952 void TestController::downloadDidCancel(WKContextRef, WKDownloadRef)
1953 {
1954     if (m_shouldLogDownloadCallbacks)
1955         m_currentInvocation->outputText("Download cancelled.\n");
1956     m_currentInvocation->notifyDownloadDone();
1957 }
1958
1959 void TestController::processDidCrash()
1960 {
1961     // This function can be called multiple times when crash logs are being saved on Windows, so
1962     // ensure we only print the crashed message once.
1963     if (!m_didPrintWebProcessCrashedMessage) {
1964         pid_t pid = WKPageGetProcessIdentifier(m_mainWebView->page());
1965         fprintf(stderr, "#CRASHED - %s (pid %ld)\n", webProcessName(), static_cast<long>(pid));
1966         fflush(stderr);
1967         m_didPrintWebProcessCrashedMessage = true;
1968     }
1969
1970     if (m_shouldExitWhenWebProcessCrashes)
1971         exit(1);
1972 }
1973
1974 void TestController::didBeginNavigationGesture(WKPageRef)
1975 {
1976     m_currentInvocation->didBeginSwipe();
1977 }
1978
1979 void TestController::willEndNavigationGesture(WKPageRef, WKBackForwardListItemRef)
1980 {
1981     m_currentInvocation->willEndSwipe();
1982 }
1983
1984 void TestController::didEndNavigationGesture(WKPageRef, WKBackForwardListItemRef)
1985 {
1986     m_currentInvocation->didEndSwipe();
1987 }
1988
1989 void TestController::didRemoveNavigationGestureSnapshot(WKPageRef)
1990 {
1991     m_currentInvocation->didRemoveSwipeSnapshot();
1992 }
1993
1994 void TestController::simulateWebNotificationClick(uint64_t notificationID)
1995 {
1996     m_webNotificationProvider.simulateWebNotificationClick(mainWebView()->page(), notificationID);
1997 }
1998
1999 void TestController::setGeolocationPermission(bool enabled)
2000 {
2001     m_isGeolocationPermissionSet = true;
2002     m_isGeolocationPermissionAllowed = enabled;
2003     decidePolicyForGeolocationPermissionRequestIfPossible();
2004 }
2005
2006 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)
2007 {
2008     m_geolocationProvider->setPosition(latitude, longitude, accuracy, providesAltitude, altitude, providesAltitudeAccuracy, altitudeAccuracy, providesHeading, heading, providesSpeed, speed, providesFloorLevel, floorLevel);
2009 }
2010
2011 void TestController::setMockGeolocationPositionUnavailableError(WKStringRef errorMessage)
2012 {
2013     m_geolocationProvider->setPositionUnavailableError(errorMessage);
2014 }
2015
2016 void TestController::handleGeolocationPermissionRequest(WKGeolocationPermissionRequestRef geolocationPermissionRequest)
2017 {
2018     m_geolocationPermissionRequests.append(geolocationPermissionRequest);
2019     decidePolicyForGeolocationPermissionRequestIfPossible();
2020 }
2021
2022 bool TestController::isGeolocationProviderActive() const
2023 {
2024     return m_geolocationProvider->isActive();
2025 }
2026
2027 static String originUserVisibleName(WKSecurityOriginRef origin)
2028 {
2029     if (!origin)
2030         return emptyString();
2031
2032     std::string host = toSTD(adoptWK(WKSecurityOriginCopyHost(origin))).c_str();
2033     std::string protocol = toSTD(adoptWK(WKSecurityOriginCopyProtocol(origin))).c_str();
2034
2035     if (!host.length() || !protocol.length())
2036         return emptyString();
2037
2038     unsigned short port = WKSecurityOriginGetPort(origin);
2039     if (port)
2040         return String::format("%s://%s:%d", protocol.c_str(), host.c_str(), port);
2041
2042     return String::format("%s://%s", protocol.c_str(), host.c_str());
2043 }
2044
2045 static String userMediaOriginHash(WKSecurityOriginRef userMediaDocumentOrigin, WKSecurityOriginRef topLevelDocumentOrigin)
2046 {
2047     String userMediaDocumentOriginString = originUserVisibleName(userMediaDocumentOrigin);
2048     String topLevelDocumentOriginString = originUserVisibleName(topLevelDocumentOrigin);
2049
2050     if (topLevelDocumentOriginString.isEmpty())
2051         return userMediaDocumentOriginString;
2052
2053     return String::format("%s-%s", userMediaDocumentOriginString.utf8().data(), topLevelDocumentOriginString.utf8().data());
2054 }
2055
2056 static String userMediaOriginHash(WKStringRef userMediaDocumentOriginString, WKStringRef topLevelDocumentOriginString)
2057 {
2058     auto userMediaDocumentOrigin = adoptWK(WKSecurityOriginCreateFromString(userMediaDocumentOriginString));
2059     if (!WKStringGetLength(topLevelDocumentOriginString))
2060         return userMediaOriginHash(userMediaDocumentOrigin.get(), nullptr);
2061
2062     auto topLevelDocumentOrigin = adoptWK(WKSecurityOriginCreateFromString(topLevelDocumentOriginString));
2063     return userMediaOriginHash(userMediaDocumentOrigin.get(), topLevelDocumentOrigin.get());
2064 }
2065
2066 void TestController::setUserMediaPermission(bool enabled)
2067 {
2068     m_isUserMediaPermissionSet = true;
2069     m_isUserMediaPermissionAllowed = enabled;
2070     decidePolicyForUserMediaPermissionRequestIfPossible();
2071 }
2072
2073 void TestController::resetUserMediaPermission()
2074 {
2075     m_isUserMediaPermissionSet = false;
2076 }
2077
2078 class OriginSettings : public RefCounted<OriginSettings> {
2079 public:
2080     explicit OriginSettings()
2081     {
2082     }
2083
2084     bool persistentPermission() const { return m_persistentPermission; }
2085     void setPersistentPermission(bool permission) { m_persistentPermission = permission; }
2086
2087     String persistentSalt() const { return m_persistentSalt; }
2088     void setPersistentSalt(const String& salt) { m_persistentSalt = salt; }
2089
2090     HashMap<uint64_t, String>& ephemeralSalts() { return m_ephemeralSalts; }
2091
2092     void incrementRequestCount() { ++m_requestCount; }
2093     void resetRequestCount() { m_requestCount = 0; }
2094     unsigned requestCount() const { return m_requestCount; }
2095
2096 private:
2097     HashMap<uint64_t, String> m_ephemeralSalts;
2098     String m_persistentSalt;
2099     unsigned m_requestCount { 0 };
2100     bool m_persistentPermission { false };
2101 };
2102
2103 String TestController::saltForOrigin(WKFrameRef frame, String originHash)
2104 {
2105     auto& settings = settingsForOrigin(originHash);
2106     auto& ephemeralSalts = settings.ephemeralSalts();
2107     auto frameInfo = adoptWK(WKFrameCreateFrameInfo(frame));
2108     auto frameHandle = WKFrameInfoGetFrameHandleRef(frameInfo.get());
2109     uint64_t frameIdentifier = WKFrameHandleGetFrameID(frameHandle);
2110     String frameSalt = ephemeralSalts.get(frameIdentifier);
2111
2112     if (settings.persistentPermission()) {
2113         if (frameSalt.length())
2114             return frameSalt;
2115
2116         if (!settings.persistentSalt().length())
2117             settings.setPersistentSalt(createCanonicalUUIDString());
2118
2119         return settings.persistentSalt();
2120     }
2121
2122     if (!frameSalt.length()) {
2123         frameSalt = createCanonicalUUIDString();
2124         ephemeralSalts.add(frameIdentifier, frameSalt);
2125     }
2126
2127     return frameSalt;
2128 }
2129
2130 void TestController::setUserMediaPersistentPermissionForOrigin(bool permission, WKStringRef userMediaDocumentOriginString, WKStringRef topLevelDocumentOriginString)
2131 {
2132     auto originHash = userMediaOriginHash(userMediaDocumentOriginString, topLevelDocumentOriginString);
2133     auto& settings = settingsForOrigin(originHash);
2134     settings.setPersistentPermission(permission);
2135 }
2136
2137 void TestController::handleCheckOfUserMediaPermissionForOrigin(WKFrameRef frame, WKSecurityOriginRef userMediaDocumentOrigin, WKSecurityOriginRef topLevelDocumentOrigin, const WKUserMediaPermissionCheckRef& checkRequest)
2138 {
2139     auto originHash = userMediaOriginHash(userMediaDocumentOrigin, topLevelDocumentOrigin);
2140     auto salt = saltForOrigin(frame, originHash);
2141     WKRetainPtr<WKStringRef> saltString = adoptWK(WKStringCreateWithUTF8CString(salt.utf8().data()));
2142
2143     WKUserMediaPermissionCheckSetUserMediaAccessInfo(checkRequest, saltString.get(), settingsForOrigin(originHash).persistentPermission());
2144 }
2145
2146 void TestController::handleUserMediaPermissionRequest(WKFrameRef frame, WKSecurityOriginRef userMediaDocumentOrigin, WKSecurityOriginRef topLevelDocumentOrigin, WKUserMediaPermissionRequestRef request)
2147 {
2148     auto originHash = userMediaOriginHash(userMediaDocumentOrigin, topLevelDocumentOrigin);
2149     m_userMediaPermissionRequests.append(std::make_pair(originHash, request));
2150     decidePolicyForUserMediaPermissionRequestIfPossible();
2151 }
2152
2153 OriginSettings& TestController::settingsForOrigin(const String& originHash)
2154 {
2155     RefPtr<OriginSettings> settings = m_cachedUserMediaPermissions.get(originHash);
2156     if (!settings) {
2157         settings = adoptRef(*new OriginSettings());
2158         m_cachedUserMediaPermissions.add(originHash, settings);
2159     }
2160
2161     return *settings;
2162 }
2163
2164 unsigned TestController::userMediaPermissionRequestCountForOrigin(WKStringRef userMediaDocumentOriginString, WKStringRef topLevelDocumentOriginString)
2165 {
2166     auto originHash = userMediaOriginHash(userMediaDocumentOriginString, topLevelDocumentOriginString);
2167     return settingsForOrigin(originHash).requestCount();
2168 }
2169
2170 void TestController::resetUserMediaPermissionRequestCountForOrigin(WKStringRef userMediaDocumentOriginString, WKStringRef topLevelDocumentOriginString)
2171 {
2172     auto originHash = userMediaOriginHash(userMediaDocumentOriginString, topLevelDocumentOriginString);
2173     settingsForOrigin(originHash).resetRequestCount();
2174 }
2175
2176 void TestController::decidePolicyForUserMediaPermissionRequestIfPossible()
2177 {
2178     if (!m_isUserMediaPermissionSet)
2179         return;
2180
2181     for (auto& pair : m_userMediaPermissionRequests) {
2182         auto originHash = pair.first;
2183         auto request = pair.second.get();
2184
2185         auto& settings = settingsForOrigin(originHash);
2186         settings.incrementRequestCount();
2187
2188         if (!m_isUserMediaPermissionAllowed && !settings.persistentPermission()) {
2189             WKUserMediaPermissionRequestDeny(request, kWKPermissionDenied);
2190             continue;
2191         }
2192
2193         WKRetainPtr<WKArrayRef> audioDeviceUIDs = adoptWK(WKUserMediaPermissionRequestAudioDeviceUIDs(request));
2194         WKRetainPtr<WKArrayRef> videoDeviceUIDs = adoptWK(WKUserMediaPermissionRequestVideoDeviceUIDs(request));
2195
2196         if (!WKArrayGetSize(videoDeviceUIDs.get()) && !WKArrayGetSize(audioDeviceUIDs.get())) {
2197             WKUserMediaPermissionRequestDeny(request, kWKNoConstraints);
2198             continue;
2199         }
2200
2201         WKRetainPtr<WKStringRef> videoDeviceUID;
2202         if (WKArrayGetSize(videoDeviceUIDs.get()))
2203             videoDeviceUID = reinterpret_cast<WKStringRef>(WKArrayGetItemAtIndex(videoDeviceUIDs.get(), 0));
2204         else
2205             videoDeviceUID = adoptWK(WKStringCreateWithUTF8CString(""));
2206
2207         WKRetainPtr<WKStringRef> audioDeviceUID;
2208         if (WKArrayGetSize(audioDeviceUIDs.get()))
2209             audioDeviceUID = reinterpret_cast<WKStringRef>(WKArrayGetItemAtIndex(audioDeviceUIDs.get(), 0));
2210         else
2211             audioDeviceUID = adoptWK(WKStringCreateWithUTF8CString(""));
2212
2213         WKUserMediaPermissionRequestAllow(request, audioDeviceUID.get(), videoDeviceUID.get());
2214     }
2215     m_userMediaPermissionRequests.clear();
2216 }
2217
2218 void TestController::setCustomPolicyDelegate(bool enabled, bool permissive)
2219 {
2220     m_policyDelegateEnabled = enabled;
2221     m_policyDelegatePermissive = permissive;
2222 }
2223
2224 void TestController::decidePolicyForGeolocationPermissionRequestIfPossible()
2225 {
2226     if (!m_isGeolocationPermissionSet)
2227         return;
2228
2229     for (size_t i = 0; i < m_geolocationPermissionRequests.size(); ++i) {
2230         WKGeolocationPermissionRequestRef permissionRequest = m_geolocationPermissionRequests[i].get();
2231         if (m_isGeolocationPermissionAllowed)
2232             WKGeolocationPermissionRequestAllow(permissionRequest);
2233         else
2234             WKGeolocationPermissionRequestDeny(permissionRequest);
2235     }
2236     m_geolocationPermissionRequests.clear();
2237 }
2238
2239 void TestController::decidePolicyForNotificationPermissionRequest(WKPageRef page, WKSecurityOriginRef origin, WKNotificationPermissionRequestRef request, const void*)
2240 {
2241     TestController::singleton().decidePolicyForNotificationPermissionRequest(page, origin, request);
2242 }
2243
2244 void TestController::decidePolicyForNotificationPermissionRequest(WKPageRef, WKSecurityOriginRef, WKNotificationPermissionRequestRef request)
2245 {
2246     WKNotificationPermissionRequestAllow(request);
2247 }
2248
2249 void TestController::unavailablePluginButtonClicked(WKPageRef, WKPluginUnavailabilityReason, WKDictionaryRef, const void*)
2250 {
2251     printf("MISSING PLUGIN BUTTON PRESSED\n");
2252 }
2253
2254 void TestController::decidePolicyForNavigationAction(WKPageRef, WKNavigationActionRef navigationAction, WKFramePolicyListenerRef listener, WKTypeRef, const void* clientInfo)
2255 {
2256     static_cast<TestController*>(const_cast<void*>(clientInfo))->decidePolicyForNavigationAction(listener);
2257 }
2258
2259 void TestController::decidePolicyForNavigationAction(WKFramePolicyListenerRef listener)
2260 {
2261     WKRetainPtr<WKFramePolicyListenerRef> retainedListener { listener };
2262     const bool shouldIgnore { m_policyDelegateEnabled && !m_policyDelegatePermissive };
2263     auto decisionFunction = [shouldIgnore, retainedListener]() {
2264         if (shouldIgnore)
2265             WKFramePolicyListenerIgnore(retainedListener.get());
2266         else
2267             WKFramePolicyListenerUse(retainedListener.get());
2268     };
2269
2270     if (m_shouldDecideNavigationPolicyAfterDelay)
2271         RunLoop::main().dispatch(WTFMove(decisionFunction));
2272     else
2273         decisionFunction();
2274 }
2275
2276 void TestController::decidePolicyForNavigationResponse(WKPageRef, WKNavigationResponseRef navigationResponse, WKFramePolicyListenerRef listener, WKTypeRef, const void* clientInfo)
2277 {
2278     static_cast<TestController*>(const_cast<void*>(clientInfo))->decidePolicyForNavigationResponse(navigationResponse, listener);
2279 }
2280
2281 void TestController::decidePolicyForNavigationResponse(WKNavigationResponseRef navigationResponse, WKFramePolicyListenerRef listener)
2282 {
2283     WKRetainPtr<WKNavigationResponseRef> retainedNavigationResponse { navigationResponse };
2284     WKRetainPtr<WKFramePolicyListenerRef> retainedListener { listener };
2285
2286     bool shouldDownloadUndisplayableMIMETypes = m_shouldDownloadUndisplayableMIMETypes;
2287     auto decisionFunction = [shouldDownloadUndisplayableMIMETypes, retainedNavigationResponse, retainedListener]() {
2288         // Even though Response was already checked by WKBundlePagePolicyClient, the check did not include plugins
2289         // so we have to re-check again.
2290         if (WKNavigationResponseCanShowMIMEType(retainedNavigationResponse.get())) {
2291             WKFramePolicyListenerUse(retainedListener.get());
2292             return;
2293         }
2294
2295         if (shouldDownloadUndisplayableMIMETypes)
2296             WKFramePolicyListenerDownload(retainedListener.get());
2297         else
2298             WKFramePolicyListenerIgnore(retainedListener.get());
2299     };
2300
2301     if (m_shouldDecideResponsePolicyAfterDelay)
2302         RunLoop::main().dispatch(WTFMove(decisionFunction));
2303     else
2304         decisionFunction();
2305 }
2306
2307 void TestController::didNavigateWithNavigationData(WKContextRef, WKPageRef, WKNavigationDataRef navigationData, WKFrameRef frame, const void* clientInfo)
2308 {
2309     static_cast<TestController*>(const_cast<void*>(clientInfo))->didNavigateWithNavigationData(navigationData, frame);
2310 }
2311
2312 void TestController::didNavigateWithNavigationData(WKNavigationDataRef navigationData, WKFrameRef)
2313 {
2314     if (m_state != RunningTest)
2315         return;
2316
2317     if (!m_shouldLogHistoryClientCallbacks)
2318         return;
2319
2320     // URL
2321     WKRetainPtr<WKURLRef> urlWK = adoptWK(WKNavigationDataCopyURL(navigationData));
2322     WKRetainPtr<WKStringRef> urlStringWK = adoptWK(WKURLCopyString(urlWK.get()));
2323     // Title
2324     WKRetainPtr<WKStringRef> titleWK = adoptWK(WKNavigationDataCopyTitle(navigationData));
2325     // HTTP method
2326     WKRetainPtr<WKURLRequestRef> requestWK = adoptWK(WKNavigationDataCopyOriginalRequest(navigationData));
2327     WKRetainPtr<WKStringRef> methodWK = adoptWK(WKURLRequestCopyHTTPMethod(requestWK.get()));
2328
2329     // FIXME: Determine whether the navigation was successful / a client redirect rather than hard-coding the message here.
2330     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",
2331         toSTD(urlStringWK).c_str(), toSTD(titleWK).c_str(), toSTD(methodWK).c_str()));
2332 }
2333
2334 void TestController::didPerformClientRedirect(WKContextRef, WKPageRef, WKURLRef sourceURL, WKURLRef destinationURL, WKFrameRef frame, const void* clientInfo)
2335 {
2336     static_cast<TestController*>(const_cast<void*>(clientInfo))->didPerformClientRedirect(sourceURL, destinationURL, frame);
2337 }
2338
2339 void TestController::didPerformClientRedirect(WKURLRef sourceURL, WKURLRef destinationURL, WKFrameRef)
2340 {
2341     if (m_state != RunningTest)
2342         return;
2343
2344     if (!m_shouldLogHistoryClientCallbacks)
2345         return;
2346
2347     WKRetainPtr<WKStringRef> sourceStringWK = adoptWK(WKURLCopyString(sourceURL));
2348     WKRetainPtr<WKStringRef> destinationStringWK = adoptWK(WKURLCopyString(destinationURL));
2349
2350     m_currentInvocation->outputText(String::format("WebView performed a client redirect from \"%s\" to \"%s\".\n", toSTD(sourceStringWK).c_str(), toSTD(destinationStringWK).c_str()));
2351 }
2352
2353 void TestController::didPerformServerRedirect(WKContextRef, WKPageRef, WKURLRef sourceURL, WKURLRef destinationURL, WKFrameRef frame, const void* clientInfo)
2354 {
2355     static_cast<TestController*>(const_cast<void*>(clientInfo))->didPerformServerRedirect(sourceURL, destinationURL, frame);
2356 }
2357
2358 void TestController::didPerformServerRedirect(WKURLRef sourceURL, WKURLRef destinationURL, WKFrameRef)
2359 {
2360     if (m_state != RunningTest)
2361         return;
2362
2363     if (!m_shouldLogHistoryClientCallbacks)
2364         return;
2365
2366     WKRetainPtr<WKStringRef> sourceStringWK = adoptWK(WKURLCopyString(sourceURL));
2367     WKRetainPtr<WKStringRef> destinationStringWK = adoptWK(WKURLCopyString(destinationURL));
2368
2369     m_currentInvocation->outputText(String::format("WebView performed a server redirect from \"%s\" to \"%s\".\n", toSTD(sourceStringWK).c_str(), toSTD(destinationStringWK).c_str()));
2370 }
2371
2372 void TestController::didUpdateHistoryTitle(WKContextRef, WKPageRef, WKStringRef title, WKURLRef URL, WKFrameRef frame, const void* clientInfo)
2373 {
2374     static_cast<TestController*>(const_cast<void*>(clientInfo))->didUpdateHistoryTitle(title, URL, frame);
2375 }
2376
2377 void TestController::didUpdateHistoryTitle(WKStringRef title, WKURLRef URL, WKFrameRef)
2378 {
2379     if (m_state != RunningTest)
2380         return;
2381
2382     if (!m_shouldLogHistoryClientCallbacks)
2383         return;
2384
2385     WKRetainPtr<WKStringRef> urlStringWK(AdoptWK, WKURLCopyString(URL));
2386     m_currentInvocation->outputText(String::format("WebView updated the title for history URL \"%s\" to \"%s\".\n", toSTD(urlStringWK).c_str(), toSTD(title).c_str()));
2387 }
2388
2389 void TestController::setNavigationGesturesEnabled(bool value)
2390 {
2391     m_mainWebView->setNavigationGesturesEnabled(value);
2392 }
2393
2394 void TestController::setIgnoresViewportScaleLimits(bool ignoresViewportScaleLimits)
2395 {
2396     WKPageSetIgnoresViewportScaleLimits(m_mainWebView->page(), ignoresViewportScaleLimits);
2397 }
2398
2399 void TestController::terminateNetworkProcess()
2400 {
2401     WKContextTerminateNetworkProcess(platformContext());
2402 }
2403
2404 void TestController::terminateServiceWorkerProcess()
2405 {
2406     WKContextTerminateServiceWorkerProcess(platformContext());
2407 }
2408
2409 void TestController::terminateStorageProcess()
2410 {
2411     WKContextTerminateStorageProcess(platformContext());
2412 }
2413
2414 #if !PLATFORM(COCOA)
2415 void TestController::platformWillRunTest(const TestInvocation&)
2416 {
2417 }
2418
2419 void TestController::platformCreateWebView(WKPageConfigurationRef configuration, const TestOptions& options)
2420 {
2421     m_mainWebView = std::make_unique<PlatformWebView>(configuration, options);
2422 }
2423
2424 PlatformWebView* TestController::platformCreateOtherPage(PlatformWebView* parentView, WKPageConfigurationRef configuration, const TestOptions& options)
2425 {
2426     return new PlatformWebView(configuration, options);
2427 }
2428
2429 WKContextRef TestController::platformAdjustContext(WKContextRef context, WKContextConfigurationRef contextConfiguration)
2430 {
2431     auto* dataStore = WKContextGetWebsiteDataStore(context);
2432     WKWebsiteDataStoreSetResourceLoadStatisticsEnabled(dataStore, true);
2433
2434     if (const char* dumpRenderTreeTemp = libraryPathForTesting()) {
2435         String temporaryFolder = String::fromUTF8(dumpRenderTreeTemp);
2436         const char separator = '/';
2437
2438         WKWebsiteDataStoreSetServiceWorkerRegistrationDirectory(dataStore, toWK(temporaryFolder + separator + "ServiceWorkers").get());
2439     }
2440
2441     return context;
2442 }
2443
2444 void TestController::platformResetStateToConsistentValues()
2445 {
2446 }
2447
2448 unsigned TestController::imageCountInGeneralPasteboard() const
2449 {
2450     return 0;
2451 }
2452
2453 void TestController::removeAllSessionCredentials()
2454 {
2455 }
2456
2457 void TestController::getAllStorageAccessEntries()
2458 {
2459 }
2460
2461 #endif
2462
2463 struct ClearServiceWorkerRegistrationsCallbackContext {
2464     explicit ClearServiceWorkerRegistrationsCallbackContext(TestController& controller)
2465         : testController(controller)
2466     {
2467     }
2468
2469     TestController& testController;
2470     bool done { false };
2471 };
2472
2473 static void clearServiceWorkerRegistrationsCallback(void* userData)
2474 {
2475     auto* context = static_cast<ClearServiceWorkerRegistrationsCallbackContext*>(userData);
2476     context->done = true;
2477     context->testController.notifyDone();
2478 }
2479
2480 void TestController::clearServiceWorkerRegistrations()
2481 {
2482     auto websiteDataStore = WKContextGetWebsiteDataStore(platformContext());
2483     ClearServiceWorkerRegistrationsCallbackContext context(*this);
2484
2485     WKWebsiteDataStoreRemoveAllServiceWorkerRegistrations(websiteDataStore, &context, clearServiceWorkerRegistrationsCallback);
2486     runUntil(context.done, noTimeout);
2487 }
2488
2489 struct ClearDOMCacheCallbackContext {
2490     explicit ClearDOMCacheCallbackContext(TestController& controller)
2491         : testController(controller)
2492     {
2493     }
2494
2495     TestController& testController;
2496     bool done { false };
2497 };
2498
2499 static void clearDOMCacheCallback(void* userData)
2500 {
2501     auto* context = static_cast<ClearDOMCacheCallbackContext*>(userData);
2502     context->done = true;
2503     context->testController.notifyDone();
2504 }
2505
2506 void TestController::clearDOMCache(WKStringRef origin)
2507 {
2508     auto websiteDataStore = WKContextGetWebsiteDataStore(platformContext());
2509     ClearDOMCacheCallbackContext context(*this);
2510
2511     auto cacheOrigin = adoptWK(WKSecurityOriginCreateFromString(origin));
2512     WKWebsiteDataStoreRemoveFetchCacheForOrigin(websiteDataStore, cacheOrigin.get(), &context, clearDOMCacheCallback);
2513     runUntil(context.done, noTimeout);
2514 }
2515
2516 void TestController::clearDOMCaches()
2517 {
2518     auto websiteDataStore = WKContextGetWebsiteDataStore(platformContext());
2519     ClearDOMCacheCallbackContext context(*this);
2520
2521     WKWebsiteDataStoreRemoveAllFetchCaches(websiteDataStore, &context, clearDOMCacheCallback);
2522     runUntil(context.done, noTimeout);
2523 }
2524
2525 struct FetchCacheOriginsCallbackContext {
2526     FetchCacheOriginsCallbackContext(TestController& controller, WKStringRef origin)
2527         : testController(controller)
2528         , origin(origin)
2529     {
2530     }
2531
2532     TestController& testController;
2533     WKStringRef origin;
2534
2535     bool done { false };
2536     bool result { false };
2537 };
2538
2539 static void fetchCacheOriginsCallback(WKArrayRef origins, void* userData)
2540 {
2541     auto* context = static_cast<FetchCacheOriginsCallbackContext*>(userData);
2542     context->done = true;
2543
2544     auto size = WKArrayGetSize(origins);
2545     for (size_t index = 0; index < size && !context->result; ++index) {
2546         WKSecurityOriginRef securityOrigin = reinterpret_cast<WKSecurityOriginRef>(WKArrayGetItemAtIndex(origins, index));
2547         if (WKStringIsEqual(context->origin, adoptWK(WKSecurityOriginCopyToString(securityOrigin)).get()))
2548             context->result = true;
2549     }
2550     context->testController.notifyDone();
2551 }
2552
2553 bool TestController::hasDOMCache(WKStringRef origin)
2554 {
2555     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2556     FetchCacheOriginsCallbackContext context(*this, origin);
2557     WKWebsiteDataStoreGetFetchCacheOrigins(dataStore, &context, fetchCacheOriginsCallback);
2558     runUntil(context.done, noTimeout);
2559     return context.result;
2560 }
2561
2562 struct FetchCacheSizeForOriginCallbackContext {
2563     explicit FetchCacheSizeForOriginCallbackContext(TestController& controller)
2564         : testController(controller)
2565     {
2566     }
2567
2568     TestController& testController;
2569
2570     bool done { false };
2571     uint64_t result { 0 };
2572 };
2573
2574 static void fetchCacheSizeForOriginCallback(uint64_t size, void* userData)
2575 {
2576     auto* context = static_cast<FetchCacheSizeForOriginCallbackContext*>(userData);
2577     context->done = true;
2578     context->result = size;
2579     context->testController.notifyDone();
2580 }
2581
2582 uint64_t TestController::domCacheSize(WKStringRef origin)
2583 {
2584     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2585     FetchCacheSizeForOriginCallbackContext context(*this);
2586     WKWebsiteDataStoreGetFetchCacheSizeForOrigin(dataStore, origin, &context, fetchCacheSizeForOriginCallback);
2587     runUntil(context.done, noTimeout);
2588     return context.result;
2589 }
2590
2591 void TestController::setStatisticsLastSeen(WKStringRef host, double seconds)
2592 {
2593     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2594     WKWebsiteDataStoreSetStatisticsLastSeen(dataStore, host, seconds);
2595 }
2596
2597 void TestController::setStatisticsPrevalentResource(WKStringRef host, bool value)
2598 {
2599     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2600     WKWebsiteDataStoreSetStatisticsPrevalentResource(dataStore, host, value);
2601 }
2602
2603 void TestController::setStatisticsVeryPrevalentResource(WKStringRef host, bool value)
2604 {
2605     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2606     WKWebsiteDataStoreSetStatisticsVeryPrevalentResource(dataStore, host, value);
2607 }
2608
2609 struct ResourceStatisticsCallbackContext {
2610     explicit ResourceStatisticsCallbackContext(TestController& controller)
2611         : testController(controller)
2612     {
2613     }
2614
2615     TestController& testController;
2616     bool done { false };
2617     bool result { false };
2618 };
2619
2620 static void resourceStatisticsVoidResultCallback(void* userData)
2621 {
2622     auto* context = static_cast<ResourceStatisticsCallbackContext*>(userData);
2623     context->done = true;
2624     context->testController.notifyDone();
2625 }
2626
2627 static void resourceStatisticsBooleanResultCallback(bool result, void* userData)
2628 {
2629     auto* context = static_cast<ResourceStatisticsCallbackContext*>(userData);
2630     context->result = result;
2631     context->done = true;
2632     context->testController.notifyDone();
2633 }
2634
2635 bool TestController::isStatisticsPrevalentResource(WKStringRef host)
2636 {
2637     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2638     ResourceStatisticsCallbackContext context(*this);
2639     WKWebsiteDataStoreIsStatisticsPrevalentResource(dataStore, host, &context, resourceStatisticsBooleanResultCallback);
2640     runUntil(context.done, noTimeout);
2641     return context.result;
2642 }
2643
2644 bool TestController::isStatisticsVeryPrevalentResource(WKStringRef host)
2645 {
2646     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2647     ResourceStatisticsCallbackContext context(*this);
2648     WKWebsiteDataStoreIsStatisticsVeryPrevalentResource(dataStore, host, &context, resourceStatisticsBooleanResultCallback);
2649     runUntil(context.done, noTimeout);
2650     return context.result;
2651 }
2652
2653 bool TestController::isStatisticsRegisteredAsSubFrameUnder(WKStringRef subFrameHost, WKStringRef topFrameHost)
2654 {
2655     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2656     ResourceStatisticsCallbackContext context(*this);
2657     WKWebsiteDataStoreIsStatisticsRegisteredAsSubFrameUnder(dataStore, subFrameHost, topFrameHost, &context, resourceStatisticsBooleanResultCallback);
2658     runUntil(context.done, noTimeout);
2659     return context.result;
2660 }
2661
2662 bool TestController::isStatisticsRegisteredAsRedirectingTo(WKStringRef hostRedirectedFrom, WKStringRef hostRedirectedTo)
2663 {
2664     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2665     ResourceStatisticsCallbackContext context(*this);
2666     WKWebsiteDataStoreIsStatisticsRegisteredAsRedirectingTo(dataStore, hostRedirectedFrom, hostRedirectedTo, &context, resourceStatisticsBooleanResultCallback);
2667     runUntil(context.done, noTimeout);
2668     return context.result;
2669 }
2670
2671 void TestController::setStatisticsHasHadUserInteraction(WKStringRef host, bool value)
2672 {
2673     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2674     WKWebsiteDataStoreSetStatisticsHasHadUserInteraction(dataStore, host, value);
2675 }
2676
2677 void TestController::setStatisticsHasHadNonRecentUserInteraction(WKStringRef host)
2678 {
2679     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2680     WKWebsiteDataStoreSetStatisticsHasHadNonRecentUserInteraction(dataStore, host);
2681 }
2682
2683 bool TestController::isStatisticsHasHadUserInteraction(WKStringRef host)
2684 {
2685     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2686     ResourceStatisticsCallbackContext context(*this);
2687     WKWebsiteDataStoreIsStatisticsHasHadUserInteraction(dataStore, host, &context, resourceStatisticsBooleanResultCallback);
2688     runUntil(context.done, noTimeout);
2689     return context.result;
2690 }
2691
2692 void TestController::setStatisticsGrandfathered(WKStringRef host, bool value)
2693 {
2694     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2695     WKWebsiteDataStoreSetStatisticsGrandfathered(dataStore, host, value);
2696 }
2697
2698 bool TestController::isStatisticsGrandfathered(WKStringRef host)
2699 {
2700     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2701     ResourceStatisticsCallbackContext context(*this);
2702     WKWebsiteDataStoreIsStatisticsGrandfathered(dataStore, host, &context, resourceStatisticsBooleanResultCallback);
2703     runUntil(context.done, noTimeout);
2704     return context.result;
2705 }
2706
2707 void TestController::setStatisticsSubframeUnderTopFrameOrigin(WKStringRef host, WKStringRef topFrameHost)
2708 {
2709     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2710     WKWebsiteDataStoreSetStatisticsSubframeUnderTopFrameOrigin(dataStore, host, topFrameHost);
2711 }
2712
2713 void TestController::setStatisticsSubresourceUnderTopFrameOrigin(WKStringRef host, WKStringRef topFrameHost)
2714 {
2715     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2716     WKWebsiteDataStoreSetStatisticsSubresourceUnderTopFrameOrigin(dataStore, host, topFrameHost);
2717 }
2718
2719 void TestController::setStatisticsSubresourceUniqueRedirectTo(WKStringRef host, WKStringRef hostRedirectedTo)
2720 {
2721     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2722     WKWebsiteDataStoreSetStatisticsSubresourceUniqueRedirectTo(dataStore, host, hostRedirectedTo);
2723 }
2724
2725 void TestController::setStatisticsSubresourceUniqueRedirectFrom(WKStringRef host, WKStringRef hostRedirectedFrom)
2726 {
2727     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2728     WKWebsiteDataStoreSetStatisticsSubresourceUniqueRedirectFrom(dataStore, host, hostRedirectedFrom);
2729 }
2730
2731 void TestController::setStatisticsTopFrameUniqueRedirectTo(WKStringRef host, WKStringRef hostRedirectedTo)
2732 {
2733     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2734     WKWebsiteDataStoreSetStatisticsTopFrameUniqueRedirectTo(dataStore, host, hostRedirectedTo);
2735 }
2736
2737 void TestController::setStatisticsTopFrameUniqueRedirectFrom(WKStringRef host, WKStringRef hostRedirectedFrom)
2738 {
2739     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2740     WKWebsiteDataStoreSetStatisticsTopFrameUniqueRedirectFrom(dataStore, host, hostRedirectedFrom);
2741 }
2742
2743 void TestController::setStatisticsTimeToLiveUserInteraction(double seconds)
2744 {
2745     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2746     WKWebsiteDataStoreSetStatisticsTimeToLiveUserInteraction(dataStore, seconds);
2747 }
2748
2749 void TestController::setStatisticsTimeToLiveCookiePartitionFree(double seconds)
2750 {
2751     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2752     WKWebsiteDataStoreSetStatisticsTimeToLiveCookiePartitionFree(dataStore, seconds);
2753 }
2754
2755 void TestController::statisticsProcessStatisticsAndDataRecords()
2756 {
2757     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2758     WKWebsiteDataStoreStatisticsProcessStatisticsAndDataRecords(dataStore);
2759 }
2760
2761 void TestController::statisticsUpdateCookiePartitioning()
2762 {
2763     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2764     ResourceStatisticsCallbackContext context(*this);
2765     WKWebsiteDataStoreStatisticsUpdateCookiePartitioning(dataStore, &context, resourceStatisticsVoidResultCallback);
2766     runUntil(context.done, noTimeout);
2767     m_currentInvocation->didSetPartitionOrBlockCookiesForHost();
2768 }
2769
2770 void TestController::statisticsSetShouldPartitionCookiesForHost(WKStringRef host, bool value)
2771 {
2772     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2773     ResourceStatisticsCallbackContext context(*this);
2774     WKWebsiteDataStoreSetStatisticsShouldPartitionCookiesForHost(dataStore, host, value, &context, resourceStatisticsVoidResultCallback);
2775     runUntil(context.done, noTimeout);
2776     m_currentInvocation->didSetPartitionOrBlockCookiesForHost();
2777 }
2778
2779 void TestController::statisticsSubmitTelemetry()
2780 {
2781     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2782     WKWebsiteDataStoreStatisticsSubmitTelemetry(dataStore);
2783 }
2784
2785 void TestController::setStatisticsNotifyPagesWhenDataRecordsWereScanned(bool value)
2786 {
2787     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2788     WKWebsiteDataStoreSetStatisticsNotifyPagesWhenDataRecordsWereScanned(dataStore, value);
2789 }
2790
2791 void TestController::setStatisticsShouldClassifyResourcesBeforeDataRecordsRemoval(bool value)
2792 {
2793     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2794     WKWebsiteDataStoreSetStatisticsShouldClassifyResourcesBeforeDataRecordsRemoval(dataStore, value);
2795 }
2796
2797 void TestController::setStatisticsNotifyPagesWhenTelemetryWasCaptured(bool value)
2798 {
2799     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2800     WKWebsiteDataStoreSetStatisticsNotifyPagesWhenTelemetryWasCaptured(dataStore, value);
2801 }
2802
2803 void TestController::setStatisticsMinimumTimeBetweenDataRecordsRemoval(double seconds)
2804 {
2805     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2806     WKWebsiteDataStoreSetStatisticsMinimumTimeBetweenDataRecordsRemoval(dataStore, seconds);
2807 }
2808
2809 void TestController::setStatisticsGrandfatheringTime(double seconds)
2810 {
2811     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2812     WKWebsiteDataStoreSetStatisticsGrandfatheringTime(dataStore, seconds);
2813 }
2814
2815 void TestController::setStatisticsMaxStatisticsEntries(unsigned entries)
2816 {
2817     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2818     WKWebsiteDataStoreSetStatisticsMaxStatisticsEntries(dataStore, entries);
2819 }
2820
2821 void TestController::setStatisticsPruneEntriesDownTo(unsigned entries)
2822 {
2823     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2824     WKWebsiteDataStoreSetStatisticsPruneEntriesDownTo(dataStore, entries);
2825 }
2826
2827 void TestController::statisticsClearInMemoryAndPersistentStore()
2828 {
2829     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2830     ResourceStatisticsCallbackContext context(*this);
2831     WKWebsiteDataStoreStatisticsClearInMemoryAndPersistentStore(dataStore, &context, resourceStatisticsVoidResultCallback);
2832     runUntil(context.done, noTimeout);
2833     m_currentInvocation->didClearStatisticsThroughWebsiteDataRemoval();
2834 }
2835
2836 void TestController::statisticsClearInMemoryAndPersistentStoreModifiedSinceHours(unsigned hours)
2837 {
2838     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2839     ResourceStatisticsCallbackContext context(*this);
2840     WKWebsiteDataStoreStatisticsClearInMemoryAndPersistentStoreModifiedSinceHours(dataStore, hours, &context, resourceStatisticsVoidResultCallback);
2841     runUntil(context.done, noTimeout);
2842     m_currentInvocation->didClearStatisticsThroughWebsiteDataRemoval();
2843 }
2844
2845 void TestController::statisticsClearThroughWebsiteDataRemoval()
2846 {
2847     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2848     ResourceStatisticsCallbackContext context(*this);
2849     WKWebsiteDataStoreStatisticsClearThroughWebsiteDataRemoval(dataStore, &context, resourceStatisticsVoidResultCallback);
2850     runUntil(context.done, noTimeout);
2851     m_currentInvocation->didClearStatisticsThroughWebsiteDataRemoval();
2852 }
2853
2854 void TestController::statisticsResetToConsistentState()
2855 {
2856     auto* dataStore = WKContextGetWebsiteDataStore(platformContext());
2857     WKWebsiteDataStoreStatisticsResetToConsistentState(dataStore);
2858 }
2859
2860 } // namespace WTR