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