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