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