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