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