WebKitTestRunner: Plugins are disabled in new windows
[WebKit-https.git] / Tools / WebKitTestRunner / InjectedBundle / TestRunner.cpp
1 /*
2  * Copyright (C) 2010-2016 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 "TestRunner.h"
28
29 #include "InjectedBundle.h"
30 #include "InjectedBundlePage.h"
31 #include "JSTestRunner.h"
32 #include "PlatformWebView.h"
33 #include "StringFunctions.h"
34 #include "TestController.h"
35 #include <JavaScriptCore/JSCTestRunnerUtils.h>
36 #include <WebKit/WKBundle.h>
37 #include <WebKit/WKBundleBackForwardList.h>
38 #include <WebKit/WKBundleFrame.h>
39 #include <WebKit/WKBundleFramePrivate.h>
40 #include <WebKit/WKBundleInspector.h>
41 #include <WebKit/WKBundleNodeHandlePrivate.h>
42 #include <WebKit/WKBundlePage.h>
43 #include <WebKit/WKBundlePagePrivate.h>
44 #include <WebKit/WKBundlePrivate.h>
45 #include <WebKit/WKBundleScriptWorld.h>
46 #include <WebKit/WKData.h>
47 #include <WebKit/WKPagePrivate.h>
48 #include <WebKit/WKRetainPtr.h>
49 #include <WebKit/WKSerializedScriptValue.h>
50 #include <WebKit/WebKit2_C.h>
51 #include <wtf/CurrentTime.h>
52 #include <wtf/HashMap.h>
53 #include <wtf/StdLibExtras.h>
54 #include <wtf/text/CString.h>
55 #include <wtf/text/StringBuilder.h>
56
57 namespace WTR {
58
59 Ref<TestRunner> TestRunner::create()
60 {
61     return adoptRef(*new TestRunner);
62 }
63
64 TestRunner::TestRunner()
65     : m_whatToDump(RenderTree)
66     , m_shouldDumpAllFrameScrollPositions(false)
67     , m_shouldDumpBackForwardListsForAllWindows(false)
68     , m_shouldAllowEditing(true)
69     , m_shouldCloseExtraWindows(false)
70     , m_dumpEditingCallbacks(false)
71     , m_dumpStatusCallbacks(false)
72     , m_dumpTitleChanges(false)
73     , m_dumpPixels(true)
74     , m_dumpSelectionRect(false)
75     , m_dumpFullScreenCallbacks(false)
76     , m_dumpFrameLoadCallbacks(false)
77     , m_dumpProgressFinishedCallback(false)
78     , m_dumpResourceLoadCallbacks(false)
79     , m_dumpResourceResponseMIMETypes(false)
80     , m_dumpWillCacheResponse(false)
81     , m_dumpApplicationCacheDelegateCallbacks(false)
82     , m_dumpDatabaseCallbacks(false)
83     , m_disallowIncreaseForApplicationCacheQuota(false)
84     , m_waitToDump(false)
85     , m_testRepaint(false)
86     , m_testRepaintSweepHorizontally(false)
87     , m_isPrinting(false)
88     , m_willSendRequestReturnsNull(false)
89     , m_willSendRequestReturnsNullOnRedirect(false)
90     , m_shouldStopProvisionalFrameLoads(false)
91     , m_policyDelegateEnabled(false)
92     , m_policyDelegatePermissive(false)
93     , m_globalFlag(false)
94     , m_customFullScreenBehavior(false)
95     , m_timeout(30000)
96     , m_databaseDefaultQuota(-1)
97     , m_databaseMaxQuota(-1)
98     , m_userStyleSheetEnabled(false)
99     , m_userStyleSheetLocation(adoptWK(WKStringCreateWithUTF8CString("")))
100 #if PLATFORM(GTK)
101     , m_waitToDumpWatchdogTimer(RunLoop::main(), this, &TestRunner::waitToDumpWatchdogTimerFired)
102 #endif
103 {
104     platformInitialize();
105 }
106
107 TestRunner::~TestRunner()
108 {
109 }
110
111 JSClassRef TestRunner::wrapperClass()
112 {
113     return JSTestRunner::testRunnerClass();
114 }
115
116 void TestRunner::display()
117 {
118     WKBundlePageRef page = InjectedBundle::singleton().page()->page();
119     WKBundlePageForceRepaint(page);
120     WKBundlePageSetTracksRepaints(page, true);
121     WKBundlePageResetTrackedRepaints(page);
122 }
123
124 void TestRunner::dumpAsText(bool dumpPixels)
125 {
126     if (m_whatToDump < MainFrameText)
127         m_whatToDump = MainFrameText;
128     m_dumpPixels = dumpPixels;
129 }
130
131 void TestRunner::setCustomPolicyDelegate(bool enabled, bool permissive)
132 {
133     m_policyDelegateEnabled = enabled;
134     m_policyDelegatePermissive = permissive;
135
136     InjectedBundle::singleton().setCustomPolicyDelegate(enabled, permissive);
137 }
138
139 void TestRunner::waitForPolicyDelegate()
140 {
141     setCustomPolicyDelegate(true);
142     waitUntilDone();
143 }
144
145 void TestRunner::waitUntilDownloadFinished()
146 {
147     m_shouldFinishAfterDownload = true;
148     waitUntilDone();
149 }
150
151 void TestRunner::waitUntilDone()
152 {
153     m_waitToDump = true;
154     if (InjectedBundle::singleton().useWaitToDumpWatchdogTimer())
155         initializeWaitToDumpWatchdogTimerIfNeeded();
156 }
157
158 void TestRunner::waitToDumpWatchdogTimerFired()
159 {
160     invalidateWaitToDumpWatchdogTimer();
161     auto& injectedBundle = InjectedBundle::singleton();
162 #if PLATFORM(COCOA)
163     char buffer[1024];
164     snprintf(buffer, sizeof(buffer), "#PID UNRESPONSIVE - %s (pid %d)\n", getprogname(), getpid());
165     injectedBundle.outputText(buffer);
166 #endif
167     injectedBundle.outputText("FAIL: Timed out waiting for notifyDone to be called\n\n");
168     injectedBundle.done();
169 }
170
171 void TestRunner::notifyDone()
172 {
173     auto& injectedBundle = InjectedBundle::singleton();
174     if (!injectedBundle.isTestRunning())
175         return;
176
177     if (m_waitToDump && !injectedBundle.topLoadingFrame())
178         injectedBundle.page()->dump();
179
180     // We don't call invalidateWaitToDumpWatchdogTimer() here, even if we continue to wait for a load to finish.
181     // The test is still subject to timeout checking - it is better to detect an async timeout inside WebKitTestRunner
182     // than to let webkitpy do that, because WebKitTestRunner will dump partial results.
183
184     m_waitToDump = false;
185 }
186
187 unsigned TestRunner::imageCountInGeneralPasteboard() const
188 {
189     return InjectedBundle::singleton().imageCountInGeneralPasteboard();
190 }
191
192 void TestRunner::addUserScript(JSStringRef source, bool runAtStart, bool allFrames)
193 {
194     WKRetainPtr<WKStringRef> sourceWK = toWK(source);
195
196     WKBundlePageAddUserScript(InjectedBundle::singleton().page()->page(), sourceWK.get(),
197         (runAtStart ? kWKInjectAtDocumentStart : kWKInjectAtDocumentEnd),
198         (allFrames ? kWKInjectInAllFrames : kWKInjectInTopFrameOnly));
199 }
200
201 void TestRunner::addUserStyleSheet(JSStringRef source, bool allFrames)
202 {
203     WKRetainPtr<WKStringRef> sourceWK = toWK(source);
204
205     WKBundlePageAddUserStyleSheet(InjectedBundle::singleton().page()->page(), sourceWK.get(),
206         (allFrames ? kWKInjectInAllFrames : kWKInjectInTopFrameOnly));
207 }
208
209 void TestRunner::keepWebHistory()
210 {
211     InjectedBundle::singleton().postSetAddsVisitedLinks(true);
212 }
213
214 void TestRunner::execCommand(JSStringRef name, JSStringRef argument)
215 {
216     WKBundlePageExecuteEditingCommand(InjectedBundle::singleton().page()->page(), toWK(name).get(), toWK(argument).get());
217 }
218
219 bool TestRunner::findString(JSStringRef target, JSValueRef optionsArrayAsValue)
220 {
221     WKFindOptions options = 0;
222
223     auto& injectedBundle = InjectedBundle::singleton();
224     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(injectedBundle.page()->page());
225     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
226     JSRetainPtr<JSStringRef> lengthPropertyName(Adopt, JSStringCreateWithUTF8CString("length"));
227     JSObjectRef optionsArray = JSValueToObject(context, optionsArrayAsValue, 0);
228     JSValueRef lengthValue = JSObjectGetProperty(context, optionsArray, lengthPropertyName.get(), 0);
229     if (!JSValueIsNumber(context, lengthValue))
230         return false;
231
232     size_t length = static_cast<size_t>(JSValueToNumber(context, lengthValue, 0));
233     for (size_t i = 0; i < length; ++i) {
234         JSValueRef value = JSObjectGetPropertyAtIndex(context, optionsArray, i, 0);
235         if (!JSValueIsString(context, value))
236             continue;
237
238         JSRetainPtr<JSStringRef> optionName(Adopt, JSValueToStringCopy(context, value, 0));
239
240         if (JSStringIsEqualToUTF8CString(optionName.get(), "CaseInsensitive"))
241             options |= kWKFindOptionsCaseInsensitive;
242         else if (JSStringIsEqualToUTF8CString(optionName.get(), "AtWordStarts"))
243             options |= kWKFindOptionsAtWordStarts;
244         else if (JSStringIsEqualToUTF8CString(optionName.get(), "TreatMedialCapitalAsWordStart"))
245             options |= kWKFindOptionsTreatMedialCapitalAsWordStart;
246         else if (JSStringIsEqualToUTF8CString(optionName.get(), "Backwards"))
247             options |= kWKFindOptionsBackwards;
248         else if (JSStringIsEqualToUTF8CString(optionName.get(), "WrapAround"))
249             options |= kWKFindOptionsWrapAround;
250         else if (JSStringIsEqualToUTF8CString(optionName.get(), "StartInSelection")) {
251             // FIXME: No kWKFindOptionsStartInSelection.
252         }
253     }
254
255     return WKBundlePageFindString(injectedBundle.page()->page(), toWK(target).get(), options);
256 }
257
258 void TestRunner::clearAllDatabases()
259 {
260     WKBundleClearAllDatabases(InjectedBundle::singleton().bundle());
261
262     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("DeleteAllIndexedDatabases"));
263     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(true));
264
265     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
266 }
267
268 void TestRunner::setDatabaseQuota(uint64_t quota)
269 {
270     return WKBundleSetDatabaseQuota(InjectedBundle::singleton().bundle(), quota);
271 }
272
273 void TestRunner::clearAllApplicationCaches()
274 {
275     WKBundlePageClearApplicationCache(InjectedBundle::singleton().page()->page());
276 }
277
278 void TestRunner::clearApplicationCacheForOrigin(JSStringRef origin)
279 {
280     WKBundlePageClearApplicationCacheForOrigin(InjectedBundle::singleton().page()->page(), toWK(origin).get());
281 }
282
283 void TestRunner::setAppCacheMaximumSize(uint64_t size)
284 {
285     WKBundlePageSetAppCacheMaximumSize(InjectedBundle::singleton().page()->page(), size);
286 }
287
288 long long TestRunner::applicationCacheDiskUsageForOrigin(JSStringRef origin)
289 {
290     return WKBundlePageGetAppCacheUsageForOrigin(InjectedBundle::singleton().page()->page(), toWK(origin).get());
291 }
292
293 void TestRunner::disallowIncreaseForApplicationCacheQuota()
294 {
295     m_disallowIncreaseForApplicationCacheQuota = true;
296 }
297
298 static inline JSValueRef stringArrayToJS(JSContextRef context, WKArrayRef strings)
299 {
300     const size_t count = WKArrayGetSize(strings);
301
302     JSValueRef arrayResult = JSObjectMakeArray(context, 0, 0, 0);
303     JSObjectRef arrayObj = JSValueToObject(context, arrayResult, 0);
304     for (size_t i = 0; i < count; ++i) {
305         WKStringRef stringRef = static_cast<WKStringRef>(WKArrayGetItemAtIndex(strings, i));
306         JSRetainPtr<JSStringRef> stringJS = toJS(stringRef);
307         JSObjectSetPropertyAtIndex(context, arrayObj, i, JSValueMakeString(context, stringJS.get()), 0);
308     }
309
310     return arrayResult;
311 }
312
313 JSValueRef TestRunner::originsWithApplicationCache()
314 {
315     WKBundlePageRef page = InjectedBundle::singleton().page()->page();
316
317     WKRetainPtr<WKArrayRef> origins(AdoptWK, WKBundlePageCopyOriginsWithApplicationCache(page));
318
319     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(page);
320     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
321
322     return stringArrayToJS(context, origins.get());
323 }
324
325 bool TestRunner::isCommandEnabled(JSStringRef name)
326 {
327     return WKBundlePageIsEditingCommandEnabled(InjectedBundle::singleton().page()->page(), toWK(name).get());
328 }
329
330 void TestRunner::setCanOpenWindows(bool)
331 {
332     // It's not clear if or why any tests require opening windows be forbidden.
333     // For now, just ignore this setting, and if we find later it's needed we can add it.
334 }
335
336 void TestRunner::setXSSAuditorEnabled(bool enabled)
337 {
338     WKRetainPtr<WKStringRef> key(AdoptWK, WKStringCreateWithUTF8CString("WebKitXSSAuditorEnabled"));
339     auto& injectedBundle = InjectedBundle::singleton();
340     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), key.get(), enabled);
341 }
342
343 void TestRunner::setShadowDOMEnabled(bool enabled)
344 {
345     WKRetainPtr<WKStringRef> key(AdoptWK, WKStringCreateWithUTF8CString("WebKitShadowDOMEnabled"));
346     auto& injectedBundle = InjectedBundle::singleton();
347     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), key.get(), enabled);
348 }
349
350 void TestRunner::setCustomElementsEnabled(bool enabled)
351 {
352     WKRetainPtr<WKStringRef> key(AdoptWK, WKStringCreateWithUTF8CString("WebKitCustomElementsEnabled"));
353     auto& injectedBundle = InjectedBundle::singleton();
354     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), key.get(), enabled);
355 }
356
357 void TestRunner::setSubtleCryptoEnabled(bool enabled)
358 {
359     WKRetainPtr<WKStringRef> key(AdoptWK, WKStringCreateWithUTF8CString("WebKitSubtleCryptoEnabled"));
360     auto& injectedBundle = InjectedBundle::singleton();
361     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), key.get(), enabled);
362 }
363
364 void TestRunner::setDOMIteratorEnabled(bool enabled)
365 {
366     WKRetainPtr<WKStringRef> key(AdoptWK, WKStringCreateWithUTF8CString("WebKitDOMIteratorEnabled"));
367     auto& injectedBundle = InjectedBundle::singleton();
368     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), key.get(), enabled);
369 }
370
371 void TestRunner::setModernMediaControlsEnabled(bool enabled)
372 {
373     WKRetainPtr<WKStringRef> key(AdoptWK, WKStringCreateWithUTF8CString("WebKitModernMediaControlsEnabled"));
374     auto& injectedBundle = InjectedBundle::singleton();
375     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), key.get(), enabled);
376 }
377
378 void TestRunner::setWebGL2Enabled(bool enabled)
379 {
380     WKRetainPtr<WKStringRef> key(AdoptWK, WKStringCreateWithUTF8CString("WebKitWebGL2Enabled"));
381     auto& injectedBundle = InjectedBundle::singleton();
382     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), key.get(), enabled);
383 }
384
385 void TestRunner::setFetchAPIEnabled(bool enabled)
386 {
387     WKRetainPtr<WKStringRef> key(AdoptWK, WKStringCreateWithUTF8CString("WebKitFetchAPIEnabled"));
388     auto& injectedBundle = InjectedBundle::singleton();
389     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), key.get(), enabled);
390 }
391
392 void TestRunner::setDownloadAttributeEnabled(bool enabled)
393 {
394     WKRetainPtr<WKStringRef> key(AdoptWK, WKStringCreateWithUTF8CString("WebKitDownloadAttributeEnabled"));
395     auto& injectedBundle = InjectedBundle::singleton();
396     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), key.get(), enabled);
397 }
398
399 void TestRunner::setES6ModulesEnabled(bool enabled)
400 {
401     WKRetainPtr<WKStringRef> key(AdoptWK, WKStringCreateWithUTF8CString("WebKitES6ModulesEnabled"));
402     auto& injectedBundle = InjectedBundle::singleton();
403     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), key.get(), enabled);
404 }
405
406 void TestRunner::setEncryptedMediaAPIEnabled(bool enabled)
407 {
408     WKRetainPtr<WKStringRef> key(AdoptWK, WKStringCreateWithUTF8CString("WebKitEncryptedMediaAPIEnabled"));
409     auto& injectedBundle = InjectedBundle::singleton();
410     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), key.get(), enabled);
411 }
412
413 void TestRunner::setAllowsAnySSLCertificate(bool enabled)
414 {
415     InjectedBundle::singleton().setAllowsAnySSLCertificate(enabled);
416 }
417
418 void TestRunner::setAllowUniversalAccessFromFileURLs(bool enabled)
419 {
420     auto& injectedBundle = InjectedBundle::singleton();
421     WKBundleSetAllowUniversalAccessFromFileURLs(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
422 }
423
424 void TestRunner::setAllowFileAccessFromFileURLs(bool enabled)
425 {
426     auto& injectedBundle = InjectedBundle::singleton();
427     WKBundleSetAllowFileAccessFromFileURLs(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
428 }
429
430 void TestRunner::setNeedsStorageAccessFromFileURLsQuirk(bool needsQuirk)
431 {
432     auto& injectedBundle = InjectedBundle::singleton();
433     WKBundleSetAllowStorageAccessFromFileURLS(injectedBundle.bundle(), injectedBundle.pageGroup(), needsQuirk);
434 }
435     
436 void TestRunner::setPluginsEnabled(bool enabled)
437 {
438     WKRetainPtr<WKStringRef> key(AdoptWK, WKStringCreateWithUTF8CString("WebKitPluginsEnabled"));
439     auto& injectedBundle = InjectedBundle::singleton();
440     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), key.get(), enabled);
441 }
442
443 void TestRunner::setJavaScriptCanAccessClipboard(bool enabled)
444 {
445     auto& injectedBundle = InjectedBundle::singleton();
446     WKBundleSetJavaScriptCanAccessClipboard(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
447 }
448
449 void TestRunner::setPrivateBrowsingEnabled(bool enabled)
450 {
451     auto& injectedBundle = InjectedBundle::singleton();
452     WKBundleSetPrivateBrowsingEnabled(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
453 }
454
455 void TestRunner::setUseDashboardCompatibilityMode(bool enabled)
456 {
457 #if ENABLE(DASHBOARD_SUPPORT)
458     auto& injectedBundle = InjectedBundle::singleton();
459     WKBundleSetUseDashboardCompatibilityMode(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
460 #endif
461 }
462     
463 void TestRunner::setPopupBlockingEnabled(bool enabled)
464 {
465     auto& injectedBundle = InjectedBundle::singleton();
466     WKBundleSetPopupBlockingEnabled(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
467 }
468
469 void TestRunner::setAuthorAndUserStylesEnabled(bool enabled)
470 {
471     auto& injectedBundle = InjectedBundle::singleton();
472     WKBundleSetAuthorAndUserStylesEnabled(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
473 }
474
475 void TestRunner::addOriginAccessWhitelistEntry(JSStringRef sourceOrigin, JSStringRef destinationProtocol, JSStringRef destinationHost, bool allowDestinationSubdomains)
476 {
477     WKBundleAddOriginAccessWhitelistEntry(InjectedBundle::singleton().bundle(), toWK(sourceOrigin).get(), toWK(destinationProtocol).get(), toWK(destinationHost).get(), allowDestinationSubdomains);
478 }
479
480 void TestRunner::removeOriginAccessWhitelistEntry(JSStringRef sourceOrigin, JSStringRef destinationProtocol, JSStringRef destinationHost, bool allowDestinationSubdomains)
481 {
482     WKBundleRemoveOriginAccessWhitelistEntry(InjectedBundle::singleton().bundle(), toWK(sourceOrigin).get(), toWK(destinationProtocol).get(), toWK(destinationHost).get(), allowDestinationSubdomains);
483 }
484
485 bool TestRunner::isPageBoxVisible(int pageIndex)
486 {
487     auto& injectedBundle = InjectedBundle::singleton();
488     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(injectedBundle.page()->page());
489     return WKBundleIsPageBoxVisible(injectedBundle.bundle(), mainFrame, pageIndex);
490 }
491
492 void TestRunner::setValueForUser(JSContextRef context, JSValueRef element, JSStringRef value)
493 {
494     if (!element || !JSValueIsObject(context, element))
495         return;
496
497     WKRetainPtr<WKBundleNodeHandleRef> nodeHandle(AdoptWK, WKBundleNodeHandleCreate(context, const_cast<JSObjectRef>(element)));
498     WKBundleNodeHandleSetHTMLInputElementValueForUser(nodeHandle.get(), toWK(value).get());
499 }
500
501 void TestRunner::setAudioResult(JSContextRef context, JSValueRef data)
502 {
503     auto& injectedBundle = InjectedBundle::singleton();
504     // FIXME (123058): Use a JSC API to get buffer contents once such is exposed.
505     WKRetainPtr<WKDataRef> audioData(AdoptWK, WKBundleCreateWKDataFromUInt8Array(injectedBundle.bundle(), context, data));
506     injectedBundle.setAudioResult(audioData.get());
507     m_whatToDump = Audio;
508     m_dumpPixels = false;
509 }
510
511 unsigned TestRunner::windowCount()
512 {
513     return InjectedBundle::singleton().pageCount();
514 }
515
516 void TestRunner::clearBackForwardList()
517 {
518     WKBundleBackForwardListClear(WKBundlePageGetBackForwardList(InjectedBundle::singleton().page()->page()));
519 }
520
521 // Object Creation
522
523 void TestRunner::makeWindowObject(JSContextRef context, JSObjectRef windowObject, JSValueRef* exception)
524 {
525     setProperty(context, windowObject, "testRunner", this, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete, exception);
526 }
527
528 void TestRunner::showWebInspector()
529 {
530     WKBundleInspectorShow(WKBundlePageGetInspector(InjectedBundle::singleton().page()->page()));
531 }
532
533 void TestRunner::closeWebInspector()
534 {
535     WKBundleInspectorClose(WKBundlePageGetInspector(InjectedBundle::singleton().page()->page()));
536 }
537
538 void TestRunner::evaluateInWebInspector(JSStringRef script)
539 {
540     WKRetainPtr<WKStringRef> scriptWK = toWK(script);
541     WKBundleInspectorEvaluateScriptForTest(WKBundlePageGetInspector(InjectedBundle::singleton().page()->page()), scriptWK.get());
542 }
543
544 typedef WTF::HashMap<unsigned, WKRetainPtr<WKBundleScriptWorldRef> > WorldMap;
545 static WorldMap& worldMap()
546 {
547     static WorldMap& map = *new WorldMap;
548     return map;
549 }
550
551 unsigned TestRunner::worldIDForWorld(WKBundleScriptWorldRef world)
552 {
553     WorldMap::const_iterator end = worldMap().end();
554     for (WorldMap::const_iterator it = worldMap().begin(); it != end; ++it) {
555         if (it->value == world)
556             return it->key;
557     }
558
559     return 0;
560 }
561
562 void TestRunner::evaluateScriptInIsolatedWorld(JSContextRef context, unsigned worldID, JSStringRef script)
563 {
564     // A worldID of 0 always corresponds to a new world. Any other worldID corresponds to a world
565     // that is created once and cached forever.
566     WKRetainPtr<WKBundleScriptWorldRef> world;
567     if (!worldID)
568         world.adopt(WKBundleScriptWorldCreateWorld());
569     else {
570         WKRetainPtr<WKBundleScriptWorldRef>& worldSlot = worldMap().add(worldID, nullptr).iterator->value;
571         if (!worldSlot)
572             worldSlot.adopt(WKBundleScriptWorldCreateWorld());
573         world = worldSlot;
574     }
575
576     WKBundleFrameRef frame = WKBundleFrameForJavaScriptContext(context);
577     if (!frame)
578         frame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
579
580     JSGlobalContextRef jsContext = WKBundleFrameGetJavaScriptContextForWorld(frame, world.get());
581     JSEvaluateScript(jsContext, script, 0, 0, 0, 0); 
582 }
583
584 void TestRunner::setPOSIXLocale(JSStringRef locale)
585 {
586     char localeBuf[32];
587     JSStringGetUTF8CString(locale, localeBuf, sizeof(localeBuf));
588     setlocale(LC_ALL, localeBuf);
589 }
590
591 void TestRunner::setTextDirection(JSStringRef direction)
592 {
593     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
594     return WKBundleFrameSetTextDirection(mainFrame, toWK(direction).get());
595 }
596     
597 void TestRunner::setShouldStayOnPageAfterHandlingBeforeUnload(bool shouldStayOnPage)
598 {
599     InjectedBundle::singleton().postNewBeforeUnloadReturnValue(!shouldStayOnPage);
600 }
601
602 void TestRunner::setDefersLoading(bool shouldDeferLoading)
603 {
604     WKBundlePageSetDefersLoading(InjectedBundle::singleton().page()->page(), shouldDeferLoading);
605 }
606
607 void TestRunner::setPageVisibility(JSStringRef state)
608 {
609     InjectedBundle::singleton().setHidden(JSStringIsEqualToUTF8CString(state, "hidden") || JSStringIsEqualToUTF8CString(state, "prerender"));
610 }
611
612 void TestRunner::resetPageVisibility()
613 {
614     InjectedBundle::singleton().setHidden(false);
615 }
616
617 typedef WTF::HashMap<unsigned, JSValueRef> CallbackMap;
618 static CallbackMap& callbackMap()
619 {
620     static CallbackMap& map = *new CallbackMap;
621     return map;
622 }
623
624 enum {
625     AddChromeInputFieldCallbackID = 1,
626     RemoveChromeInputFieldCallbackID,
627     FocusWebViewCallbackID,
628     SetBackingScaleFactorCallbackID,
629     DidBeginSwipeCallbackID,
630     WillEndSwipeCallbackID,
631     DidEndSwipeCallbackID,
632     DidRemoveSwipeSnapshotCallbackID,
633     FirstUIScriptCallbackID = 100
634 };
635
636 static void cacheTestRunnerCallback(unsigned index, JSValueRef callback)
637 {
638     if (!callback)
639         return;
640
641     if (callbackMap().contains(index)) {
642         InjectedBundle::singleton().outputText(String::format("FAIL: Tried to install a second TestRunner callback for the same event (id %d)\n\n", index));
643         return;
644     }
645
646     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
647     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
648     JSValueProtect(context, callback);
649     callbackMap().add(index, callback);
650 }
651
652 static void callTestRunnerCallback(unsigned index, size_t argumentCount = 0, const JSValueRef arguments[] = nullptr)
653 {
654     if (!callbackMap().contains(index))
655         return;
656     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
657     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
658     JSObjectRef callback = JSValueToObject(context, callbackMap().take(index), 0);
659     JSObjectCallAsFunction(context, callback, JSContextGetGlobalObject(context), argumentCount, arguments, 0);
660     JSValueUnprotect(context, callback);
661 }
662
663 void TestRunner::clearTestRunnerCallbacks()
664 {
665     for (auto& iter : callbackMap()) {
666         WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
667         JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
668         JSObjectRef callback = JSValueToObject(context, iter.value, 0);
669         JSValueUnprotect(context, callback);
670     }
671
672     callbackMap().clear();
673 }
674
675 void TestRunner::accummulateLogsForChannel(JSStringRef)
676 {
677     // FIXME: Implement getting the call to all processes.
678 }
679
680 void TestRunner::addChromeInputField(JSValueRef callback)
681 {
682     cacheTestRunnerCallback(AddChromeInputFieldCallbackID, callback);
683     InjectedBundle::singleton().postAddChromeInputField();
684 }
685
686 void TestRunner::removeChromeInputField(JSValueRef callback)
687 {
688     cacheTestRunnerCallback(RemoveChromeInputFieldCallbackID, callback);
689     InjectedBundle::singleton().postRemoveChromeInputField();
690 }
691
692 void TestRunner::focusWebView(JSValueRef callback)
693 {
694     cacheTestRunnerCallback(FocusWebViewCallbackID, callback);
695     InjectedBundle::singleton().postFocusWebView();
696 }
697
698 void TestRunner::setBackingScaleFactor(double backingScaleFactor, JSValueRef callback)
699 {
700     cacheTestRunnerCallback(SetBackingScaleFactorCallbackID, callback);
701     InjectedBundle::singleton().postSetBackingScaleFactor(backingScaleFactor);
702 }
703
704 void TestRunner::setWindowIsKey(bool isKey)
705 {
706     InjectedBundle::singleton().postSetWindowIsKey(isKey);
707 }
708
709 void TestRunner::setViewSize(double width, double height)
710 {
711     InjectedBundle::singleton().postSetViewSize(width, height);
712 }
713
714 void TestRunner::callAddChromeInputFieldCallback()
715 {
716     callTestRunnerCallback(AddChromeInputFieldCallbackID);
717 }
718
719 void TestRunner::callRemoveChromeInputFieldCallback()
720 {
721     callTestRunnerCallback(RemoveChromeInputFieldCallbackID);
722 }
723
724 void TestRunner::callFocusWebViewCallback()
725 {
726     callTestRunnerCallback(FocusWebViewCallbackID);
727 }
728
729 void TestRunner::callSetBackingScaleFactorCallback()
730 {
731     callTestRunnerCallback(SetBackingScaleFactorCallbackID);
732 }
733
734 static inline bool toBool(JSStringRef value)
735 {
736     return JSStringIsEqualToUTF8CString(value, "true") || JSStringIsEqualToUTF8CString(value, "1");
737 }
738
739 void TestRunner::overridePreference(JSStringRef preference, JSStringRef value)
740 {
741     auto& injectedBundle = InjectedBundle::singleton();
742     // FIXME: handle non-boolean preferences.
743     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), toWK(preference).get(), toBool(value));
744 }
745
746 void TestRunner::setAlwaysAcceptCookies(bool accept)
747 {
748     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetAlwaysAcceptCookies"));
749
750     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(accept));
751
752     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
753 }
754
755 double TestRunner::preciseTime()
756 {
757     return currentTime();
758 }
759
760 void TestRunner::setUserStyleSheetEnabled(bool enabled)
761 {
762     m_userStyleSheetEnabled = enabled;
763
764     WKRetainPtr<WKStringRef> emptyUrl = adoptWK(WKStringCreateWithUTF8CString(""));
765     WKStringRef location = enabled ? m_userStyleSheetLocation.get() : emptyUrl.get();
766     auto& injectedBundle = InjectedBundle::singleton();
767     WKBundleSetUserStyleSheetLocation(injectedBundle.bundle(), injectedBundle.pageGroup(), location);
768 }
769
770 void TestRunner::setUserStyleSheetLocation(JSStringRef location)
771 {
772     m_userStyleSheetLocation = adoptWK(WKStringCreateWithJSString(location));
773
774     if (m_userStyleSheetEnabled)
775         setUserStyleSheetEnabled(true);
776 }
777
778 void TestRunner::setSpatialNavigationEnabled(bool enabled)
779 {
780     auto& injectedBundle = InjectedBundle::singleton();
781     WKBundleSetSpatialNavigationEnabled(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
782 }
783
784 void TestRunner::setTabKeyCyclesThroughElements(bool enabled)
785 {
786     auto& injectedBundle = InjectedBundle::singleton();
787     WKBundleSetTabKeyCyclesThroughElements(injectedBundle.bundle(), injectedBundle.page()->page(), enabled);
788 }
789
790 void TestRunner::setSerializeHTTPLoads()
791 {
792     // WK2 doesn't reorder loads.
793 }
794
795 void TestRunner::dispatchPendingLoadRequests()
796 {
797     // WK2 doesn't keep pending requests.
798 }
799
800 void TestRunner::setCacheModel(int model)
801 {
802     InjectedBundle::singleton().setCacheModel(model);
803 }
804
805 void TestRunner::setAsynchronousSpellCheckingEnabled(bool enabled)
806 {
807     auto& injectedBundle = InjectedBundle::singleton();
808     WKBundleSetAsynchronousSpellCheckingEnabled(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
809 }
810
811 void TestRunner::grantWebNotificationPermission(JSStringRef origin)
812 {
813     WKRetainPtr<WKStringRef> originWK = toWK(origin);
814     auto& injectedBundle = InjectedBundle::singleton();
815     WKBundleSetWebNotificationPermission(injectedBundle.bundle(), injectedBundle.page()->page(), originWK.get(), true);
816 }
817
818 void TestRunner::denyWebNotificationPermission(JSStringRef origin)
819 {
820     WKRetainPtr<WKStringRef> originWK = toWK(origin);
821     auto& injectedBundle = InjectedBundle::singleton();
822     WKBundleSetWebNotificationPermission(injectedBundle.bundle(), injectedBundle.page()->page(), originWK.get(), false);
823 }
824
825 void TestRunner::removeAllWebNotificationPermissions()
826 {
827     auto& injectedBundle = InjectedBundle::singleton();
828     WKBundleRemoveAllWebNotificationPermissions(injectedBundle.bundle(), injectedBundle.page()->page());
829 }
830
831 void TestRunner::simulateWebNotificationClick(JSValueRef notification)
832 {
833     auto& injectedBundle = InjectedBundle::singleton();
834     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(injectedBundle.page()->page());
835     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
836     uint64_t notificationID = WKBundleGetWebNotificationID(injectedBundle.bundle(), context, notification);
837     injectedBundle.postSimulateWebNotificationClick(notificationID);
838 }
839
840 void TestRunner::setGeolocationPermission(bool enabled)
841 {
842     // FIXME: this should be done by frame.
843     InjectedBundle::singleton().setGeolocationPermission(enabled);
844 }
845
846 bool TestRunner::isGeolocationProviderActive()
847 {
848     return InjectedBundle::singleton().isGeolocationProviderActive();
849 }
850
851 void TestRunner::setMockGeolocationPosition(double latitude, double longitude, double accuracy, JSValueRef jsAltitude, JSValueRef jsAltitudeAccuracy, JSValueRef jsHeading, JSValueRef jsSpeed)
852 {
853     auto& injectedBundle = InjectedBundle::singleton();
854     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(injectedBundle.page()->page());
855     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
856
857     bool providesAltitude = false;
858     double altitude = 0.;
859     if (!JSValueIsUndefined(context, jsAltitude)) {
860         providesAltitude = true;
861         altitude = JSValueToNumber(context, jsAltitude, 0);
862     }
863
864     bool providesAltitudeAccuracy = false;
865     double altitudeAccuracy = 0.;
866     if (!JSValueIsUndefined(context, jsAltitudeAccuracy)) {
867         providesAltitudeAccuracy = true;
868         altitudeAccuracy = JSValueToNumber(context, jsAltitudeAccuracy, 0);
869     }
870
871     bool providesHeading = false;
872     double heading = 0.;
873     if (!JSValueIsUndefined(context, jsHeading)) {
874         providesHeading = true;
875         heading = JSValueToNumber(context, jsHeading, 0);
876     }
877
878     bool providesSpeed = false;
879     double speed = 0.;
880     if (!JSValueIsUndefined(context, jsSpeed)) {
881         providesSpeed = true;
882         speed = JSValueToNumber(context, jsSpeed, 0);
883     }
884
885     injectedBundle.setMockGeolocationPosition(latitude, longitude, accuracy, providesAltitude, altitude, providesAltitudeAccuracy, altitudeAccuracy, providesHeading, heading, providesSpeed, speed);
886 }
887
888 void TestRunner::setMockGeolocationPositionUnavailableError(JSStringRef message)
889 {
890     WKRetainPtr<WKStringRef> messageWK = toWK(message);
891     InjectedBundle::singleton().setMockGeolocationPositionUnavailableError(messageWK.get());
892 }
893
894 void TestRunner::setUserMediaPermission(bool enabled)
895 {
896     // FIXME: this should be done by frame.
897     InjectedBundle::singleton().setUserMediaPermission(enabled);
898 }
899
900 void TestRunner::setUserMediaPersistentPermissionForOrigin(bool permission, JSStringRef origin, JSStringRef parentOrigin)
901 {
902     WKRetainPtr<WKStringRef> originWK = toWK(origin);
903     WKRetainPtr<WKStringRef> parentOriginWK = toWK(parentOrigin);
904     InjectedBundle::singleton().setUserMediaPersistentPermissionForOrigin(permission, originWK.get(), parentOriginWK.get());
905 }
906
907 unsigned TestRunner::userMediaPermissionRequestCountForOrigin(JSStringRef origin, JSStringRef parentOrigin) const
908 {
909     WKRetainPtr<WKStringRef> originWK = toWK(origin);
910     WKRetainPtr<WKStringRef> parentOriginWK = toWK(parentOrigin);
911     return InjectedBundle::singleton().userMediaPermissionRequestCountForOrigin(originWK.get(), parentOriginWK.get());
912 }
913
914 void TestRunner::resetUserMediaPermissionRequestCountForOrigin(JSStringRef origin, JSStringRef parentOrigin)
915 {
916     WKRetainPtr<WKStringRef> originWK = toWK(origin);
917     WKRetainPtr<WKStringRef> parentOriginWK = toWK(parentOrigin);
918     InjectedBundle::singleton().resetUserMediaPermissionRequestCountForOrigin(originWK.get(), parentOriginWK.get());
919 }
920
921 bool TestRunner::callShouldCloseOnWebView()
922 {
923     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
924     return WKBundleFrameCallShouldCloseOnWebView(mainFrame);
925 }
926
927 void TestRunner::queueBackNavigation(unsigned howFarBackward)
928 {
929     InjectedBundle::singleton().queueBackNavigation(howFarBackward);
930 }
931
932 void TestRunner::queueForwardNavigation(unsigned howFarForward)
933 {
934     InjectedBundle::singleton().queueForwardNavigation(howFarForward);
935 }
936
937 void TestRunner::queueLoad(JSStringRef url, JSStringRef target, bool shouldOpenExternalURLs)
938 {
939     auto& injectedBundle = InjectedBundle::singleton();
940     WKRetainPtr<WKURLRef> baseURLWK(AdoptWK, WKBundleFrameCopyURL(WKBundlePageGetMainFrame(injectedBundle.page()->page())));
941     WKRetainPtr<WKURLRef> urlWK(AdoptWK, WKURLCreateWithBaseURL(baseURLWK.get(), toWTFString(toWK(url)).utf8().data()));
942     WKRetainPtr<WKStringRef> urlStringWK(AdoptWK, WKURLCopyString(urlWK.get()));
943
944     injectedBundle.queueLoad(urlStringWK.get(), toWK(target).get(), shouldOpenExternalURLs);
945 }
946
947 void TestRunner::queueLoadHTMLString(JSStringRef content, JSStringRef baseURL, JSStringRef unreachableURL)
948 {
949     WKRetainPtr<WKStringRef> contentWK = toWK(content);
950     WKRetainPtr<WKStringRef> baseURLWK = baseURL ? toWK(baseURL) : WKRetainPtr<WKStringRef>();
951     WKRetainPtr<WKStringRef> unreachableURLWK = unreachableURL ? toWK(unreachableURL) : WKRetainPtr<WKStringRef>();
952
953     InjectedBundle::singleton().queueLoadHTMLString(contentWK.get(), baseURLWK.get(), unreachableURLWK.get());
954 }
955
956 void TestRunner::queueReload()
957 {
958     InjectedBundle::singleton().queueReload();
959 }
960
961 void TestRunner::queueLoadingScript(JSStringRef script)
962 {
963     WKRetainPtr<WKStringRef> scriptWK = toWK(script);
964     InjectedBundle::singleton().queueLoadingScript(scriptWK.get());
965 }
966
967 void TestRunner::queueNonLoadingScript(JSStringRef script)
968 {
969     WKRetainPtr<WKStringRef> scriptWK = toWK(script);
970     InjectedBundle::singleton().queueNonLoadingScript(scriptWK.get());
971 }
972
973 void TestRunner::setRejectsProtectionSpaceAndContinueForAuthenticationChallenges(bool value)
974 {
975     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetRejectsProtectionSpaceAndContinueForAuthenticationChallenges"));
976     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(value));
977     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
978 }
979     
980 void TestRunner::setHandlesAuthenticationChallenges(bool handlesAuthenticationChallenges)
981 {
982     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetHandlesAuthenticationChallenges"));
983     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(handlesAuthenticationChallenges));
984     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
985 }
986
987 void TestRunner::setShouldLogCanAuthenticateAgainstProtectionSpace(bool value)
988 {
989     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetShouldLogCanAuthenticateAgainstProtectionSpace"));
990     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(value));
991     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
992 }
993
994 void TestRunner::setAuthenticationUsername(JSStringRef username)
995 {
996     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetAuthenticationUsername"));
997     WKRetainPtr<WKStringRef> messageBody(AdoptWK, WKStringCreateWithJSString(username));
998     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
999 }
1000
1001 void TestRunner::setAuthenticationPassword(JSStringRef password)
1002 {
1003     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetAuthenticationPassword"));
1004     WKRetainPtr<WKStringRef> messageBody(AdoptWK, WKStringCreateWithJSString(password));
1005     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
1006 }
1007
1008 bool TestRunner::secureEventInputIsEnabled() const
1009 {
1010     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SecureEventInputIsEnabled"));
1011     WKTypeRef returnData = 0;
1012
1013     WKBundlePagePostSynchronousMessageForTesting(InjectedBundle::singleton().page()->page(), messageName.get(), 0, &returnData);
1014     return WKBooleanGetValue(static_cast<WKBooleanRef>(returnData));
1015 }
1016
1017 void TestRunner::setBlockAllPlugins(bool shouldBlock)
1018 {
1019     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetBlockAllPlugins"));
1020     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(shouldBlock));
1021     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
1022 }
1023
1024 JSValueRef TestRunner::failNextNewCodeBlock()
1025 {
1026     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
1027     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
1028     return JSC::failNextNewCodeBlock(context);
1029 }
1030
1031 JSValueRef TestRunner::numberOfDFGCompiles(JSValueRef theFunction)
1032 {
1033     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
1034     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
1035     return JSC::numberOfDFGCompiles(context, theFunction);
1036 }
1037
1038 JSValueRef TestRunner::neverInlineFunction(JSValueRef theFunction)
1039 {
1040     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
1041     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
1042     return JSC::setNeverInline(context, theFunction);
1043 }
1044
1045 void TestRunner::setShouldDecideNavigationPolicyAfterDelay(bool value)
1046 {
1047     m_shouldDecideNavigationPolicyAfterDelay = value;
1048     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetShouldDecideNavigationPolicyAfterDelay"));
1049     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(value));
1050     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
1051 }
1052
1053 void TestRunner::setNavigationGesturesEnabled(bool value)
1054 {
1055     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetNavigationGesturesEnabled"));
1056     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(value));
1057     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
1058 }
1059
1060 void TestRunner::setIgnoresViewportScaleLimits(bool value)
1061 {
1062     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetIgnoresViewportScaleLimits"));
1063     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(value));
1064     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
1065 }
1066
1067 void TestRunner::setShouldDownloadUndisplayableMIMETypes(bool value)
1068 {
1069     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetShouldDownloadUndisplayableMIMETypes"));
1070     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(value));
1071     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
1072 }
1073
1074 static unsigned nextUIScriptCallbackID()
1075 {
1076     static unsigned callbackID = FirstUIScriptCallbackID;
1077     return callbackID++;
1078 }
1079
1080 void TestRunner::runUIScript(JSStringRef script, JSValueRef callback)
1081 {
1082     unsigned callbackID = nextUIScriptCallbackID();
1083     cacheTestRunnerCallback(callbackID, callback);
1084
1085     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("RunUIProcessScript"));
1086
1087     WKRetainPtr<WKMutableDictionaryRef> testDictionary(AdoptWK, WKMutableDictionaryCreate());
1088
1089     WKRetainPtr<WKStringRef> scriptKey(AdoptWK, WKStringCreateWithUTF8CString("Script"));
1090     WKRetainPtr<WKStringRef> scriptValue(AdoptWK, WKStringCreateWithJSString(script));
1091
1092     WKRetainPtr<WKStringRef> callbackIDKey(AdoptWK, WKStringCreateWithUTF8CString("CallbackID"));
1093     WKRetainPtr<WKUInt64Ref> callbackIDValue = adoptWK(WKUInt64Create(callbackID));
1094
1095     WKDictionarySetItem(testDictionary.get(), scriptKey.get(), scriptValue.get());
1096     WKDictionarySetItem(testDictionary.get(), callbackIDKey.get(), callbackIDValue.get());
1097
1098     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), testDictionary.get());
1099 }
1100
1101 void TestRunner::runUIScriptCallback(unsigned callbackID, JSStringRef result)
1102 {
1103     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
1104     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
1105
1106     JSValueRef resultValue = JSValueMakeString(context, result);
1107     callTestRunnerCallback(callbackID, 1, &resultValue);
1108 }
1109
1110 void TestRunner::installDidBeginSwipeCallback(JSValueRef callback)
1111 {
1112     cacheTestRunnerCallback(DidBeginSwipeCallbackID, callback);
1113 }
1114
1115 void TestRunner::installWillEndSwipeCallback(JSValueRef callback)
1116 {
1117     cacheTestRunnerCallback(WillEndSwipeCallbackID, callback);
1118 }
1119
1120 void TestRunner::installDidEndSwipeCallback(JSValueRef callback)
1121 {
1122     cacheTestRunnerCallback(DidEndSwipeCallbackID, callback);
1123 }
1124
1125 void TestRunner::installDidRemoveSwipeSnapshotCallback(JSValueRef callback)
1126 {
1127     cacheTestRunnerCallback(DidRemoveSwipeSnapshotCallbackID, callback);
1128 }
1129
1130 void TestRunner::callDidBeginSwipeCallback()
1131 {
1132     callTestRunnerCallback(DidBeginSwipeCallbackID);
1133 }
1134
1135 void TestRunner::callWillEndSwipeCallback()
1136 {
1137     callTestRunnerCallback(WillEndSwipeCallbackID);
1138 }
1139
1140 void TestRunner::callDidEndSwipeCallback()
1141 {
1142     callTestRunnerCallback(DidEndSwipeCallbackID);
1143 }
1144
1145 void TestRunner::callDidRemoveSwipeSnapshotCallback()
1146 {
1147     callTestRunnerCallback(DidRemoveSwipeSnapshotCallbackID);
1148 }
1149
1150 #if PLATFORM(MAC)
1151 void TestRunner::connectMockGamepad(unsigned index)
1152 {
1153     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("ConnectMockGamepad"));
1154     WKRetainPtr<WKTypeRef> messageBody(AdoptWK, WKUInt64Create(index));
1155
1156     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1157 }
1158
1159 void TestRunner::disconnectMockGamepad(unsigned index)
1160 {
1161     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("DisconnectMockGamepad"));
1162     WKRetainPtr<WKTypeRef> messageBody(AdoptWK, WKUInt64Create(index));
1163
1164     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1165 }
1166
1167 void TestRunner::setMockGamepadDetails(unsigned index, JSStringRef gamepadID, unsigned axisCount, unsigned buttonCount)
1168 {
1169     Vector<WKRetainPtr<WKStringRef>> keys;
1170     Vector<WKRetainPtr<WKTypeRef>> values;
1171
1172     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("GamepadID") });
1173     values.append(toWK(gamepadID));
1174
1175     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("GamepadIndex") });
1176     values.append({ AdoptWK, WKUInt64Create(index) });
1177
1178     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("AxisCount") });
1179     values.append({ AdoptWK, WKUInt64Create(axisCount) });
1180
1181     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("ButtonCount") });
1182     values.append({ AdoptWK, WKUInt64Create(buttonCount) });
1183
1184     Vector<WKStringRef> rawKeys;
1185     Vector<WKTypeRef> rawValues;
1186     rawKeys.resize(keys.size());
1187     rawValues.resize(values.size());
1188
1189     for (size_t i = 0; i < keys.size(); ++i) {
1190         rawKeys[i] = keys[i].get();
1191         rawValues[i] = values[i].get();
1192     }
1193
1194     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetMockGamepadDetails"));
1195     WKRetainPtr<WKDictionaryRef> messageBody(AdoptWK, WKDictionaryCreate(rawKeys.data(), rawValues.data(), rawKeys.size()));
1196
1197     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1198 }
1199
1200 void TestRunner::setMockGamepadAxisValue(unsigned index, unsigned axisIndex, double value)
1201 {
1202     Vector<WKRetainPtr<WKStringRef>> keys;
1203     Vector<WKRetainPtr<WKTypeRef>> values;
1204
1205     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("GamepadIndex") });
1206     values.append({ AdoptWK, WKUInt64Create(index) });
1207
1208     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("AxisIndex") });
1209     values.append({ AdoptWK, WKUInt64Create(axisIndex) });
1210
1211     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("Value") });
1212     values.append({ AdoptWK, WKDoubleCreate(value) });
1213
1214     Vector<WKStringRef> rawKeys;
1215     Vector<WKTypeRef> rawValues;
1216     rawKeys.resize(keys.size());
1217     rawValues.resize(values.size());
1218
1219     for (size_t i = 0; i < keys.size(); ++i) {
1220         rawKeys[i] = keys[i].get();
1221         rawValues[i] = values[i].get();
1222     }
1223
1224     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetMockGamepadAxisValue"));
1225     WKRetainPtr<WKDictionaryRef> messageBody(AdoptWK, WKDictionaryCreate(rawKeys.data(), rawValues.data(), rawKeys.size()));
1226
1227     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1228 }
1229
1230 void TestRunner::setMockGamepadButtonValue(unsigned index, unsigned buttonIndex, double value)
1231 {
1232     Vector<WKRetainPtr<WKStringRef>> keys;
1233     Vector<WKRetainPtr<WKTypeRef>> values;
1234
1235     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("GamepadIndex") });
1236     values.append({ AdoptWK, WKUInt64Create(index) });
1237
1238     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("ButtonIndex") });
1239     values.append({ AdoptWK, WKUInt64Create(buttonIndex) });
1240
1241     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("Value") });
1242     values.append({ AdoptWK, WKDoubleCreate(value) });
1243
1244     Vector<WKStringRef> rawKeys;
1245     Vector<WKTypeRef> rawValues;
1246     rawKeys.resize(keys.size());
1247     rawValues.resize(values.size());
1248
1249     for (size_t i = 0; i < keys.size(); ++i) {
1250         rawKeys[i] = keys[i].get();
1251         rawValues[i] = values[i].get();
1252     }
1253
1254     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetMockGamepadButtonValue"));
1255     WKRetainPtr<WKDictionaryRef> messageBody(AdoptWK, WKDictionaryCreate(rawKeys.data(), rawValues.data(), rawKeys.size()));
1256
1257     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1258 }
1259 #else
1260 void TestRunner::connectMockGamepad(unsigned)
1261 {
1262 }
1263
1264 void TestRunner::disconnectMockGamepad(unsigned)
1265 {
1266 }
1267
1268 void TestRunner::setMockGamepadDetails(unsigned, JSStringRef, unsigned, unsigned)
1269 {
1270 }
1271
1272 void TestRunner::setMockGamepadAxisValue(unsigned, unsigned, double)
1273 {
1274 }
1275
1276 void TestRunner::setMockGamepadButtonValue(unsigned, unsigned, double)
1277 {
1278 }
1279 #endif // PLATFORM(MAC)
1280
1281 } // namespace WTR