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