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