[Qt][WK2] Convert touch-point area
[WebKit-https.git] / Tools / WebKitTestRunner / TestController.cpp
1 /*
2  * Copyright (C) 2010 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 "PlatformWebView.h"
30 #include "StringFunctions.h"
31 #include "TestInvocation.h"
32 #include <WebKit2/WKContextPrivate.h>
33 #include <WebKit2/WKNumber.h>
34 #include <WebKit2/WKPageGroup.h>
35 #include <WebKit2/WKPagePrivate.h>
36 #include <WebKit2/WKPreferencesPrivate.h>
37 #include <WebKit2/WKRetainPtr.h>
38 #include <cstdio>
39 #include <wtf/PassOwnPtr.h>
40
41 #if PLATFORM(MAC)
42 #include <WebKit2/WKPagePrivateMac.h>
43 #endif
44
45 #if PLATFORM(MAC) || PLATFORM(QT) || PLATFORM(GTK)
46 #include "EventSenderProxy.h"
47 #endif
48
49 namespace WTR {
50
51 static const double defaultLongTimeout = 30;
52 static const double defaultShortTimeout = 5;
53 static const double defaultNoTimeout = -1;
54
55 static WKURLRef blankURL()
56 {
57     static WKURLRef staticBlankURL = WKURLCreateWithUTF8CString("about:blank");
58     return staticBlankURL;
59 }
60
61 static TestController* controller;
62
63 TestController& TestController::shared()
64 {
65     ASSERT(controller);
66     return *controller;
67 }
68
69 TestController::TestController(int argc, const char* argv[])
70     : m_dumpPixels(false)
71     , m_verbose(false)
72     , m_printSeparators(false)
73     , m_usingServerMode(false)
74     , m_gcBetweenTests(false)
75     , m_state(Initial)
76     , m_doneResetting(false)
77     , m_longTimeout(defaultLongTimeout)
78     , m_shortTimeout(defaultShortTimeout)
79     , m_noTimeout(defaultNoTimeout)
80     , m_useWaitToDumpWatchdogTimer(true)
81     , m_didPrintWebProcessCrashedMessage(false)
82     , m_shouldExitWhenWebProcessCrashes(true)
83     , m_beforeUnloadReturnValue(true)
84 #if PLATFORM(MAC) || PLATFORM(QT) || PLATFORM(GTK)
85     , m_eventSenderProxy(new EventSenderProxy(this))
86 #endif
87 {
88     initialize(argc, argv);
89     controller = this;
90     run();
91     controller = 0;
92 }
93
94 TestController::~TestController()
95 {
96 }
97
98 static WKRect getWindowFrameMainPage(WKPageRef page, const void* clientInfo)
99 {
100     PlatformWebView* view = static_cast<TestController*>(const_cast<void*>(clientInfo))->mainWebView();
101     return view->windowFrame();
102 }
103
104 static void setWindowFrameMainPage(WKPageRef page, WKRect frame, const void* clientInfo)
105 {
106     PlatformWebView* view = static_cast<TestController*>(const_cast<void*>(clientInfo))->mainWebView();
107     view->setWindowFrame(frame);
108 }
109
110 static WKRect getWindowFrameOtherPage(WKPageRef page, const void* clientInfo)
111 {
112     PlatformWebView* view = static_cast<PlatformWebView*>(const_cast<void*>(clientInfo));
113     return view->windowFrame();
114 }
115
116 static void setWindowFrameOtherPage(WKPageRef page, WKRect frame, const void* clientInfo)
117 {
118     PlatformWebView* view = static_cast<PlatformWebView*>(const_cast<void*>(clientInfo));
119     view->setWindowFrame(frame);
120 }
121
122 static bool runBeforeUnloadConfirmPanel(WKPageRef page, WKStringRef message, WKFrameRef frame, const void *clientInfo)
123 {
124     TestController* testController = static_cast<TestController*>(const_cast<void*>(clientInfo));
125     printf("CONFIRM NAVIGATION: %s\n", toSTD(message).c_str());
126     return testController->beforeUnloadReturnValue();
127 }
128
129 static unsigned long long exceededDatabaseQuota(WKPageRef, WKFrameRef, WKSecurityOriginRef, WKStringRef, WKStringRef, unsigned long long, unsigned long long, unsigned long long, unsigned long long, const void*)
130 {
131     static const unsigned long long defaultQuota = 5 * 1024 * 1024;
132     return defaultQuota;
133 }
134
135
136 void TestController::runModal(WKPageRef page, const void* clientInfo)
137 {
138     PlatformWebView* view = static_cast<PlatformWebView*>(const_cast<void*>(clientInfo));
139     view->setWindowIsKey(false);
140     runModal(view);
141     view->setWindowIsKey(true);
142 }
143
144 static void closeOtherPage(WKPageRef page, const void* clientInfo)
145 {
146     WKPageClose(page);
147     PlatformWebView* view = static_cast<PlatformWebView*>(const_cast<void*>(clientInfo));
148     delete view;
149 }
150
151 static void focus(WKPageRef page, const void* clientInfo)
152 {
153     PlatformWebView* view = static_cast<PlatformWebView*>(const_cast<void*>(clientInfo));
154     view->setWindowIsKey(true);
155 }
156
157 static void unfocus(WKPageRef page, const void* clientInfo)
158 {
159     PlatformWebView* view = static_cast<PlatformWebView*>(const_cast<void*>(clientInfo));
160     view->setWindowIsKey(false);
161 }
162
163 WKPageRef TestController::createOtherPage(WKPageRef oldPage, WKURLRequestRef, WKDictionaryRef, WKEventModifiers, WKEventMouseButton, const void*)
164 {
165     PlatformWebView* view = new PlatformWebView(WKPageGetContext(oldPage), WKPageGetPageGroup(oldPage));
166     WKPageRef newPage = view->page();
167
168     view->resizeTo(800, 600);
169
170     WKPageUIClient otherPageUIClient = {
171         kWKPageUIClientCurrentVersion,
172         view,
173         0, // createNewPage_deprecatedForUseWithV0
174         0, // showPage
175         closeOtherPage,
176         0, // takeFocus
177         focus,
178         unfocus,
179         0, // runJavaScriptAlert
180         0, // runJavaScriptConfirm
181         0, // runJavaScriptPrompt
182         0, // setStatusText
183         0, // mouseDidMoveOverElement_deprecatedForUseWithV0
184         0, // missingPluginButtonClicked
185         0, // didNotHandleKeyEvent
186         0, // didNotHandleWheelEvent
187         0, // toolbarsAreVisible
188         0, // setToolbarsAreVisible
189         0, // menuBarIsVisible
190         0, // setMenuBarIsVisible
191         0, // statusBarIsVisible
192         0, // setStatusBarIsVisible
193         0, // isResizable
194         0, // setIsResizable
195         getWindowFrameOtherPage,
196         setWindowFrameOtherPage,
197         runBeforeUnloadConfirmPanel,
198         0, // didDraw
199         0, // pageDidScroll
200         exceededDatabaseQuota,
201         0, // runOpenPanel
202         0, // decidePolicyForGeolocationPermissionRequest
203         0, // headerHeight
204         0, // footerHeight
205         0, // drawHeader
206         0, // drawFooter
207         0, // printFrame
208         runModal,
209         0, // didCompleteRubberBandForMainFrame
210         0, // saveDataToFileInDownloadsFolder
211         0, // shouldInterruptJavaScript
212         createOtherPage,
213         0, // mouseDidMoveOverElement
214         0, // decidePolicyForNotificationPermissionRequest
215     };
216     WKPageSetPageUIClient(newPage, &otherPageUIClient);
217
218     WKRetain(newPage);
219     return newPage;
220 }
221
222 const char* TestController::libraryPathForTesting()
223 {
224     // FIXME: This may not be sufficient to prevent interactions/crashes
225     // when running more than one copy of DumpRenderTree.
226     // See https://bugs.webkit.org/show_bug.cgi?id=10906
227     char* dumpRenderTreeTemp = getenv("DUMPRENDERTREE_TEMP");
228     if (dumpRenderTreeTemp)
229         return dumpRenderTreeTemp;
230     return platformLibraryPathForTesting();
231 }
232
233
234 void TestController::initialize(int argc, const char* argv[])
235 {
236     platformInitialize();
237
238     if (argc < 2) {
239         fputs("Usage: WebKitTestRunner [options] filename [filename2..n]\n", stderr);
240         // FIXME: Refactor option parsing to allow us to print
241         // an auto-generated list of options.
242         exit(1);
243     }
244
245     bool printSupportedFeatures = false;
246
247     for (int i = 1; i < argc; ++i) {
248         std::string argument(argv[i]);
249
250         if (argument == "--timeout" && i + 1 < argc) {
251             m_longTimeout = atoi(argv[++i]);
252             // Scale up the short timeout to match.
253             m_shortTimeout = defaultShortTimeout * m_longTimeout / defaultLongTimeout;
254             continue;
255         }
256
257         if (argument == "--no-timeout") {
258             m_useWaitToDumpWatchdogTimer = false;
259             continue;
260         }
261
262         if (argument == "--pixel-tests") {
263             m_dumpPixels = true;
264             continue;
265         }
266         if (argument == "--verbose") {
267             m_verbose = true;
268             continue;
269         }
270         if (argument == "--gc-between-tests") {
271             m_gcBetweenTests = true;
272             continue;
273         }
274         if (argument == "--print-supported-features") {
275             printSupportedFeatures = true;
276             break;
277         }
278
279         // Skip any other arguments that begin with '--'.
280         if (argument.length() >= 2 && argument[0] == '-' && argument[1] == '-')
281             continue;
282
283         m_paths.push_back(argument);
284     }
285
286     if (printSupportedFeatures) {
287         // FIXME: On Windows, DumpRenderTree uses this to expose whether it supports 3d
288         // transforms and accelerated compositing. When we support those features, we
289         // should match DRT's behavior.
290         exit(0);
291     }
292
293     m_usingServerMode = (m_paths.size() == 1 && m_paths[0] == "-");
294     if (m_usingServerMode)
295         m_printSeparators = true;
296     else
297         m_printSeparators = m_paths.size() > 1;
298
299     initializeInjectedBundlePath();
300     initializeTestPluginDirectory();
301
302     WKRetainPtr<WKStringRef> pageGroupIdentifier(AdoptWK, WKStringCreateWithUTF8CString("WebKitTestRunnerPageGroup"));
303     m_pageGroup.adopt(WKPageGroupCreateWithIdentifier(pageGroupIdentifier.get()));
304
305     m_context.adopt(WKContextCreateWithInjectedBundlePath(injectedBundlePath()));
306
307     const char* path = libraryPathForTesting();
308     if (path) {
309         Vector<char> databaseDirectory(strlen(path) + strlen("/Databases") + 1);
310         sprintf(databaseDirectory.data(), "%s%s", path, "/Databases");
311         WKRetainPtr<WKStringRef> databaseDirectoryWK(AdoptWK, WKStringCreateWithUTF8CString(databaseDirectory.data()));
312         WKContextSetDatabaseDirectory(m_context.get(), databaseDirectoryWK.get());
313     }
314
315     platformInitializeContext();
316
317     WKContextInjectedBundleClient injectedBundleClient = {
318         kWKContextInjectedBundleClientCurrentVersion,
319         this,
320         didReceiveMessageFromInjectedBundle,
321         didReceiveSynchronousMessageFromInjectedBundle
322     };
323     WKContextSetInjectedBundleClient(m_context.get(), &injectedBundleClient);
324
325     WKContextSetAdditionalPluginsDirectory(m_context.get(), testPluginDirectory());
326
327     m_mainWebView = adoptPtr(new PlatformWebView(m_context.get(), m_pageGroup.get()));
328
329     WKPageUIClient pageUIClient = {
330         kWKPageUIClientCurrentVersion,
331         this,
332         0, // createNewPage_deprecatedForUseWithV0
333         0, // showPage
334         0, // close
335         0, // takeFocus
336         0, // focus
337         0, // unfocus
338         0, // runJavaScriptAlert
339         0, // runJavaScriptConfirm
340         0, // runJavaScriptPrompt
341         0, // setStatusText
342         0, // mouseDidMoveOverElement_deprecatedForUseWithV0
343         0, // missingPluginButtonClicked
344         0, // didNotHandleKeyEvent
345         0, // didNotHandleWheelEvent
346         0, // toolbarsAreVisible
347         0, // setToolbarsAreVisible
348         0, // menuBarIsVisible
349         0, // setMenuBarIsVisible
350         0, // statusBarIsVisible
351         0, // setStatusBarIsVisible
352         0, // isResizable
353         0, // setIsResizable
354         getWindowFrameMainPage,
355         setWindowFrameMainPage,
356         runBeforeUnloadConfirmPanel,
357         0, // didDraw
358         0, // pageDidScroll
359         exceededDatabaseQuota,
360         0, // runOpenPanel
361         0, // decidePolicyForGeolocationPermissionRequest
362         0, // headerHeight
363         0, // footerHeight
364         0, // drawHeader
365         0, // drawFooter
366         0, // printFrame
367         runModal,
368         0, // didCompleteRubberBandForMainFrame
369         0, // saveDataToFileInDownloadsFolder
370         0, // shouldInterruptJavaScript
371         createOtherPage,
372         0, // mouseDidMoveOverElement
373         0, // decidePolicyForNotificationPermissionRequest
374     };
375     WKPageSetPageUIClient(m_mainWebView->page(), &pageUIClient);
376
377     WKPageLoaderClient pageLoaderClient = {
378         kWKPageLoaderClientCurrentVersion,
379         this,
380         0, // didStartProvisionalLoadForFrame
381         0, // didReceiveServerRedirectForProvisionalLoadForFrame
382         0, // didFailProvisionalLoadWithErrorForFrame
383         didCommitLoadForFrame,
384         0, // didFinishDocumentLoadForFrame
385         didFinishLoadForFrame,
386         0, // didFailLoadWithErrorForFrame
387         0, // didSameDocumentNavigationForFrame
388         0, // didReceiveTitleForFrame
389         0, // didFirstLayoutForFrame
390         0, // didFirstVisuallyNonEmptyLayoutForFrame
391         0, // didRemoveFrameFromHierarchy
392         0, // didFailToInitializePlugin
393         0, // didDisplayInsecureContentForFrame
394         0, // canAuthenticateAgainstProtectionSpaceInFrame
395         0, // didReceiveAuthenticationChallengeInFrame
396         0, // didStartProgress
397         0, // didChangeProgress
398         0, // didFinishProgress
399         0, // didBecomeUnresponsive
400         0, // didBecomeResponsive
401         processDidCrash,
402         0, // didChangeBackForwardList
403         0, // shouldGoToBackForwardListItem
404         0, // didRunInsecureContentForFrame
405         0, // didDetectXSSForFrame
406         0, // didNewFirstVisuallyNonEmptyLayout
407         0, // willGoToBackForwardListItem
408         0, // interactionOccurredWhileProcessUnresponsive
409     };
410     WKPageSetPageLoaderClient(m_mainWebView->page(), &pageLoaderClient);
411 }
412
413 bool TestController::resetStateToConsistentValues()
414 {
415     m_state = Resetting;
416
417     m_beforeUnloadReturnValue = true;
418
419     WKRetainPtr<WKStringRef> messageName = adoptWK(WKStringCreateWithUTF8CString("Reset"));
420     WKRetainPtr<WKMutableDictionaryRef> resetMessageBody = adoptWK(WKMutableDictionaryCreate());
421
422     WKRetainPtr<WKStringRef> shouldGCKey = adoptWK(WKStringCreateWithUTF8CString("ShouldGC"));
423     WKRetainPtr<WKBooleanRef> shouldGCValue = adoptWK(WKBooleanCreate(m_gcBetweenTests));
424     WKDictionaryAddItem(resetMessageBody.get(), shouldGCKey.get(), shouldGCValue.get());
425
426     WKContextPostMessageToInjectedBundle(TestController::shared().context(), messageName.get(), resetMessageBody.get());
427
428     WKContextSetShouldUseFontSmoothing(TestController::shared().context(), false);
429
430     WKContextSetCacheModel(TestController::shared().context(), kWKCacheModelDocumentBrowser);
431
432     // FIXME: This function should also ensure that there is only one page open.
433
434     // Reset preferences
435     WKPreferencesRef preferences = WKPageGroupGetPreferences(m_pageGroup.get());
436     WKPreferencesResetTestRunnerOverrides(preferences);
437     WKPreferencesSetOfflineWebApplicationCacheEnabled(preferences, true);
438     WKPreferencesSetFontSmoothingLevel(preferences, kWKFontSmoothingLevelNoSubpixelAntiAliasing);
439     WKPreferencesSetXSSAuditorEnabled(preferences, false);
440     WKPreferencesSetWebAudioEnabled(preferences, true);
441     WKPreferencesSetDeveloperExtrasEnabled(preferences, true);
442     WKPreferencesSetJavaScriptCanOpenWindowsAutomatically(preferences, true);
443     WKPreferencesSetJavaScriptCanAccessClipboard(preferences, true);
444     WKPreferencesSetDOMPasteAllowed(preferences, true);
445     WKPreferencesSetUniversalAccessFromFileURLsAllowed(preferences, true);
446     WKPreferencesSetFileAccessFromFileURLsAllowed(preferences, true);
447 #if ENABLE(FULLSCREEN_API)
448     WKPreferencesSetFullScreenEnabled(preferences, true);
449 #endif
450     WKPreferencesSetPageCacheEnabled(preferences, false);
451
452 // [Qt][WK2]REGRESSION(r104881):It broke hundreds of tests
453 // FIXME: https://bugs.webkit.org/show_bug.cgi?id=76247
454 #if !PLATFORM(QT)
455     WKPreferencesSetMockScrollbarsEnabled(preferences, true);
456 #endif
457
458 #if !PLATFORM(QT)
459     static WKStringRef standardFontFamily = WKStringCreateWithUTF8CString("Times");
460     static WKStringRef cursiveFontFamily = WKStringCreateWithUTF8CString("Apple Chancery");
461     static WKStringRef fantasyFontFamily = WKStringCreateWithUTF8CString("Papyrus");
462     static WKStringRef fixedFontFamily = WKStringCreateWithUTF8CString("Courier");
463     static WKStringRef pictographFontFamily = WKStringCreateWithUTF8CString("Apple Color Emoji");
464     static WKStringRef sansSerifFontFamily = WKStringCreateWithUTF8CString("Helvetica");
465     static WKStringRef serifFontFamily = WKStringCreateWithUTF8CString("Times");
466
467     WKPreferencesSetStandardFontFamily(preferences, standardFontFamily);
468     WKPreferencesSetCursiveFontFamily(preferences, cursiveFontFamily);
469     WKPreferencesSetFantasyFontFamily(preferences, fantasyFontFamily);
470     WKPreferencesSetFixedFontFamily(preferences, fixedFontFamily);
471     WKPreferencesSetPictographFontFamily(preferences, pictographFontFamily);
472     WKPreferencesSetSansSerifFontFamily(preferences, sansSerifFontFamily);
473     WKPreferencesSetSerifFontFamily(preferences, serifFontFamily);
474 #endif
475     WKPreferencesSetInspectorUsesWebKitUserInterface(preferences, true);
476
477     // in the case that a test using the chrome input field failed, be sure to clean up for the next test
478     m_mainWebView->removeChromeInputField();
479     m_mainWebView->focus();
480
481     // Re-set to the default backing scale factor by setting the custom scale factor to 0.
482     WKPageSetCustomBackingScaleFactor(m_mainWebView->page(), 0);
483
484     // Reset main page back to about:blank
485     m_doneResetting = false;
486
487     WKPageLoadURL(m_mainWebView->page(), blankURL());
488     runUntil(m_doneResetting, ShortTimeout);
489     return m_doneResetting;
490 }
491
492 bool TestController::runTest(const char* test)
493 {
494     if (!resetStateToConsistentValues()) {
495 #if PLATFORM(MAC)
496         pid_t pid = WKPageGetProcessIdentifier(m_mainWebView->page());
497         fprintf(stderr, "#CRASHED - WebProcess (pid %ld)\n", static_cast<long>(pid));
498 #else
499         fputs("#CRASHED - WebProcess\n", stderr);
500 #endif
501         fflush(stderr);
502         return false;
503     }
504
505     std::string pathOrURL(test);
506     std::string expectedPixelHash;
507     size_t separatorPos = pathOrURL.find("'");
508     if (separatorPos != std::string::npos) {
509         pathOrURL = std::string(std::string(test), 0, separatorPos);
510         expectedPixelHash = std::string(std::string(test), separatorPos + 1);
511     }
512
513     m_state = RunningTest;
514
515     m_currentInvocation = adoptPtr(new TestInvocation(pathOrURL));
516     if (m_dumpPixels)
517         m_currentInvocation->setIsPixelTest(expectedPixelHash);
518
519     m_currentInvocation->invoke();
520     m_currentInvocation.clear();
521
522     return true;
523 }
524
525 void TestController::runTestingServerLoop()
526 {
527     char filenameBuffer[2048];
528     while (fgets(filenameBuffer, sizeof(filenameBuffer), stdin)) {
529         char* newLineCharacter = strchr(filenameBuffer, '\n');
530         if (newLineCharacter)
531             *newLineCharacter = '\0';
532
533         if (strlen(filenameBuffer) == 0)
534             continue;
535
536         if (!runTest(filenameBuffer))
537             break;
538     }
539 }
540
541 void TestController::run()
542 {
543     if (m_usingServerMode)
544         runTestingServerLoop();
545     else {
546         for (size_t i = 0; i < m_paths.size(); ++i) {
547             if (!runTest(m_paths[i].c_str()))
548                 break;
549         }
550     }
551 }
552
553 void TestController::runUntil(bool& done, TimeoutDuration timeoutDuration)
554 {
555     double timeout;
556     switch (timeoutDuration) {
557     case ShortTimeout:
558         timeout = m_shortTimeout;
559         break;
560     case LongTimeout:
561         timeout = m_longTimeout;
562         break;
563     case NoTimeout:
564     default:
565         timeout = m_noTimeout;
566         break;
567     }
568
569     platformRunUntil(done, timeout);
570 }
571
572 // WKContextInjectedBundleClient
573
574 void TestController::didReceiveMessageFromInjectedBundle(WKContextRef context, WKStringRef messageName, WKTypeRef messageBody, const void* clientInfo)
575 {
576     static_cast<TestController*>(const_cast<void*>(clientInfo))->didReceiveMessageFromInjectedBundle(messageName, messageBody);
577 }
578
579 void TestController::didReceiveSynchronousMessageFromInjectedBundle(WKContextRef context, WKStringRef messageName, WKTypeRef messageBody, WKTypeRef* returnData, const void* clientInfo)
580 {
581     *returnData = static_cast<TestController*>(const_cast<void*>(clientInfo))->didReceiveSynchronousMessageFromInjectedBundle(messageName, messageBody).leakRef();
582 }
583
584 void TestController::didReceiveMessageFromInjectedBundle(WKStringRef messageName, WKTypeRef messageBody)
585 {
586     if (!m_currentInvocation)
587         return;
588     m_currentInvocation->didReceiveMessageFromInjectedBundle(messageName, messageBody);
589 }
590
591 WKRetainPtr<WKTypeRef> TestController::didReceiveSynchronousMessageFromInjectedBundle(WKStringRef messageName, WKTypeRef messageBody)
592 {
593 #if PLATFORM(MAC) || PLATFORM(QT) || PLATFORM(GTK)
594     if (WKStringIsEqualToUTF8CString(messageName, "EventSender")) {
595         ASSERT(WKGetTypeID(messageBody) == WKDictionaryGetTypeID());
596         WKDictionaryRef messageBodyDictionary = static_cast<WKDictionaryRef>(messageBody);
597
598         WKRetainPtr<WKStringRef> subMessageKey(AdoptWK, WKStringCreateWithUTF8CString("SubMessage"));
599         WKStringRef subMessageName = static_cast<WKStringRef>(WKDictionaryGetItemForKey(messageBodyDictionary, subMessageKey.get()));
600
601         if (WKStringIsEqualToUTF8CString(subMessageName, "KeyDown")) {
602             WKRetainPtr<WKStringRef> keyKey = adoptWK(WKStringCreateWithUTF8CString("Key"));
603             WKStringRef key = static_cast<WKStringRef>(WKDictionaryGetItemForKey(messageBodyDictionary, keyKey.get()));
604
605             WKRetainPtr<WKStringRef> modifiersKey = adoptWK(WKStringCreateWithUTF8CString("Modifiers"));
606             WKEventModifiers modifiers = static_cast<WKEventModifiers>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, modifiersKey.get()))));
607
608             WKRetainPtr<WKStringRef> locationKey = adoptWK(WKStringCreateWithUTF8CString("Location"));
609             unsigned location = static_cast<unsigned>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, locationKey.get()))));
610
611             // Forward to WebProcess
612             WKPageSetShouldSendEventsSynchronously(mainWebView()->page(), true);
613             m_eventSenderProxy->keyDown(key, modifiers, location);
614             WKPageSetShouldSendEventsSynchronously(mainWebView()->page(), false);
615             return 0;
616         }
617
618 #if PLATFORM(MAC) || PLATFORM(QT) || PLATFORM(GTK)
619         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseDown") || WKStringIsEqualToUTF8CString(subMessageName, "MouseUp")) {
620             WKRetainPtr<WKStringRef> buttonKey = adoptWK(WKStringCreateWithUTF8CString("Button"));
621             unsigned button = static_cast<unsigned>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, buttonKey.get()))));
622
623             WKRetainPtr<WKStringRef> modifiersKey = adoptWK(WKStringCreateWithUTF8CString("Modifiers"));
624             WKEventModifiers modifiers = static_cast<WKEventModifiers>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, modifiersKey.get()))));
625
626             // Forward to WebProcess
627             WKPageSetShouldSendEventsSynchronously(mainWebView()->page(), true);
628             if (WKStringIsEqualToUTF8CString(subMessageName, "MouseDown"))
629                 m_eventSenderProxy->mouseDown(button, modifiers);
630             else
631                 m_eventSenderProxy->mouseUp(button, modifiers);
632             WKPageSetShouldSendEventsSynchronously(mainWebView()->page(), false);
633             return 0;
634         }
635
636         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseMoveTo")) {
637             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
638             double x = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get())));
639
640             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
641             double y = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get())));
642
643             // Forward to WebProcess
644             WKPageSetShouldSendEventsSynchronously(mainWebView()->page(), true);
645             m_eventSenderProxy->mouseMoveTo(x, y);
646             WKPageSetShouldSendEventsSynchronously(mainWebView()->page(), false);
647             return 0;
648         }
649
650         if (WKStringIsEqualToUTF8CString(subMessageName, "MouseScrollBy")) {
651             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
652             double x = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get())));
653
654             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
655             double y = WKDoubleGetValue(static_cast<WKDoubleRef>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get())));
656
657             // Forward to WebProcess
658             WKPageSetShouldSendEventsSynchronously(mainWebView()->page(), true);
659             m_eventSenderProxy->mouseScrollBy(x, y);
660             WKPageSetShouldSendEventsSynchronously(mainWebView()->page(), false);
661             return 0;
662         }
663
664         if (WKStringIsEqualToUTF8CString(subMessageName, "LeapForward")) {
665             WKRetainPtr<WKStringRef> timeKey = adoptWK(WKStringCreateWithUTF8CString("TimeInMilliseconds"));
666             unsigned time = static_cast<unsigned>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, timeKey.get()))));
667
668             m_eventSenderProxy->leapForward(time);
669             return 0;
670         }
671 #endif
672
673 #if ENABLE(TOUCH_EVENTS)
674         if (WKStringIsEqualToUTF8CString(subMessageName, "AddTouchPoint")) {
675             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
676             int x = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get()))));
677
678             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
679             int y = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get()))));
680
681             m_eventSenderProxy->addTouchPoint(x, y);
682             return 0;
683         }
684
685         if (WKStringIsEqualToUTF8CString(subMessageName, "UpdateTouchPoint")) {
686             WKRetainPtr<WKStringRef> indexKey = adoptWK(WKStringCreateWithUTF8CString("Index"));
687             int index = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, indexKey.get()))));
688
689             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("X"));
690             int x = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get()))));
691
692             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("Y"));
693             int y = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get()))));
694
695             m_eventSenderProxy->updateTouchPoint(index, x, y);
696             return 0;
697         }
698
699         if (WKStringIsEqualToUTF8CString(subMessageName, "SetTouchModifier")) {
700             WKRetainPtr<WKStringRef> modifierKey = adoptWK(WKStringCreateWithUTF8CString("Modifier"));
701             WKEventModifiers modifier = static_cast<WKEventModifiers>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, modifierKey.get()))));
702
703             WKRetainPtr<WKStringRef> enableKey = adoptWK(WKStringCreateWithUTF8CString("Enable"));
704             bool enable = static_cast<bool>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, enableKey.get()))));
705
706             m_eventSenderProxy->setTouchModifier(modifier, enable);
707             return 0;
708         }
709
710         if (WKStringIsEqualToUTF8CString(subMessageName, "SetTouchPointRadius")) {
711             WKRetainPtr<WKStringRef> xKey = adoptWK(WKStringCreateWithUTF8CString("RadiusX"));
712             int x = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, xKey.get()))));
713
714             WKRetainPtr<WKStringRef> yKey = adoptWK(WKStringCreateWithUTF8CString("RadiusY"));
715             int y = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, yKey.get()))));
716
717             m_eventSenderProxy->setTouchPointRadius(x, y);
718             return 0;
719         }
720
721         if (WKStringIsEqualToUTF8CString(subMessageName, "TouchStart")) {
722             WKPageSetShouldSendEventsSynchronously(mainWebView()->page(), true);
723             m_eventSenderProxy->touchStart();
724             WKPageSetShouldSendEventsSynchronously(mainWebView()->page(), false);
725             return 0;
726         }
727
728         if (WKStringIsEqualToUTF8CString(subMessageName, "TouchMove")) {
729             WKPageSetShouldSendEventsSynchronously(mainWebView()->page(), true);
730             m_eventSenderProxy->touchMove();
731             WKPageSetShouldSendEventsSynchronously(mainWebView()->page(), false);
732             return 0;
733         }
734
735         if (WKStringIsEqualToUTF8CString(subMessageName, "TouchEnd")) {
736             WKPageSetShouldSendEventsSynchronously(mainWebView()->page(), true);
737             m_eventSenderProxy->touchEnd();
738             WKPageSetShouldSendEventsSynchronously(mainWebView()->page(), false);
739             return 0;
740         }
741
742         if (WKStringIsEqualToUTF8CString(subMessageName, "TouchCancel")) {
743             WKPageSetShouldSendEventsSynchronously(mainWebView()->page(), true);
744             m_eventSenderProxy->touchCancel();
745             WKPageSetShouldSendEventsSynchronously(mainWebView()->page(), false);
746             return 0;
747         }
748
749         if (WKStringIsEqualToUTF8CString(subMessageName, "ClearTouchPoints")) {
750             m_eventSenderProxy->clearTouchPoints();
751             return 0;
752         }
753
754         if (WKStringIsEqualToUTF8CString(subMessageName, "ReleaseTouchPoint")) {
755             WKRetainPtr<WKStringRef> indexKey = adoptWK(WKStringCreateWithUTF8CString("Index"));
756             int index = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, indexKey.get()))));
757             m_eventSenderProxy->releaseTouchPoint(index);
758             return 0;
759         }
760
761         if (WKStringIsEqualToUTF8CString(subMessageName, "CancelTouchPoint")) {
762             WKRetainPtr<WKStringRef> indexKey = adoptWK(WKStringCreateWithUTF8CString("Index"));
763             int index = static_cast<int>(WKUInt64GetValue(static_cast<WKUInt64Ref>(WKDictionaryGetItemForKey(messageBodyDictionary, indexKey.get()))));
764             m_eventSenderProxy->cancelTouchPoint(index);
765             return 0;
766         }
767 #endif
768         ASSERT_NOT_REACHED();
769     }
770 #endif
771     return m_currentInvocation->didReceiveSynchronousMessageFromInjectedBundle(messageName, messageBody);
772 }
773
774 // WKPageLoaderClient
775
776 void TestController::didCommitLoadForFrame(WKPageRef page, WKFrameRef frame, WKTypeRef, const void* clientInfo)
777 {
778     static_cast<TestController*>(const_cast<void*>(clientInfo))->didCommitLoadForFrame(page, frame);
779 }
780
781 void TestController::didFinishLoadForFrame(WKPageRef page, WKFrameRef frame, WKTypeRef, const void* clientInfo)
782 {
783     static_cast<TestController*>(const_cast<void*>(clientInfo))->didFinishLoadForFrame(page, frame);
784 }
785
786 void TestController::processDidCrash(WKPageRef page, const void* clientInfo)
787 {
788     static_cast<TestController*>(const_cast<void*>(clientInfo))->processDidCrash();
789 }
790
791 void TestController::didCommitLoadForFrame(WKPageRef page, WKFrameRef frame)
792 {
793     if (!WKFrameIsMainFrame(frame))
794         return;
795
796     mainWebView()->focus();
797 }
798
799 void TestController::didFinishLoadForFrame(WKPageRef page, WKFrameRef frame)
800 {
801     if (m_state != Resetting)
802         return;
803
804     if (!WKFrameIsMainFrame(frame))
805         return;
806
807     WKRetainPtr<WKURLRef> wkURL(AdoptWK, WKFrameCopyURL(frame));
808     if (!WKURLIsEqual(wkURL.get(), blankURL()))
809         return;
810
811     m_doneResetting = true;
812     shared().notifyDone();
813 }
814
815 void TestController::processDidCrash()
816 {
817     // This function can be called multiple times when crash logs are being saved on Windows, so
818     // ensure we only print the crashed message once.
819     if (!m_didPrintWebProcessCrashedMessage) {
820 #if PLATFORM(MAC)
821         pid_t pid = WKPageGetProcessIdentifier(m_mainWebView->page());
822         fprintf(stderr, "#CRASHED - WebProcess (pid %ld)\n", static_cast<long>(pid));
823 #else
824         fputs("#CRASHED - WebProcess\n", stderr);
825 #endif
826         fflush(stderr);
827         m_didPrintWebProcessCrashedMessage = true;
828     }
829
830     if (m_shouldExitWhenWebProcessCrashes)
831         exit(1);
832 }
833
834 } // namespace WTR