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