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