Rolling out r212757
[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     WKPreferencesSetSubpixelAntialiasedLayerTextEnabled(preferences, false);
646     WKPreferencesSetXSSAuditorEnabled(preferences, false);
647     WKPreferencesSetWebAudioEnabled(preferences, true);
648     WKPreferencesSetMediaStreamEnabled(preferences, true);
649     WKPreferencesSetDeveloperExtrasEnabled(preferences, true);
650     WKPreferencesSetJavaScriptRuntimeFlags(preferences, kWKJavaScriptRuntimeFlagsAllEnabled);
651     WKPreferencesSetJavaScriptCanOpenWindowsAutomatically(preferences, true);
652     WKPreferencesSetJavaScriptCanAccessClipboard(preferences, true);
653     WKPreferencesSetDOMPasteAllowed(preferences, true);
654     WKPreferencesSetUniversalAccessFromFileURLsAllowed(preferences, true);
655     WKPreferencesSetFileAccessFromFileURLsAllowed(preferences, true);
656 #if ENABLE(FULLSCREEN_API)
657     WKPreferencesSetFullScreenEnabled(preferences, true);
658 #endif
659     WKPreferencesSetPageCacheEnabled(preferences, false);
660     WKPreferencesSetAsynchronousPluginInitializationEnabled(preferences, false);
661     WKPreferencesSetAsynchronousPluginInitializationEnabledForAllPlugins(preferences, false);
662     WKPreferencesSetArtificialPluginInitializationDelayEnabled(preferences, false);
663     WKPreferencesSetTabToLinksEnabled(preferences, false);
664     WKPreferencesSetInteractiveFormValidationEnabled(preferences, true);
665
666     WKPreferencesSetMockScrollbarsEnabled(preferences, options.useMockScrollbars);
667     WKPreferencesSetNeedsSiteSpecificQuirks(preferences, options.needsSiteSpecificQuirks);
668     WKPreferencesSetIntersectionObserverEnabled(preferences, options.enableIntersectionObserver);
669     WKPreferencesSetModernMediaControlsEnabled(preferences, options.enableModernMediaControls);
670
671     static WKStringRef defaultTextEncoding = WKStringCreateWithUTF8CString("ISO-8859-1");
672     WKPreferencesSetDefaultTextEncodingName(preferences, defaultTextEncoding);
673
674     static WKStringRef standardFontFamily = WKStringCreateWithUTF8CString("Times");
675     static WKStringRef cursiveFontFamily = WKStringCreateWithUTF8CString("Apple Chancery");
676     static WKStringRef fantasyFontFamily = WKStringCreateWithUTF8CString("Papyrus");
677     static WKStringRef fixedFontFamily = WKStringCreateWithUTF8CString("Courier");
678     static WKStringRef pictographFontFamily = WKStringCreateWithUTF8CString("Apple Color Emoji");
679     static WKStringRef sansSerifFontFamily = WKStringCreateWithUTF8CString("Helvetica");
680     static WKStringRef serifFontFamily = WKStringCreateWithUTF8CString("Times");
681
682     WKPreferencesSetMinimumFontSize(preferences, 0);
683     WKPreferencesSetStandardFontFamily(preferences, standardFontFamily);
684     WKPreferencesSetCursiveFontFamily(preferences, cursiveFontFamily);
685     WKPreferencesSetFantasyFontFamily(preferences, fantasyFontFamily);
686     WKPreferencesSetFixedFontFamily(preferences, fixedFontFamily);
687     WKPreferencesSetPictographFontFamily(preferences, pictographFontFamily);
688     WKPreferencesSetSansSerifFontFamily(preferences, sansSerifFontFamily);
689     WKPreferencesSetSerifFontFamily(preferences, serifFontFamily);
690     WKPreferencesSetAsynchronousSpellCheckingEnabled(preferences, false);
691 #if ENABLE(WEB_AUDIO)
692     WKPreferencesSetMediaSourceEnabled(preferences, true);
693 #endif
694
695     WKPreferencesSetHiddenPageDOMTimerThrottlingEnabled(preferences, false);
696     WKPreferencesSetHiddenPageCSSAnimationSuspensionEnabled(preferences, false);
697
698     WKPreferencesSetAcceleratedDrawingEnabled(preferences, m_shouldUseAcceleratedDrawing);
699     // FIXME: We should be testing the default.
700     WKPreferencesSetStorageBlockingPolicy(preferences, kWKAllowAllStorage);
701
702     WKPreferencesSetResourceTimingEnabled(preferences, true);
703
704     WKPreferencesSetMediaPlaybackAllowsInline(preferences, true);
705     WKPreferencesSetInlineMediaPlaybackRequiresPlaysInlineAttribute(preferences, false);
706
707     WKCookieManagerDeleteAllCookies(WKContextGetCookieManager(m_context.get()));
708
709     WKPreferencesSetMockCaptureDevicesEnabled(preferences, true);
710
711     platformResetPreferencesToConsistentValues();
712 }
713
714 bool TestController::resetStateToConsistentValues(const TestOptions& options)
715 {
716     SetForScope<State> changeState(m_state, Resetting);
717     m_beforeUnloadReturnValue = true;
718
719     // This setting differs between the antique and modern Mac WebKit2 API.
720     // For now, maintain the antique behavior, because some tests depend on it!
721     // FIXME: We should be testing the default.
722     WKPageSetBackgroundExtendsBeyondPage(m_mainWebView->page(), false);
723
724     WKRetainPtr<WKStringRef> messageName = adoptWK(WKStringCreateWithUTF8CString("Reset"));
725     WKRetainPtr<WKMutableDictionaryRef> resetMessageBody = adoptWK(WKMutableDictionaryCreate());
726
727     WKRetainPtr<WKStringRef> shouldGCKey = adoptWK(WKStringCreateWithUTF8CString("ShouldGC"));
728     WKRetainPtr<WKBooleanRef> shouldGCValue = adoptWK(WKBooleanCreate(m_gcBetweenTests));
729     WKDictionarySetItem(resetMessageBody.get(), shouldGCKey.get(), shouldGCValue.get());
730
731     WKRetainPtr<WKStringRef> allowedHostsKey = adoptWK(WKStringCreateWithUTF8CString("AllowedHosts"));
732     WKRetainPtr<WKMutableArrayRef> allowedHostsValue = adoptWK(WKMutableArrayCreate());
733     for (auto& host : m_allowedHosts) {
734         WKRetainPtr<WKStringRef> wkHost = adoptWK(WKStringCreateWithUTF8CString(host.c_str()));
735         WKArrayAppendItem(allowedHostsValue.get(), wkHost.get());
736     }
737     WKDictionarySetItem(resetMessageBody.get(), allowedHostsKey.get(), allowedHostsValue.get());
738
739     WKPagePostMessageToInjectedBundle(TestController::singleton().mainWebView()->page(), messageName.get(), resetMessageBody.get());
740
741     WKContextSetShouldUseFontSmoothing(TestController::singleton().context(), false);
742
743     WKContextSetCacheModel(TestController::singleton().context(), kWKCacheModelDocumentBrowser);
744
745     WKContextClearCachedCredentials(TestController::singleton().context());
746
747     // FIXME: This function should also ensure that there is only one page open.
748
749     // Reset the EventSender for each test.
750     m_eventSenderProxy = std::make_unique<EventSenderProxy>(this);
751
752     // FIXME: Is this needed? Nothing in TestController changes preferences during tests, and if there is
753     // some other code doing this, it should probably be responsible for cleanup too.
754     resetPreferencesToConsistentValues(options);
755
756 #if !PLATFORM(COCOA)
757     WKTextCheckerContinuousSpellCheckingEnabledStateChanged(true);
758 #endif
759
760     // Make sure the view is in the window (a test can unparent it).
761     m_mainWebView->addToWindow();
762
763     // In the case that a test using the chrome input field failed, be sure to clean up for the next test.
764     m_mainWebView->removeChromeInputField();
765     m_mainWebView->focus();
766
767     // Re-set to the default backing scale factor by setting the custom scale factor to 0.
768     WKPageSetCustomBackingScaleFactor(m_mainWebView->page(), 0);
769
770     WKPageClearWheelEventTestTrigger(m_mainWebView->page());
771
772 #if PLATFORM(EFL)
773     // EFL uses a real window while other ports such as Qt don't.
774     // In EFL, we need to resize the window to the original size after calls to window.resizeTo.
775     WKRect rect = m_mainWebView->windowFrame();
776     m_mainWebView->setWindowFrame(WKRectMake(rect.origin.x, rect.origin.y, TestController::viewWidth, TestController::viewHeight));
777 #endif
778
779     WKPageSetMuted(m_mainWebView->page(), true);
780
781     WKPageClearUserMediaState(m_mainWebView->page());
782
783     // Reset notification permissions
784     m_webNotificationProvider.reset();
785
786     // Reset Geolocation permissions.
787     m_geolocationPermissionRequests.clear();
788     m_isGeolocationPermissionSet = false;
789     m_isGeolocationPermissionAllowed = false;
790
791     // Reset UserMedia permissions.
792     m_userMediaPermissionRequests.clear();
793     m_cachedUserMediaPermissions.clear();
794     m_isUserMediaPermissionSet = false;
795     m_isUserMediaPermissionAllowed = false;
796
797     // Reset Custom Policy Delegate.
798     setCustomPolicyDelegate(false, false);
799
800     m_shouldDownloadUndisplayableMIMETypes = false;
801
802     m_workQueueManager.clearWorkQueue();
803
804     m_rejectsProtectionSpaceAndContinueForAuthenticationChallenges = false;
805     m_handlesAuthenticationChallenges = false;
806     m_authenticationUsername = String();
807     m_authenticationPassword = String();
808
809     m_shouldBlockAllPlugins = false;
810
811     m_shouldLogHistoryClientCallbacks = false;
812     m_shouldLogCanAuthenticateAgainstProtectionSpace = false;
813
814     setHidden(false);
815
816     platformResetStateToConsistentValues();
817
818     // Reset main page back to about:blank
819     m_doneResetting = false;
820
821     m_shouldDecideNavigationPolicyAfterDelay = false;
822
823     setNavigationGesturesEnabled(false);
824     
825     setIgnoresViewportScaleLimits(options.ignoresViewportScaleLimits);
826
827     WKPageLoadURL(m_mainWebView->page(), blankURL());
828     runUntil(m_doneResetting, m_currentInvocation->shortTimeout());
829     return m_doneResetting;
830 }
831
832 void TestController::terminateWebContentProcess()
833 {
834     WKPageTerminate(m_mainWebView->page());
835 }
836
837 void TestController::reattachPageToWebProcess()
838 {
839     // Loading a web page is the only way to reattach an existing page to a process.
840     m_doneResetting = false;
841     WKPageLoadURL(m_mainWebView->page(), blankURL());
842     runUntil(m_doneResetting, m_currentInvocation->shortTimeout());
843 }
844
845 const char* TestController::webProcessName()
846 {
847     // FIXME: Find a way to not hardcode the process name.
848 #if PLATFORM(COCOA)
849     return "com.apple.WebKit.WebContent.Development";
850 #else
851     return "WebProcess";
852 #endif
853 }
854
855 const char* TestController::networkProcessName()
856 {
857     // FIXME: Find a way to not hardcode the process name.
858 #if PLATFORM(COCOA)
859     return "com.apple.WebKit.Networking.Development";
860 #else
861     return "NetworkProcess";
862 #endif
863 }
864
865 const char* TestController::databaseProcessName()
866 {
867     // FIXME: Find a way to not hardcode the process name.
868 #if PLATFORM(COCOA)
869     return "com.apple.WebKit.Databases.Development";
870 #else
871     return "DatabaseProcess";
872 #endif
873 }
874
875 static std::string testPath(WKURLRef url)
876 {
877     auto scheme = adoptWK(WKURLCopyScheme(url));
878     if (WKStringIsEqualToUTF8CStringIgnoringCase(scheme.get(), "file")) {
879         auto path = adoptWK(WKURLCopyPath(url));
880         auto buffer = std::vector<char>(WKStringGetMaximumUTF8CStringSize(path.get()));
881         auto length = WKStringGetUTF8CString(path.get(), buffer.data(), buffer.size());
882         return std::string(buffer.data(), length);
883     }
884     return std::string();
885 }
886
887 static WKURLRef createTestURL(const char* pathOrURL)
888 {
889     if (strstr(pathOrURL, "http://") || strstr(pathOrURL, "https://") || strstr(pathOrURL, "file://"))
890         return WKURLCreateWithUTF8CString(pathOrURL);
891
892     // Creating from filesytem path.
893     size_t length = strlen(pathOrURL);
894     if (!length)
895         return 0;
896
897     const char separator = '/';
898     bool isAbsolutePath = pathOrURL[0] == separator;
899     const char* filePrefix = "file://";
900     static const size_t prefixLength = strlen(filePrefix);
901
902     std::unique_ptr<char[]> buffer;
903     if (isAbsolutePath) {
904         buffer = std::make_unique<char[]>(prefixLength + length + 1);
905         strcpy(buffer.get(), filePrefix);
906         strcpy(buffer.get() + prefixLength, pathOrURL);
907     } else {
908         buffer = std::make_unique<char[]>(prefixLength + PATH_MAX + length + 2); // 1 for the separator
909         strcpy(buffer.get(), filePrefix);
910         if (!getcwd(buffer.get() + prefixLength, PATH_MAX))
911             return 0;
912         size_t numCharacters = strlen(buffer.get());
913         buffer[numCharacters] = separator;
914         strcpy(buffer.get() + numCharacters + 1, pathOrURL);
915     }
916
917     return WKURLCreateWithUTF8CString(buffer.get());
918 }
919
920 static bool parseBooleanTestHeaderValue(const std::string& value)
921 {
922     if (value == "true")
923         return true;
924     if (value == "false")
925         return false;
926
927     LOG_ERROR("Found unexpected value '%s' for boolean option. Expected 'true' or 'false'.", value.c_str());
928     return false;
929 }
930
931 static void updateTestOptionsFromTestHeader(TestOptions& testOptions, const std::string& pathOrURL, const std::string& absolutePath)
932 {
933     std::string filename = absolutePath;
934     if (filename.empty()) {
935         // Gross. Need to reduce conversions between all the string types and URLs.
936         WKRetainPtr<WKURLRef> wkURL(AdoptWK, createTestURL(pathOrURL.c_str()));
937         filename = testPath(wkURL.get());
938     }
939
940     if (filename.empty())
941         return;
942
943     std::string options;
944     std::ifstream testFile(filename.data());
945     if (!testFile.good())
946         return;
947     getline(testFile, options);
948     std::string beginString("webkit-test-runner [ ");
949     std::string endString(" ]");
950     size_t beginLocation = options.find(beginString);
951     if (beginLocation == std::string::npos)
952         return;
953     size_t endLocation = options.find(endString, beginLocation);
954     if (endLocation == std::string::npos) {
955         LOG_ERROR("Could not find end of test header in %s", filename.c_str());
956         return;
957     }
958     std::string pairString = options.substr(beginLocation + beginString.size(), endLocation - (beginLocation + beginString.size()));
959     size_t pairStart = 0;
960     while (pairStart < pairString.size()) {
961         size_t pairEnd = pairString.find(" ", pairStart);
962         if (pairEnd == std::string::npos)
963             pairEnd = pairString.size();
964         size_t equalsLocation = pairString.find("=", pairStart);
965         if (equalsLocation == std::string::npos) {
966             LOG_ERROR("Malformed option in test header (could not find '=' character) in %s", filename.c_str());
967             break;
968         }
969         auto key = pairString.substr(pairStart, equalsLocation - pairStart);
970         auto value = pairString.substr(equalsLocation + 1, pairEnd - (equalsLocation + 1));
971         if (key == "language")
972             String(value.c_str()).split(",", false, testOptions.overrideLanguages);
973         if (key == "useThreadedScrolling")
974             testOptions.useThreadedScrolling = parseBooleanTestHeaderValue(value);
975         if (key == "useFlexibleViewport")
976             testOptions.useFlexibleViewport = parseBooleanTestHeaderValue(value);
977         if (key == "useDataDetection")
978             testOptions.useDataDetection = parseBooleanTestHeaderValue(value);
979         if (key == "useMockScrollbars")
980             testOptions.useMockScrollbars = parseBooleanTestHeaderValue(value);
981         if (key == "needsSiteSpecificQuirks")
982             testOptions.needsSiteSpecificQuirks = parseBooleanTestHeaderValue(value);
983         if (key == "ignoresViewportScaleLimits")
984             testOptions.ignoresViewportScaleLimits = parseBooleanTestHeaderValue(value);
985         if (key == "useCharacterSelectionGranularity")
986             testOptions.useCharacterSelectionGranularity = parseBooleanTestHeaderValue(value);
987         if (key == "enableIntersectionObserver")
988             testOptions.enableIntersectionObserver = parseBooleanTestHeaderValue(value);
989         if (key == "enableModernMediaControls")
990             testOptions.enableModernMediaControls = parseBooleanTestHeaderValue(value);
991         if (key == "enablePointerLock")
992             testOptions.enablePointerLock = parseBooleanTestHeaderValue(value);
993         pairStart = pairEnd + 1;
994     }
995 }
996
997 TestOptions TestController::testOptionsForTest(const TestCommand& command) const
998 {
999     TestOptions options(command.pathOrURL);
1000
1001     options.useRemoteLayerTree = m_shouldUseRemoteLayerTree;
1002     options.shouldShowWebView = m_shouldShowWebView;
1003
1004     updatePlatformSpecificTestOptionsForTest(options, command.pathOrURL);
1005     updateTestOptionsFromTestHeader(options, command.pathOrURL, command.absolutePath);
1006
1007     return options;
1008 }
1009
1010 void TestController::updateWebViewSizeForTest(const TestInvocation& test)
1011 {
1012     unsigned width = viewWidth;
1013     unsigned height = viewHeight;
1014     if (test.options().isSVGTest) {
1015         width = w3cSVGViewWidth;
1016         height = w3cSVGViewHeight;
1017     }
1018
1019     mainWebView()->resizeTo(width, height);
1020 }
1021
1022 void TestController::updateWindowScaleForTest(PlatformWebView* view, const TestInvocation& test)
1023 {
1024     view->changeWindowScaleIfNeeded(test.options().deviceScaleFactor);
1025 }
1026
1027 void TestController::configureViewForTest(const TestInvocation& test)
1028 {
1029     ensureViewSupportsOptionsForTest(test);
1030     updateWebViewSizeForTest(test);
1031     updateWindowScaleForTest(mainWebView(), test);
1032
1033     platformConfigureViewForTest(test);
1034 }
1035
1036 class CommandTokenizer {
1037 public:
1038     explicit CommandTokenizer(const std::string& input)
1039         : m_input(input)
1040         , m_posNextSeparator(0)
1041     {
1042         pump();
1043     }
1044
1045     bool hasNext() const;
1046     std::string next();
1047
1048 private:
1049     void pump();
1050     static const char kSeparator = '\'';
1051     const std::string& m_input;
1052     std::string m_next;
1053     size_t m_posNextSeparator;
1054 };
1055
1056 void CommandTokenizer::pump()
1057 {
1058     if (m_posNextSeparator == std::string::npos || m_posNextSeparator == m_input.size()) {
1059         m_next = std::string();
1060         return;
1061     }
1062     size_t start = m_posNextSeparator ? m_posNextSeparator + 1 : 0;
1063     m_posNextSeparator = m_input.find(kSeparator, start);
1064     size_t size = m_posNextSeparator == std::string::npos ? std::string::npos : m_posNextSeparator - start;
1065     m_next = std::string(m_input, start, size);
1066 }
1067
1068 std::string CommandTokenizer::next()
1069 {
1070     ASSERT(hasNext());
1071
1072     std::string oldNext = m_next;
1073     pump();
1074     return oldNext;
1075 }
1076
1077 bool CommandTokenizer::hasNext() const
1078 {
1079     return !m_next.empty();
1080 }
1081
1082 NO_RETURN static void die(const std::string& inputLine)
1083 {
1084     fprintf(stderr, "Unexpected input line: %s\n", inputLine.c_str());
1085     exit(1);
1086 }
1087
1088 TestCommand parseInputLine(const std::string& inputLine)
1089 {
1090     TestCommand result;
1091     CommandTokenizer tokenizer(inputLine);
1092     if (!tokenizer.hasNext())
1093         die(inputLine);
1094
1095     std::string arg = tokenizer.next();
1096     result.pathOrURL = arg;
1097     while (tokenizer.hasNext()) {
1098         arg = tokenizer.next();
1099         if (arg == std::string("--timeout")) {
1100             std::string timeoutToken = tokenizer.next();
1101             result.timeout = atoi(timeoutToken.c_str());
1102         } else if (arg == std::string("-p") || arg == std::string("--pixel-test")) {
1103             result.shouldDumpPixels = true;
1104             if (tokenizer.hasNext())
1105                 result.expectedPixelHash = tokenizer.next();
1106         } else if (arg == std::string("--dump-jsconsolelog-in-stderr"))
1107             result.dumpJSConsoleLogInStdErr = true;
1108         else if (arg == std::string("--absolutePath"))
1109             result.absolutePath = tokenizer.next();
1110         else
1111             die(inputLine);
1112     }
1113     return result;
1114 }
1115
1116 bool TestController::runTest(const char* inputLine)
1117 {
1118     WKTextCheckerSetTestingMode(true);
1119     TestCommand command = parseInputLine(std::string(inputLine));
1120
1121     m_state = RunningTest;
1122     
1123     TestOptions options = testOptionsForTest(command);
1124
1125     WKRetainPtr<WKURLRef> wkURL(AdoptWK, createTestURL(command.pathOrURL.c_str()));
1126     m_currentInvocation = std::make_unique<TestInvocation>(wkURL.get(), options);
1127
1128     if (command.shouldDumpPixels || m_shouldDumpPixelsForAllTests)
1129         m_currentInvocation->setIsPixelTest(command.expectedPixelHash);
1130     if (command.timeout > 0)
1131         m_currentInvocation->setCustomTimeout(command.timeout);
1132     m_currentInvocation->setDumpJSConsoleLogInStdErr(command.dumpJSConsoleLogInStdErr);
1133
1134     platformWillRunTest(*m_currentInvocation);
1135
1136     m_currentInvocation->invoke();
1137     m_currentInvocation = nullptr;
1138
1139     return true;
1140 }
1141
1142 void TestController::runTestingServerLoop()
1143 {
1144     char filenameBuffer[2048];
1145     while (fgets(filenameBuffer, sizeof(filenameBuffer), stdin)) {
1146         char* newLineCharacter = strchr(filenameBuffer, '\n');
1147         if (newLineCharacter)
1148             *newLineCharacter = '\0';
1149
1150         if (strlen(filenameBuffer) == 0)
1151             continue;
1152
1153         if (!runTest(filenameBuffer))
1154             break;
1155     }
1156 }
1157
1158 void TestController::run()
1159 {
1160     if (m_usingServerMode)
1161         runTestingServerLoop();
1162     else {
1163         for (size_t i = 0; i < m_paths.size(); ++i) {
1164             if (!runTest(m_paths[i].c_str()))
1165                 break;
1166         }
1167     }
1168 }
1169
1170 void TestController::runUntil(bool& done, double timeout)
1171 {
1172     if (m_forceNoTimeout)
1173         timeout = noTimeout;
1174
1175     platformRunUntil(done, timeout);
1176 }
1177
1178 // WKContextInjectedBundleClient
1179
1180 void TestController::didReceiveMessageFromInjectedBundle(WKContextRef context, WKStringRef messageName, WKTypeRef messageBody, const void* clientInfo)
1181 {
1182     static_cast<TestController*>(const_cast<void*>(clientInfo))->didReceiveMessageFromInjectedBundle(messageName, messageBody);
1183 }
1184
1185 void TestController::didReceiveSynchronousMessageFromInjectedBundle(WKContextRef context, WKStringRef messageName, WKTypeRef messageBody, WKTypeRef* returnData, const void* clientInfo)
1186 {
1187     *returnData = static_cast<TestController*>(const_cast<void*>(clientInfo))->didReceiveSynchronousMessageFromInjectedBundle(messageName, messageBody).leakRef();
1188 }
1189
1190 WKTypeRef TestController::getInjectedBundleInitializationUserData(WKContextRef, const void* clientInfo)
1191 {
1192     return static_cast<TestController*>(const_cast<void*>(clientInfo))->getInjectedBundleInitializationUserData().leakRef();
1193 }
1194
1195 // WKPageInjectedBundleClient
1196
1197 void TestController::didReceivePageMessageFromInjectedBundle(WKPageRef page, WKStringRef messageName, WKTypeRef messageBody, const void* clientInfo)
1198 {
1199     static_cast<TestController*>(const_cast<void*>(clientInfo))->didReceiveMessageFromInjectedBundle(messageName, messageBody);
1200 }
1201
1202 void TestController::didReceiveSynchronousPageMessageFromInjectedBundle(WKPageRef page, WKStringRef messageName, WKTypeRef messageBody, WKTypeRef* returnData, const void* clientInfo)
1203 {
1204     *returnData = static_cast<TestController*>(const_cast<void*>(clientInfo))->didReceiveSynchronousMessageFromInjectedBundle(messageName, messageBody).leakRef();
1205 }
1206
1207 void TestController::networkProcessDidCrash(WKContextRef context, const void *clientInfo)
1208 {
1209     static_cast<TestController*>(const_cast<void*>(clientInfo))->networkProcessDidCrash();
1210 }
1211
1212 void TestController::databaseProcessDidCrash(WKContextRef context, const void *clientInfo)
1213 {
1214     static_cast<TestController*>(const_cast<void*>(clientInfo))->databaseProcessDidCrash();
1215 }
1216
1217 void TestController::didReceiveKeyDownMessageFromInjectedBundle(WKDictionaryRef messageBodyDictionary, bool synchronous)
1218 {
1219     WKRetainPtr<WKStringRef> keyKey = adoptWK(WKStringCreateWithUTF8CString("Key"));
1220     WKStringRef key = static_cast<WKStringRef>(WKDictionaryGetItemForKey(messageBodyDictionary, keyKey.get()));
1221
1222     WKRetainPtr<WKStringRef> modifiersKey = adoptWK(WKStringCreateWithUTF8CString("Modifiers"));
1223     WKEventModifiers modifiers = static_cast<WKEventModifiers>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, modifiersKey.get()))));
1224
1225     WKRetainPtr<WKStringRef> locationKey = adoptWK(WKStringCreateWithUTF8CString("Location"));
1226     unsigned location = static_cast<unsigned>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, locationKey.get()))));
1227
1228     m_eventSenderProxy->keyDown(key, modifiers, location);
1229 }
1230
1231 void TestController::didReceiveMessageFromInjectedBundle(WKStringRef messageName, WKTypeRef messageBody)
1232 {
1233     if (WKStringIsEqualToUTF8CString(messageName, "EventSender")) {
1234         if (m_state != RunningTest)
1235             return;
1236
1237         ASSERT(WKGetTypeID(messageBody) == WKDictionaryGetTypeID());
1238         WKDictionaryRef messageBodyDictionary = static_cast<WKDictionaryRef>(messageBody);
1239
1240         WKRetainPtr<WKStringRef> subMessageKey(AdoptWK, WKStringCreateWithUTF8CString("SubMessage"));
1241         WKStringRef subMessageName = static_cast<WKStringRef>(WKDictionaryGetItemForKey(messageBodyDictionary, subMessageKey.get()));
1242
1243         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseDown") || WKStringIsEqualToUTF8CString(subMessageName, "MouseUp")) {
1244             WKRetainPtr<WKStringRef> buttonKey = adoptWK(WKStringCreateWithUTF8CString("Button"));
1245             unsigned button = static_cast<unsigned>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, buttonKey.get()))));
1246
1247             WKRetainPtr<WKStringRef> modifiersKey = adoptWK(WKStringCreateWithUTF8CString("Modifiers"));
1248             WKEventModifiers modifiers = static_cast<WKEventModifiers>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, modifiersKey.get()))));
1249
1250             // Forward to WebProcess
1251             if (WKStringIsEqualToUTF8CString(subMessageName, "MouseDown"))
1252                 m_eventSenderProxy->mouseDown(button, modifiers);
1253             else
1254                 m_eventSenderProxy->mouseUp(button, modifiers);
1255
1256             return;
1257         }
1258
1259         if (WKStringIsEqualToUTF8CString(subMessageName, "KeyDown")) {
1260             didReceiveKeyDownMessageFromInjectedBundle(messageBodyDictionary, false);
1261
1262             return;
1263         }
1264
1265         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseScrollBy")) {
1266             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
1267             double x = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get())));
1268
1269             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
1270             double y = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get())));
1271
1272             // Forward to WebProcess
1273             m_eventSenderProxy->mouseScrollBy(x, y);
1274             return;
1275         }
1276
1277         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseScrollByWithWheelAndMomentumPhases")) {
1278             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
1279             double x = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get())));
1280             
1281             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
1282             double y = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get())));
1283             
1284             WKRetainPtr<WKStringRef> phaseKey = adoptWK(WKStringCreateWithUTF8CString("Phase"));
1285             int phase = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, phaseKey.get()))));
1286             WKRetainPtr<WKStringRef> momentumKey = adoptWK(WKStringCreateWithUTF8CString("Momentum"));
1287             int momentum = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, momentumKey.get()))));
1288             
1289             // Forward to WebProcess
1290             m_eventSenderProxy->mouseScrollByWithWheelAndMomentumPhases(x, y, phase, momentum);
1291
1292             return;
1293         }
1294
1295         if (WKStringIsEqualToUTF8CString(subMessageName, "SwipeGestureWithWheelAndMomentumPhases")) {
1296             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
1297             double x = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get())));
1298
1299             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
1300             double y = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get())));
1301
1302             WKRetainPtr<WKStringRef> phaseKey = adoptWK(WKStringCreateWithUTF8CString("Phase"));
1303             int phase = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, phaseKey.get()))));
1304             WKRetainPtr<WKStringRef> momentumKey = adoptWK(WKStringCreateWithUTF8CString("Momentum"));
1305             int momentum = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, momentumKey.get()))));
1306
1307             m_eventSenderProxy->swipeGestureWithWheelAndMomentumPhases(x, y, phase, momentum);
1308
1309             return;
1310         }
1311
1312         ASSERT_NOT_REACHED();
1313     }
1314
1315     if (!m_currentInvocation)
1316         return;
1317
1318     m_currentInvocation->didReceiveMessageFromInjectedBundle(messageName, messageBody);
1319 }
1320
1321 WKRetainPtr<WKTypeRef> TestController::didReceiveSynchronousMessageFromInjectedBundle(WKStringRef messageName, WKTypeRef messageBody)
1322 {
1323     if (WKStringIsEqualToUTF8CString(messageName, "EventSender")) {
1324         if (m_state != RunningTest)
1325             return nullptr;
1326
1327         ASSERT(WKGetTypeID(messageBody) == WKDictionaryGetTypeID());
1328         WKDictionaryRef messageBodyDictionary = static_cast<WKDictionaryRef>(messageBody);
1329
1330         WKRetainPtr<WKStringRef> subMessageKey(AdoptWK, WKStringCreateWithUTF8CString("SubMessage"));
1331         WKStringRef subMessageName = static_cast<WKStringRef>(WKDictionaryGetItemForKey(messageBodyDictionary, subMessageKey.get()));
1332
1333         if (WKStringIsEqualToUTF8CString(subMessageName, "KeyDown")) {
1334             didReceiveKeyDownMessageFromInjectedBundle(messageBodyDictionary, true);
1335
1336             return 0;
1337         }
1338
1339         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseDown") || WKStringIsEqualToUTF8CString(subMessageName, "MouseUp")) {
1340             WKRetainPtr<WKStringRef> buttonKey = adoptWK(WKStringCreateWithUTF8CString("Button"));
1341             unsigned button = static_cast<unsigned>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, buttonKey.get()))));
1342
1343             WKRetainPtr<WKStringRef> modifiersKey = adoptWK(WKStringCreateWithUTF8CString("Modifiers"));
1344             WKEventModifiers modifiers = static_cast<WKEventModifiers>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, modifiersKey.get()))));
1345
1346             // Forward to WebProcess
1347             if (WKStringIsEqualToUTF8CString(subMessageName, "MouseDown"))
1348                 m_eventSenderProxy->mouseDown(button, modifiers);
1349             else
1350                 m_eventSenderProxy->mouseUp(button, modifiers);
1351             return 0;
1352         }
1353
1354         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseMoveTo")) {
1355             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
1356             double x = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get())));
1357
1358             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
1359             double y = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get())));
1360
1361             // Forward to WebProcess
1362             m_eventSenderProxy->mouseMoveTo(x, y);
1363             return 0;
1364         }
1365
1366 #if PLATFORM(MAC)
1367         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseForceClick")) {
1368             m_eventSenderProxy->mouseForceClick();
1369             return 0;
1370         }
1371
1372         if (WKStringIsEqualToUTF8CString(subMessageName, "StartAndCancelMouseForceClick")) {
1373             m_eventSenderProxy->startAndCancelMouseForceClick();
1374             return 0;
1375         }
1376
1377         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseForceDown")) {
1378             m_eventSenderProxy->mouseForceDown();
1379             return 0;
1380         }
1381
1382         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseForceUp")) {
1383             m_eventSenderProxy->mouseForceUp();
1384             return 0;
1385         }
1386
1387         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseForceChanged")) {
1388             WKRetainPtr<WKStringRef> forceKey = adoptWK(WKStringCreateWithUTF8CString("Force"));
1389             double force = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, forceKey.get())));
1390
1391             m_eventSenderProxy->mouseForceChanged(force);
1392             return 0;
1393         }
1394 #endif // PLATFORM(MAC)
1395
1396         if (WKStringIsEqualToUTF8CString(subMessageName, "ContinuousMouseScrollBy")) {
1397             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
1398             double x = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get())));
1399
1400             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
1401             double y = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get())));
1402
1403             WKRetainPtr<WKStringRef> pagedKey = adoptWK(WKStringCreateWithUTF8CString("Paged"));
1404             bool paged = static_cast<bool>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, pagedKey.get()))));
1405
1406             // Forward to WebProcess
1407             m_eventSenderProxy->continuousMouseScrollBy(x, y, paged);
1408             return 0;
1409         }
1410
1411         if (WKStringIsEqualToUTF8CString(subMessageName, "LeapForward")) {
1412             WKRetainPtr<WKStringRef> timeKey = adoptWK(WKStringCreateWithUTF8CString("TimeInMilliseconds"));
1413             unsigned time = static_cast<unsigned>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, timeKey.get()))));
1414
1415             m_eventSenderProxy->leapForward(time);
1416             return 0;
1417         }
1418
1419 #if ENABLE(TOUCH_EVENTS)
1420         if (WKStringIsEqualToUTF8CString(subMessageName, "AddTouchPoint")) {
1421             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
1422             int x = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get()))));
1423
1424             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
1425             int y = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get()))));
1426
1427             m_eventSenderProxy->addTouchPoint(x, y);
1428             return 0;
1429         }
1430
1431         if (WKStringIsEqualToUTF8CString(subMessageName, "UpdateTouchPoint")) {
1432             WKRetainPtr<WKStringRef> indexKey = adoptWK(WKStringCreateWithUTF8CString("Index"));
1433             int index = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, indexKey.get()))));
1434
1435             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
1436             int x = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get()))));
1437
1438             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
1439             int y = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get()))));
1440
1441             m_eventSenderProxy->updateTouchPoint(index, x, y);
1442             return 0;
1443         }
1444
1445         if (WKStringIsEqualToUTF8CString(subMessageName, "SetTouchModifier")) {
1446             WKRetainPtr<WKStringRef> modifierKey = adoptWK(WKStringCreateWithUTF8CString("Modifier"));
1447             WKEventModifiers modifier = static_cast<WKEventModifiers>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, modifierKey.get()))));
1448
1449             WKRetainPtr<WKStringRef> enableKey = adoptWK(WKStringCreateWithUTF8CString("Enable"));
1450             bool enable = static_cast<bool>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, enableKey.get()))));
1451
1452             m_eventSenderProxy->setTouchModifier(modifier, enable);
1453             return 0;
1454         }
1455
1456         if (WKStringIsEqualToUTF8CString(subMessageName, "SetTouchPointRadius")) {
1457             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("RadiusX"));
1458             int x = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get()))));
1459
1460             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("RadiusY"));
1461             int y = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get()))));
1462
1463             m_eventSenderProxy->setTouchPointRadius(x, y);
1464             return 0;
1465         }
1466
1467         if (WKStringIsEqualToUTF8CString(subMessageName, "TouchStart")) {
1468             m_eventSenderProxy->touchStart();
1469             return 0;
1470         }
1471
1472         if (WKStringIsEqualToUTF8CString(subMessageName, "TouchMove")) {
1473             m_eventSenderProxy->touchMove();
1474             return 0;
1475         }
1476
1477         if (WKStringIsEqualToUTF8CString(subMessageName, "TouchEnd")) {
1478             m_eventSenderProxy->touchEnd();
1479             return 0;
1480         }
1481
1482         if (WKStringIsEqualToUTF8CString(subMessageName, "TouchCancel")) {
1483             m_eventSenderProxy->touchCancel();
1484             return 0;
1485         }
1486
1487         if (WKStringIsEqualToUTF8CString(subMessageName, "ClearTouchPoints")) {
1488             m_eventSenderProxy->clearTouchPoints();
1489             return 0;
1490         }
1491
1492         if (WKStringIsEqualToUTF8CString(subMessageName, "ReleaseTouchPoint")) {
1493             WKRetainPtr<WKStringRef> indexKey = adoptWK(WKStringCreateWithUTF8CString("Index"));
1494             int index = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, indexKey.get()))));
1495             m_eventSenderProxy->releaseTouchPoint(index);
1496             return 0;
1497         }
1498
1499         if (WKStringIsEqualToUTF8CString(subMessageName, "CancelTouchPoint")) {
1500             WKRetainPtr<WKStringRef> indexKey = adoptWK(WKStringCreateWithUTF8CString("Index"));
1501             int index = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, indexKey.get()))));
1502             m_eventSenderProxy->cancelTouchPoint(index);
1503             return 0;
1504         }
1505 #endif
1506         ASSERT_NOT_REACHED();
1507     }
1508     return m_currentInvocation->didReceiveSynchronousMessageFromInjectedBundle(messageName, messageBody);
1509 }
1510
1511 WKRetainPtr<WKTypeRef> TestController::getInjectedBundleInitializationUserData()
1512 {
1513     return nullptr;
1514 }
1515
1516 // WKContextClient
1517
1518 void TestController::networkProcessDidCrash()
1519 {
1520     pid_t pid = WKContextGetNetworkProcessIdentifier(m_context.get());
1521     fprintf(stderr, "#CRASHED - %s (pid %ld)\n", networkProcessName(), static_cast<long>(pid));
1522     exit(1);
1523 }
1524
1525 void TestController::databaseProcessDidCrash()
1526 {
1527     pid_t pid = WKContextGetDatabaseProcessIdentifier(m_context.get());
1528     fprintf(stderr, "#CRASHED - %s (pid %ld)\n", databaseProcessName(), static_cast<long>(pid));
1529     exit(1);
1530 }
1531
1532 // WKPageNavigationClient
1533
1534 void TestController::didCommitNavigation(WKPageRef page, WKNavigationRef navigation, WKTypeRef, const void* clientInfo)
1535 {
1536     static_cast<TestController*>(const_cast<void*>(clientInfo))->didCommitNavigation(page, navigation);
1537 }
1538
1539 void TestController::didFinishNavigation(WKPageRef page, WKNavigationRef navigation, WKTypeRef, const void* clientInfo)
1540 {
1541     static_cast<TestController*>(const_cast<void*>(clientInfo))->didFinishNavigation(page, navigation);
1542 }
1543
1544 bool TestController::canAuthenticateAgainstProtectionSpace(WKPageRef page, WKProtectionSpaceRef protectionSpace, const void* clientInfo)
1545 {
1546     return static_cast<TestController*>(const_cast<void*>(clientInfo))->canAuthenticateAgainstProtectionSpace(page, protectionSpace);
1547 }
1548
1549 void TestController::didReceiveAuthenticationChallenge(WKPageRef page, WKAuthenticationChallengeRef authenticationChallenge, const void *clientInfo)
1550 {
1551     static_cast<TestController*>(const_cast<void*>(clientInfo))->didReceiveAuthenticationChallenge(page, /*frame,*/ authenticationChallenge);
1552 }
1553
1554 void TestController::processDidCrash(WKPageRef page, const void* clientInfo)
1555 {
1556     static_cast<TestController*>(const_cast<void*>(clientInfo))->processDidCrash();
1557 }
1558
1559 void TestController::didBeginNavigationGesture(WKPageRef page, const void *clientInfo)
1560 {
1561     static_cast<TestController*>(const_cast<void*>(clientInfo))->didBeginNavigationGesture(page);
1562 }
1563
1564 void TestController::willEndNavigationGesture(WKPageRef page, WKBackForwardListItemRef backForwardListItem, const void *clientInfo)
1565 {
1566     static_cast<TestController*>(const_cast<void*>(clientInfo))->willEndNavigationGesture(page, backForwardListItem);
1567 }
1568
1569 void TestController::didEndNavigationGesture(WKPageRef page, WKBackForwardListItemRef backForwardListItem, const void *clientInfo)
1570 {
1571     static_cast<TestController*>(const_cast<void*>(clientInfo))->didEndNavigationGesture(page, backForwardListItem);
1572 }
1573
1574 void TestController::didRemoveNavigationGestureSnapshot(WKPageRef page, const void *clientInfo)
1575 {
1576     static_cast<TestController*>(const_cast<void*>(clientInfo))->didRemoveNavigationGestureSnapshot(page);
1577 }
1578
1579 WKPluginLoadPolicy TestController::decidePolicyForPluginLoad(WKPageRef page, WKPluginLoadPolicy currentPluginLoadPolicy, WKDictionaryRef pluginInformation, WKStringRef* unavailabilityDescription, const void* clientInfo)
1580 {
1581     return static_cast<TestController*>(const_cast<void*>(clientInfo))->decidePolicyForPluginLoad(page, currentPluginLoadPolicy, pluginInformation, unavailabilityDescription);
1582 }
1583
1584 WKPluginLoadPolicy TestController::decidePolicyForPluginLoad(WKPageRef, WKPluginLoadPolicy currentPluginLoadPolicy, WKDictionaryRef pluginInformation, WKStringRef* unavailabilityDescription)
1585 {
1586     if (m_shouldBlockAllPlugins)
1587         return kWKPluginLoadPolicyBlocked;
1588
1589 #if PLATFORM(MAC)
1590     WKStringRef bundleIdentifier = (WKStringRef)WKDictionaryGetItemForKey(pluginInformation, WKPluginInformationBundleIdentifierKey());
1591     if (!bundleIdentifier)
1592         return currentPluginLoadPolicy;
1593
1594     if (WKStringIsEqualToUTF8CString(bundleIdentifier, "com.apple.QuickTime Plugin.plugin"))
1595         return currentPluginLoadPolicy;
1596
1597     if (WKStringIsEqualToUTF8CString(bundleIdentifier, "com.apple.testnetscapeplugin"))
1598         return currentPluginLoadPolicy;
1599
1600     RELEASE_ASSERT_NOT_REACHED(); // Please don't use any other plug-ins in tests, as they will not be installed on all machines.
1601 #else
1602     return currentPluginLoadPolicy;
1603 #endif
1604 }
1605
1606 void TestController::didCommitNavigation(WKPageRef page, WKNavigationRef navigation)
1607 {
1608     mainWebView()->focus();
1609 }
1610
1611 bool TestController::canAuthenticateAgainstProtectionSpace(WKPageRef page, WKProtectionSpaceRef protectionSpace)
1612 {
1613     if (m_shouldLogCanAuthenticateAgainstProtectionSpace)
1614         m_currentInvocation->outputText("canAuthenticateAgainstProtectionSpace\n");
1615     WKProtectionSpaceAuthenticationScheme authenticationScheme = WKProtectionSpaceGetAuthenticationScheme(protectionSpace);
1616     
1617     if (authenticationScheme == kWKProtectionSpaceAuthenticationSchemeServerTrustEvaluationRequested) {
1618         std::string host = toSTD(adoptWK(WKProtectionSpaceCopyHost(protectionSpace)).get());
1619         return host == "localhost" || host == "127.0.0.1";
1620     }
1621     
1622     return authenticationScheme <= kWKProtectionSpaceAuthenticationSchemeHTTPDigest;
1623 }
1624
1625 void TestController::didFinishNavigation(WKPageRef page, WKNavigationRef navigation)
1626 {
1627     if (m_state != Resetting)
1628         return;
1629
1630     WKRetainPtr<WKURLRef> wkURL(AdoptWK, WKFrameCopyURL(WKPageGetMainFrame(page)));
1631     if (!WKURLIsEqual(wkURL.get(), blankURL()))
1632         return;
1633
1634     m_doneResetting = true;
1635     singleton().notifyDone();
1636 }
1637
1638 void TestController::didReceiveAuthenticationChallenge(WKPageRef page, WKAuthenticationChallengeRef authenticationChallenge)
1639 {
1640     WKProtectionSpaceRef protectionSpace = WKAuthenticationChallengeGetProtectionSpace(authenticationChallenge);
1641     WKAuthenticationDecisionListenerRef decisionListener = WKAuthenticationChallengeGetDecisionListener(authenticationChallenge);
1642
1643     if (WKProtectionSpaceGetAuthenticationScheme(protectionSpace) == kWKProtectionSpaceAuthenticationSchemeServerTrustEvaluationRequested) {
1644         // Any non-empty credential signals to accept the server trust. Since the cross-platform API
1645         // doesn't expose a way to create a credential from server trust, we use a password credential.
1646
1647         WKRetainPtr<WKCredentialRef> credential = adoptWK(WKCredentialCreate(toWK("accept server trust").get(), toWK("").get(), kWKCredentialPersistenceNone));
1648         WKAuthenticationDecisionListenerUseCredential(decisionListener, credential.get());
1649         return;
1650     }
1651
1652     if (m_rejectsProtectionSpaceAndContinueForAuthenticationChallenges) {
1653         m_currentInvocation->outputText("Simulating reject protection space and continue for authentication challenge\n");
1654         WKAuthenticationDecisionListenerRejectProtectionSpaceAndContinue(decisionListener);
1655         return;
1656     }
1657
1658     std::string host = toSTD(adoptWK(WKProtectionSpaceCopyHost(protectionSpace)).get());
1659     int port = WKProtectionSpaceGetPort(protectionSpace);
1660     String message = String::format("%s:%d - didReceiveAuthenticationChallenge - ", host.c_str(), port);
1661     if (!m_handlesAuthenticationChallenges)
1662         message.append("Simulating cancelled authentication sheet\n");
1663     else
1664         message.append(String::format("Responding with %s:%s\n", m_authenticationUsername.utf8().data(), m_authenticationPassword.utf8().data()));
1665     m_currentInvocation->outputText(message);
1666
1667     if (!m_handlesAuthenticationChallenges) {
1668         WKAuthenticationDecisionListenerUseCredential(decisionListener, 0);
1669         return;
1670     }
1671     WKRetainPtr<WKStringRef> username(AdoptWK, WKStringCreateWithUTF8CString(m_authenticationUsername.utf8().data()));
1672     WKRetainPtr<WKStringRef> password(AdoptWK, WKStringCreateWithUTF8CString(m_authenticationPassword.utf8().data()));
1673     WKRetainPtr<WKCredentialRef> credential(AdoptWK, WKCredentialCreate(username.get(), password.get(), kWKCredentialPersistenceForSession));
1674     WKAuthenticationDecisionListenerUseCredential(decisionListener, credential.get());
1675 }
1676
1677     
1678 // WKContextDownloadClient
1679
1680 void TestController::downloadDidStart(WKContextRef context, WKDownloadRef download, const void* clientInfo)
1681 {
1682     static_cast<TestController*>(const_cast<void*>(clientInfo))->downloadDidStart(context, download);
1683 }
1684     
1685 WKStringRef TestController::decideDestinationWithSuggestedFilename(WKContextRef context, WKDownloadRef download, WKStringRef filename, bool* allowOverwrite, const void* clientInfo)
1686 {
1687     return static_cast<TestController*>(const_cast<void*>(clientInfo))->decideDestinationWithSuggestedFilename(context, download, filename, allowOverwrite);
1688 }
1689
1690 void TestController::downloadDidFinish(WKContextRef context, WKDownloadRef download, const void* clientInfo)
1691 {
1692     static_cast<TestController*>(const_cast<void*>(clientInfo))->downloadDidFinish(context, download);
1693 }
1694
1695 void TestController::downloadDidFail(WKContextRef context, WKDownloadRef download, WKErrorRef error, const void* clientInfo)
1696 {
1697     static_cast<TestController*>(const_cast<void*>(clientInfo))->downloadDidFail(context, download, error);
1698 }
1699
1700 void TestController::downloadDidCancel(WKContextRef context, WKDownloadRef download, const void* clientInfo)
1701 {
1702     static_cast<TestController*>(const_cast<void*>(clientInfo))->downloadDidCancel(context, download);
1703 }
1704
1705 void TestController::downloadDidStart(WKContextRef context, WKDownloadRef download)
1706 {
1707     m_currentInvocation->outputText("Download started.\n");
1708 }
1709
1710 WKStringRef TestController::decideDestinationWithSuggestedFilename(WKContextRef, WKDownloadRef, WKStringRef filename, bool*& allowOverwrite)
1711 {
1712     String suggestedFilename = toWTFString(filename);
1713
1714     StringBuilder builder;
1715     builder.append("Downloading URL with suggested filename \"");
1716     builder.append(suggestedFilename);
1717     builder.append("\"\n");
1718
1719     m_currentInvocation->outputText(builder.toString());
1720
1721     const char* dumpRenderTreeTemp = libraryPathForTesting();
1722     if (!dumpRenderTreeTemp)
1723         return nullptr;
1724
1725     *allowOverwrite = true;
1726     String temporaryFolder = String::fromUTF8(dumpRenderTreeTemp);
1727     if (suggestedFilename.isEmpty())
1728         suggestedFilename = "Unknown";
1729
1730     return toWK(temporaryFolder + "/" + suggestedFilename).leakRef();
1731 }
1732
1733 void TestController::downloadDidFinish(WKContextRef, WKDownloadRef)
1734 {
1735     m_currentInvocation->outputText("Download completed.\n");
1736     m_currentInvocation->notifyDownloadDone();
1737 }
1738
1739 void TestController::downloadDidFail(WKContextRef, WKDownloadRef, WKErrorRef error)
1740 {
1741     String message = String::format("Download failed.\n");
1742     m_currentInvocation->outputText(message);
1743     
1744     WKRetainPtr<WKStringRef> errorDomain = adoptWK(WKErrorCopyDomain(error));
1745     WKRetainPtr<WKStringRef> errorDescription = adoptWK(WKErrorCopyLocalizedDescription(error));
1746     int errorCode = WKErrorGetErrorCode(error);
1747
1748     StringBuilder errorBuilder;
1749     errorBuilder.append("Failed: ");
1750     errorBuilder.append(toWTFString(errorDomain));
1751     errorBuilder.append(", code=");
1752     errorBuilder.appendNumber(errorCode);
1753     errorBuilder.append(", description=");
1754     errorBuilder.append(toWTFString(errorDescription));
1755     errorBuilder.append("\n");
1756
1757     m_currentInvocation->outputText(errorBuilder.toString());
1758     m_currentInvocation->notifyDownloadDone();
1759 }
1760
1761 void TestController::downloadDidCancel(WKContextRef, WKDownloadRef)
1762 {
1763     m_currentInvocation->outputText("Download cancelled.\n");
1764     m_currentInvocation->notifyDownloadDone();
1765 }
1766
1767 void TestController::processDidCrash()
1768 {
1769     // This function can be called multiple times when crash logs are being saved on Windows, so
1770     // ensure we only print the crashed message once.
1771     if (!m_didPrintWebProcessCrashedMessage) {
1772         pid_t pid = WKPageGetProcessIdentifier(m_mainWebView->page());
1773         fprintf(stderr, "#CRASHED - %s (pid %ld)\n", webProcessName(), static_cast<long>(pid));
1774         fflush(stderr);
1775         m_didPrintWebProcessCrashedMessage = true;
1776     }
1777
1778     if (m_shouldExitWhenWebProcessCrashes)
1779         exit(1);
1780 }
1781
1782 void TestController::didBeginNavigationGesture(WKPageRef)
1783 {
1784     m_currentInvocation->didBeginSwipe();
1785 }
1786
1787 void TestController::willEndNavigationGesture(WKPageRef, WKBackForwardListItemRef)
1788 {
1789     m_currentInvocation->willEndSwipe();
1790 }
1791
1792 void TestController::didEndNavigationGesture(WKPageRef, WKBackForwardListItemRef)
1793 {
1794     m_currentInvocation->didEndSwipe();
1795 }
1796
1797 void TestController::didRemoveNavigationGestureSnapshot(WKPageRef)
1798 {
1799     m_currentInvocation->didRemoveSwipeSnapshot();
1800 }
1801
1802 void TestController::simulateWebNotificationClick(uint64_t notificationID)
1803 {
1804     m_webNotificationProvider.simulateWebNotificationClick(mainWebView()->page(), notificationID);
1805 }
1806
1807 void TestController::setGeolocationPermission(bool enabled)
1808 {
1809     m_isGeolocationPermissionSet = true;
1810     m_isGeolocationPermissionAllowed = enabled;
1811     decidePolicyForGeolocationPermissionRequestIfPossible();
1812 }
1813
1814 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)
1815 {
1816     m_geolocationProvider->setPosition(latitude, longitude, accuracy, providesAltitude, altitude, providesAltitudeAccuracy, altitudeAccuracy, providesHeading, heading, providesSpeed, speed);
1817 }
1818
1819 void TestController::setMockGeolocationPositionUnavailableError(WKStringRef errorMessage)
1820 {
1821     m_geolocationProvider->setPositionUnavailableError(errorMessage);
1822 }
1823
1824 void TestController::handleGeolocationPermissionRequest(WKGeolocationPermissionRequestRef geolocationPermissionRequest)
1825 {
1826     m_geolocationPermissionRequests.append(geolocationPermissionRequest);
1827     decidePolicyForGeolocationPermissionRequestIfPossible();
1828 }
1829
1830 bool TestController::isGeolocationProviderActive() const
1831 {
1832     return m_geolocationProvider->isActive();
1833 }
1834
1835 static String originUserVisibleName(WKSecurityOriginRef origin)
1836 {
1837     if (!origin)
1838         return emptyString();
1839
1840     std::string host = toSTD(adoptWK(WKSecurityOriginCopyHost(origin))).c_str();
1841     std::string protocol = toSTD(adoptWK(WKSecurityOriginCopyProtocol(origin))).c_str();
1842
1843     if (!host.length() || !protocol.length())
1844         return emptyString();
1845
1846     unsigned short port = WKSecurityOriginGetPort(origin);
1847     if (port)
1848         return String::format("%s://%s:%d", protocol.c_str(), host.c_str(), port);
1849
1850     return String::format("%s://%s", protocol.c_str(), host.c_str());
1851 }
1852
1853 static String userMediaOriginHash(WKSecurityOriginRef userMediaDocumentOrigin, WKSecurityOriginRef topLevelDocumentOrigin)
1854 {
1855     String userMediaDocumentOriginString = originUserVisibleName(userMediaDocumentOrigin);
1856     String topLevelDocumentOriginString = originUserVisibleName(topLevelDocumentOrigin);
1857
1858     if (topLevelDocumentOriginString.isEmpty())
1859         return userMediaDocumentOriginString;
1860
1861     return String::format("%s-%s", userMediaDocumentOriginString.utf8().data(), topLevelDocumentOriginString.utf8().data());
1862 }
1863
1864 static String userMediaOriginHash(WKStringRef userMediaDocumentOriginString, WKStringRef topLevelDocumentOriginString)
1865 {
1866     auto userMediaDocumentOrigin = adoptWK(WKSecurityOriginCreateFromString(userMediaDocumentOriginString));
1867     if (!WKStringGetLength(topLevelDocumentOriginString))
1868         return userMediaOriginHash(userMediaDocumentOrigin.get(), nullptr);
1869
1870     auto topLevelDocumentOrigin = adoptWK(WKSecurityOriginCreateFromString(topLevelDocumentOriginString));
1871     return userMediaOriginHash(userMediaDocumentOrigin.get(), topLevelDocumentOrigin.get());
1872 }
1873
1874 void TestController::setUserMediaPermission(bool enabled)
1875 {
1876     m_isUserMediaPermissionSet = true;
1877     m_isUserMediaPermissionAllowed = enabled;
1878     decidePolicyForUserMediaPermissionRequestIfPossible();
1879 }
1880
1881 static String createCanonicalUUIDString()
1882 {
1883     unsigned randomData[4];
1884     cryptographicallyRandomValues(reinterpret_cast<unsigned char*>(randomData), sizeof(randomData));
1885
1886     // Format as Version 4 UUID.
1887     StringBuilder builder;
1888     builder.reserveCapacity(36);
1889     appendUnsignedAsHexFixedSize(randomData[0], builder, 8, Lowercase);
1890     builder.append('-');
1891     appendUnsignedAsHexFixedSize(randomData[1] >> 16, builder, 4, Lowercase);
1892     builder.appendLiteral("-4");
1893     appendUnsignedAsHexFixedSize(randomData[1] & 0x00000fff, builder, 3, Lowercase);
1894     builder.append('-');
1895     appendUnsignedAsHexFixedSize((randomData[2] >> 30) | 0x8, builder, 1, Lowercase);
1896     appendUnsignedAsHexFixedSize((randomData[2] >> 16) & 0x00000fff, builder, 3, Lowercase);
1897     builder.append('-');
1898     appendUnsignedAsHexFixedSize(randomData[2] & 0x0000ffff, builder, 4, Lowercase);
1899     appendUnsignedAsHexFixedSize(randomData[3], builder, 8, Lowercase);
1900     return builder.toString();
1901 }
1902
1903 class OriginSettings : public RefCounted<OriginSettings> {
1904 public:
1905     explicit OriginSettings()
1906     {
1907     }
1908
1909     bool persistentPermission() const { return m_persistentPermission; }
1910     void setPersistentPermission(bool permission) { m_persistentPermission = permission; }
1911
1912     String persistentSalt() const { return m_persistentSalt; }
1913     void setPersistentSalt(const String& salt) { m_persistentSalt = salt; }
1914
1915     HashMap<uint64_t, String>& ephemeralSalts() { return m_ephemeralSalts; }
1916
1917     void incrementRequestCount() { ++m_requestCount; }
1918     void resetRequestCount() { m_requestCount = 0; }
1919     unsigned requestCount() const { return m_requestCount; }
1920
1921 private:
1922     HashMap<uint64_t, String> m_ephemeralSalts;
1923     String m_persistentSalt;
1924     unsigned m_requestCount { 0 };
1925     bool m_persistentPermission { false };
1926 };
1927
1928 String TestController::saltForOrigin(WKFrameRef frame, String originHash)
1929 {
1930     auto& settings = settingsForOrigin(originHash);
1931     auto& ephemeralSalts = settings.ephemeralSalts();
1932     auto frameInfo = adoptWK(WKFrameCreateFrameInfo(frame));
1933     auto frameHandle = WKFrameInfoGetFrameHandleRef(frameInfo.get());
1934     uint64_t frameIdentifier = WKFrameHandleGetFrameID(frameHandle);
1935     String frameSalt = ephemeralSalts.get(frameIdentifier);
1936
1937     if (settings.persistentPermission()) {
1938         if (frameSalt.length())
1939             return frameSalt;
1940
1941         if (!settings.persistentSalt().length())
1942             settings.setPersistentSalt(createCanonicalUUIDString());
1943
1944         return settings.persistentSalt();
1945     }
1946
1947     if (!frameSalt.length()) {
1948         frameSalt = createCanonicalUUIDString();
1949         ephemeralSalts.add(frameIdentifier, frameSalt);
1950     }
1951
1952     return frameSalt;
1953 }
1954
1955 void TestController::setUserMediaPersistentPermissionForOrigin(bool permission, WKStringRef userMediaDocumentOriginString, WKStringRef topLevelDocumentOriginString)
1956 {
1957     auto originHash = userMediaOriginHash(userMediaDocumentOriginString, topLevelDocumentOriginString);
1958     auto& settings = settingsForOrigin(originHash);
1959     settings.setPersistentPermission(permission);
1960 }
1961
1962 void TestController::handleCheckOfUserMediaPermissionForOrigin(WKFrameRef frame, WKSecurityOriginRef userMediaDocumentOrigin, WKSecurityOriginRef topLevelDocumentOrigin, const WKUserMediaPermissionCheckRef& checkRequest)
1963 {
1964     auto originHash = userMediaOriginHash(userMediaDocumentOrigin, topLevelDocumentOrigin);
1965     auto salt = saltForOrigin(frame, originHash);
1966     WKRetainPtr<WKStringRef> saltString = adoptWK(WKStringCreateWithUTF8CString(salt.utf8().data()));
1967
1968     WKUserMediaPermissionCheckSetUserMediaAccessInfo(checkRequest, saltString.get(), settingsForOrigin(originHash).persistentPermission());
1969 }
1970
1971 void TestController::handleUserMediaPermissionRequest(WKFrameRef frame, WKSecurityOriginRef userMediaDocumentOrigin, WKSecurityOriginRef topLevelDocumentOrigin, WKUserMediaPermissionRequestRef request)
1972 {
1973     auto originHash = userMediaOriginHash(userMediaDocumentOrigin, topLevelDocumentOrigin);
1974     m_userMediaPermissionRequests.append(std::make_pair(originHash, request));
1975     decidePolicyForUserMediaPermissionRequestIfPossible();
1976 }
1977
1978 OriginSettings& TestController::settingsForOrigin(const String& originHash)
1979 {
1980     RefPtr<OriginSettings> settings = m_cachedUserMediaPermissions.get(originHash);
1981     if (!settings) {
1982         settings = adoptRef(*new OriginSettings());
1983         m_cachedUserMediaPermissions.add(originHash, settings);
1984     }
1985
1986     return *settings;
1987 }
1988
1989 unsigned TestController::userMediaPermissionRequestCountForOrigin(WKStringRef userMediaDocumentOriginString, WKStringRef topLevelDocumentOriginString)
1990 {
1991     auto originHash = userMediaOriginHash(userMediaDocumentOriginString, topLevelDocumentOriginString);
1992     return settingsForOrigin(originHash).requestCount();
1993 }
1994
1995 void TestController::resetUserMediaPermissionRequestCountForOrigin(WKStringRef userMediaDocumentOriginString, WKStringRef topLevelDocumentOriginString)
1996 {
1997     auto originHash = userMediaOriginHash(userMediaDocumentOriginString, topLevelDocumentOriginString);
1998     settingsForOrigin(originHash).resetRequestCount();
1999 }
2000
2001 void TestController::decidePolicyForUserMediaPermissionRequestIfPossible()
2002 {
2003     if (!m_isUserMediaPermissionSet)
2004         return;
2005
2006     for (auto& pair : m_userMediaPermissionRequests) {
2007         auto originHash = pair.first;
2008         auto request = pair.second.get();
2009
2010         auto& settings = settingsForOrigin(originHash);
2011         settings.incrementRequestCount();
2012
2013         if (!m_isUserMediaPermissionAllowed && !settings.persistentPermission()) {
2014             WKUserMediaPermissionRequestDeny(request, kWKPermissionDenied);
2015             continue;
2016         }
2017
2018         WKRetainPtr<WKArrayRef> audioDeviceUIDs = adoptWK(WKUserMediaPermissionRequestAudioDeviceUIDs(request));
2019         WKRetainPtr<WKArrayRef> videoDeviceUIDs = adoptWK(WKUserMediaPermissionRequestVideoDeviceUIDs(request));
2020
2021         if (!WKArrayGetSize(videoDeviceUIDs.get()) && !WKArrayGetSize(audioDeviceUIDs.get())) {
2022             WKUserMediaPermissionRequestDeny(request, kWKNoConstraints);
2023             continue;
2024         }
2025
2026         WKRetainPtr<WKStringRef> videoDeviceUID;
2027         if (WKArrayGetSize(videoDeviceUIDs.get()))
2028             videoDeviceUID = reinterpret_cast<WKStringRef>(WKArrayGetItemAtIndex(videoDeviceUIDs.get(), 0));
2029         else
2030             videoDeviceUID = adoptWK(WKStringCreateWithUTF8CString(""));
2031
2032         WKRetainPtr<WKStringRef> audioDeviceUID;
2033         if (WKArrayGetSize(audioDeviceUIDs.get()))
2034             audioDeviceUID = reinterpret_cast<WKStringRef>(WKArrayGetItemAtIndex(audioDeviceUIDs.get(), 0));
2035         else
2036             audioDeviceUID = adoptWK(WKStringCreateWithUTF8CString(""));
2037
2038         WKUserMediaPermissionRequestAllow(request, audioDeviceUID.get(), videoDeviceUID.get());
2039     }
2040     m_userMediaPermissionRequests.clear();
2041 }
2042
2043 void TestController::setCustomPolicyDelegate(bool enabled, bool permissive)
2044 {
2045     m_policyDelegateEnabled = enabled;
2046     m_policyDelegatePermissive = permissive;
2047 }
2048
2049 void TestController::decidePolicyForGeolocationPermissionRequestIfPossible()
2050 {
2051     if (!m_isGeolocationPermissionSet)
2052         return;
2053
2054     for (size_t i = 0; i < m_geolocationPermissionRequests.size(); ++i) {
2055         WKGeolocationPermissionRequestRef permissionRequest = m_geolocationPermissionRequests[i].get();
2056         if (m_isGeolocationPermissionAllowed)
2057             WKGeolocationPermissionRequestAllow(permissionRequest);
2058         else
2059             WKGeolocationPermissionRequestDeny(permissionRequest);
2060     }
2061     m_geolocationPermissionRequests.clear();
2062 }
2063
2064 void TestController::decidePolicyForNotificationPermissionRequest(WKPageRef page, WKSecurityOriginRef origin, WKNotificationPermissionRequestRef request, const void*)
2065 {
2066     TestController::singleton().decidePolicyForNotificationPermissionRequest(page, origin, request);
2067 }
2068
2069 void TestController::decidePolicyForNotificationPermissionRequest(WKPageRef, WKSecurityOriginRef, WKNotificationPermissionRequestRef request)
2070 {
2071     WKNotificationPermissionRequestAllow(request);
2072 }
2073
2074 void TestController::unavailablePluginButtonClicked(WKPageRef, WKPluginUnavailabilityReason, WKDictionaryRef, const void*)
2075 {
2076     printf("MISSING PLUGIN BUTTON PRESSED\n");
2077 }
2078
2079 void TestController::decidePolicyForNavigationAction(WKPageRef, WKNavigationActionRef navigationAction, WKFramePolicyListenerRef listener, WKTypeRef, const void* clientInfo)
2080 {
2081     static_cast<TestController*>(const_cast<void*>(clientInfo))->decidePolicyForNavigationAction(listener);
2082 }
2083
2084 void TestController::decidePolicyForNavigationAction(WKFramePolicyListenerRef listener)
2085 {
2086     WKRetainPtr<WKFramePolicyListenerRef> retainedListener { listener };
2087     const bool shouldIgnore { m_policyDelegateEnabled && !m_policyDelegatePermissive };
2088     auto decisionFunction = [shouldIgnore, retainedListener]() {
2089         if (shouldIgnore)
2090             WKFramePolicyListenerIgnore(retainedListener.get());
2091         else
2092             WKFramePolicyListenerUse(retainedListener.get());
2093     };
2094
2095     if (m_shouldDecideNavigationPolicyAfterDelay)
2096         RunLoop::main().dispatch(WTFMove(decisionFunction));
2097     else
2098         decisionFunction();
2099 }
2100
2101 void TestController::decidePolicyForNavigationResponse(WKPageRef, WKNavigationResponseRef navigationResponse, WKFramePolicyListenerRef listener, WKTypeRef, const void* clientInfo)
2102 {
2103     static_cast<TestController*>(const_cast<void*>(clientInfo))->decidePolicyForNavigationResponse(navigationResponse, listener);
2104 }
2105
2106 void TestController::decidePolicyForNavigationResponse(WKNavigationResponseRef navigationResponse, WKFramePolicyListenerRef listener)
2107 {
2108     // Even though Response was already checked by WKBundlePagePolicyClient, the check did not include plugins
2109     // so we have to re-check again.
2110     if (WKNavigationResponseCanShowMIMEType(navigationResponse)) {
2111         WKFramePolicyListenerUse(listener);
2112         return;
2113     }
2114
2115     if (m_shouldDownloadUndisplayableMIMETypes)
2116         WKFramePolicyListenerDownload(listener);
2117     else
2118         WKFramePolicyListenerIgnore(listener);
2119 }
2120
2121 void TestController::didNavigateWithNavigationData(WKContextRef, WKPageRef, WKNavigationDataRef navigationData, WKFrameRef frame, const void* clientInfo)
2122 {
2123     static_cast<TestController*>(const_cast<void*>(clientInfo))->didNavigateWithNavigationData(navigationData, frame);
2124 }
2125
2126 void TestController::didNavigateWithNavigationData(WKNavigationDataRef navigationData, WKFrameRef)
2127 {
2128     if (m_state != RunningTest)
2129         return;
2130
2131     if (!m_shouldLogHistoryClientCallbacks)
2132         return;
2133
2134     // URL
2135     WKRetainPtr<WKURLRef> urlWK = adoptWK(WKNavigationDataCopyURL(navigationData));
2136     WKRetainPtr<WKStringRef> urlStringWK = adoptWK(WKURLCopyString(urlWK.get()));
2137     // Title
2138     WKRetainPtr<WKStringRef> titleWK = adoptWK(WKNavigationDataCopyTitle(navigationData));
2139     // HTTP method
2140     WKRetainPtr<WKURLRequestRef> requestWK = adoptWK(WKNavigationDataCopyOriginalRequest(navigationData));
2141     WKRetainPtr<WKStringRef> methodWK = adoptWK(WKURLRequestCopyHTTPMethod(requestWK.get()));
2142
2143     // FIXME: Determine whether the navigation was successful / a client redirect rather than hard-coding the message here.
2144     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",
2145         toSTD(urlStringWK).c_str(), toSTD(titleWK).c_str(), toSTD(methodWK).c_str()));
2146 }
2147
2148 void TestController::didPerformClientRedirect(WKContextRef, WKPageRef, WKURLRef sourceURL, WKURLRef destinationURL, WKFrameRef frame, const void* clientInfo)
2149 {
2150     static_cast<TestController*>(const_cast<void*>(clientInfo))->didPerformClientRedirect(sourceURL, destinationURL, frame);
2151 }
2152
2153 void TestController::didPerformClientRedirect(WKURLRef sourceURL, WKURLRef destinationURL, WKFrameRef)
2154 {
2155     if (m_state != RunningTest)
2156         return;
2157
2158     if (!m_shouldLogHistoryClientCallbacks)
2159         return;
2160
2161     WKRetainPtr<WKStringRef> sourceStringWK = adoptWK(WKURLCopyString(sourceURL));
2162     WKRetainPtr<WKStringRef> destinationStringWK = adoptWK(WKURLCopyString(destinationURL));
2163
2164     m_currentInvocation->outputText(String::format("WebView performed a client redirect from \"%s\" to \"%s\".\n", toSTD(sourceStringWK).c_str(), toSTD(destinationStringWK).c_str()));
2165 }
2166
2167 void TestController::didPerformServerRedirect(WKContextRef, WKPageRef, WKURLRef sourceURL, WKURLRef destinationURL, WKFrameRef frame, const void* clientInfo)
2168 {
2169     static_cast<TestController*>(const_cast<void*>(clientInfo))->didPerformServerRedirect(sourceURL, destinationURL, frame);
2170 }
2171
2172 void TestController::didPerformServerRedirect(WKURLRef sourceURL, WKURLRef destinationURL, WKFrameRef)
2173 {
2174     if (m_state != RunningTest)
2175         return;
2176
2177     if (!m_shouldLogHistoryClientCallbacks)
2178         return;
2179
2180     WKRetainPtr<WKStringRef> sourceStringWK = adoptWK(WKURLCopyString(sourceURL));
2181     WKRetainPtr<WKStringRef> destinationStringWK = adoptWK(WKURLCopyString(destinationURL));
2182
2183     m_currentInvocation->outputText(String::format("WebView performed a server redirect from \"%s\" to \"%s\".\n", toSTD(sourceStringWK).c_str(), toSTD(destinationStringWK).c_str()));
2184 }
2185
2186 void TestController::didUpdateHistoryTitle(WKContextRef, WKPageRef, WKStringRef title, WKURLRef URL, WKFrameRef frame, const void* clientInfo)
2187 {
2188     static_cast<TestController*>(const_cast<void*>(clientInfo))->didUpdateHistoryTitle(title, URL, frame);
2189 }
2190
2191 void TestController::didUpdateHistoryTitle(WKStringRef title, WKURLRef URL, WKFrameRef)
2192 {
2193     if (m_state != RunningTest)
2194         return;
2195
2196     if (!m_shouldLogHistoryClientCallbacks)
2197         return;
2198
2199     WKRetainPtr<WKStringRef> urlStringWK(AdoptWK, WKURLCopyString(URL));
2200     m_currentInvocation->outputText(String::format("WebView updated the title for history URL \"%s\" to \"%s\".\n", toSTD(urlStringWK).c_str(), toSTD(title).c_str()));
2201 }
2202
2203 void TestController::setNavigationGesturesEnabled(bool value)
2204 {
2205     m_mainWebView->setNavigationGesturesEnabled(value);
2206 }
2207
2208 void TestController::setIgnoresViewportScaleLimits(bool ignoresViewportScaleLimits)
2209 {
2210     WKPageSetIgnoresViewportScaleLimits(m_mainWebView->page(), ignoresViewportScaleLimits);
2211 }
2212
2213 void TestController::setStatisticsPrevalentResource(WKStringRef hostName, bool value)
2214 {
2215     WKResourceLoadStatisticsManagerSetPrevalentResource(hostName, value);
2216 }
2217
2218 bool TestController::isStatisticsPrevalentResource(WKStringRef hostName)
2219 {
2220     return WKResourceLoadStatisticsManagerIsPrevalentResource(hostName);
2221 }
2222
2223 void TestController::setStatisticsHasHadUserInteraction(WKStringRef hostName, bool value)
2224 {
2225     WKResourceLoadStatisticsManagerSetHasHadUserInteraction(hostName, value);
2226 }
2227
2228 bool TestController::isStatisticsHasHadUserInteraction(WKStringRef hostName)
2229 {
2230     return WKResourceLoadStatisticsManagerIsHasHadUserInteraction(hostName);
2231 }
2232
2233 void TestController::setStatisticsTimeToLiveUserInteraction(double seconds)
2234 {
2235     WKResourceLoadStatisticsManagerSetTimeToLiveUserInteraction(seconds);
2236 }
2237
2238 void TestController::statisticsFireDataModificationHandler()
2239 {
2240     WKResourceLoadStatisticsManagerFireDataModificationHandler();
2241 }
2242     
2243 void TestController::setStatisticsNotifyPagesWhenDataRecordsWereScanned(bool value)
2244 {
2245     WKResourceLoadStatisticsManagerSetNotifyPagesWhenDataRecordsWereScanned(value);
2246 }
2247     
2248 void TestController::setStatisticsShouldClassifyResourcesBeforeDataRecordsRemoval(bool value)
2249 {
2250     WKResourceLoadStatisticsManagerSetShouldClassifyResourcesBeforeDataRecordsRemoval(value);
2251 }
2252
2253 void TestController::setStatisticsMinimumTimeBetweeenDataRecordsRemoval(double seconds)
2254 {
2255     WKResourceLoadStatisticsManagerSetMinimumTimeBetweeenDataRecordsRemoval(seconds);
2256 }
2257 void TestController::statisticsResetToConsistentState()
2258 {
2259     WKResourceLoadStatisticsManagerResetToConsistentState();
2260 }
2261     
2262 #if !PLATFORM(COCOA)
2263 void TestController::platformWillRunTest(const TestInvocation&)
2264 {
2265 }
2266
2267 void TestController::platformCreateWebView(WKPageConfigurationRef configuration, const TestOptions& options)
2268 {
2269     m_mainWebView = std::make_unique<PlatformWebView>(configuration, options);
2270 }
2271
2272 PlatformWebView* TestController::platformCreateOtherPage(PlatformWebView* parentView, WKPageConfigurationRef configuration, const TestOptions& options)
2273 {
2274     return new PlatformWebView(configuration, options);
2275 }
2276
2277 WKContextRef TestController::platformAdjustContext(WKContextRef context, WKContextConfigurationRef contextConfiguration)
2278 {
2279     return context;
2280 }
2281
2282 void TestController::platformResetStateToConsistentValues()
2283 {
2284
2285 }
2286
2287 unsigned TestController::imageCountInGeneralPasteboard() const
2288 {
2289     return 0;
2290 }
2291
2292 #endif
2293
2294 } // namespace WTR