[EncryptedMedia] Make EME API runtime-enabled
[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::setDOMIteratorEnabled(bool enabled)
358 {
359     WKRetainPtr<WKStringRef> key(AdoptWK, WKStringCreateWithUTF8CString("WebKitDOMIteratorEnabled"));
360     auto& injectedBundle = InjectedBundle::singleton();
361     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), key.get(), enabled);
362 }
363
364 void TestRunner::setModernMediaControlsEnabled(bool enabled)
365 {
366     WKRetainPtr<WKStringRef> key(AdoptWK, WKStringCreateWithUTF8CString("WebKitModernMediaControlsEnabled"));
367     auto& injectedBundle = InjectedBundle::singleton();
368     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), key.get(), enabled);
369 }
370
371 void TestRunner::setWebGL2Enabled(bool enabled)
372 {
373     WKRetainPtr<WKStringRef> key(AdoptWK, WKStringCreateWithUTF8CString("WebKitWebGL2Enabled"));
374     auto& injectedBundle = InjectedBundle::singleton();
375     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), key.get(), enabled);
376 }
377
378 void TestRunner::setFetchAPIEnabled(bool enabled)
379 {
380     WKRetainPtr<WKStringRef> key(AdoptWK, WKStringCreateWithUTF8CString("WebKitFetchAPIEnabled"));
381     auto& injectedBundle = InjectedBundle::singleton();
382     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), key.get(), enabled);
383 }
384
385 void TestRunner::setDownloadAttributeEnabled(bool enabled)
386 {
387     WKRetainPtr<WKStringRef> key(AdoptWK, WKStringCreateWithUTF8CString("WebKitDownloadAttributeEnabled"));
388     auto& injectedBundle = InjectedBundle::singleton();
389     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), key.get(), enabled);
390 }
391
392 void TestRunner::setES6ModulesEnabled(bool enabled)
393 {
394     WKRetainPtr<WKStringRef> key(AdoptWK, WKStringCreateWithUTF8CString("WebKitES6ModulesEnabled"));
395     auto& injectedBundle = InjectedBundle::singleton();
396     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), key.get(), enabled);
397 }
398
399 void TestRunner::setEncryptedMediaAPIEnabled(bool enabled)
400 {
401     WKRetainPtr<WKStringRef> key(AdoptWK, WKStringCreateWithUTF8CString("WebKitEncryptedMediaAPIEnabled"));
402     auto& injectedBundle = InjectedBundle::singleton();
403     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), key.get(), enabled);
404 }
405
406 void TestRunner::setAllowsAnySSLCertificate(bool enabled)
407 {
408     InjectedBundle::singleton().setAllowsAnySSLCertificate(enabled);
409 }
410
411 void TestRunner::setAllowUniversalAccessFromFileURLs(bool enabled)
412 {
413     auto& injectedBundle = InjectedBundle::singleton();
414     WKBundleSetAllowUniversalAccessFromFileURLs(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
415 }
416
417 void TestRunner::setAllowFileAccessFromFileURLs(bool enabled)
418 {
419     auto& injectedBundle = InjectedBundle::singleton();
420     WKBundleSetAllowFileAccessFromFileURLs(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
421 }
422
423 void TestRunner::setNeedsStorageAccessFromFileURLsQuirk(bool needsQuirk)
424 {
425     auto& injectedBundle = InjectedBundle::singleton();
426     WKBundleSetAllowStorageAccessFromFileURLS(injectedBundle.bundle(), injectedBundle.pageGroup(), needsQuirk);
427 }
428     
429 void TestRunner::setPluginsEnabled(bool enabled)
430 {
431     auto& injectedBundle = InjectedBundle::singleton();
432     WKBundleSetPluginsEnabled(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
433 }
434
435 void TestRunner::setJavaScriptCanAccessClipboard(bool enabled)
436 {
437     auto& injectedBundle = InjectedBundle::singleton();
438     WKBundleSetJavaScriptCanAccessClipboard(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
439 }
440
441 void TestRunner::setPrivateBrowsingEnabled(bool enabled)
442 {
443     auto& injectedBundle = InjectedBundle::singleton();
444     WKBundleSetPrivateBrowsingEnabled(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
445 }
446
447 void TestRunner::setUseDashboardCompatibilityMode(bool enabled)
448 {
449 #if ENABLE(DASHBOARD_SUPPORT)
450     auto& injectedBundle = InjectedBundle::singleton();
451     WKBundleSetUseDashboardCompatibilityMode(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
452 #endif
453 }
454     
455 void TestRunner::setPopupBlockingEnabled(bool enabled)
456 {
457     auto& injectedBundle = InjectedBundle::singleton();
458     WKBundleSetPopupBlockingEnabled(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
459 }
460
461 void TestRunner::setAuthorAndUserStylesEnabled(bool enabled)
462 {
463     auto& injectedBundle = InjectedBundle::singleton();
464     WKBundleSetAuthorAndUserStylesEnabled(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
465 }
466
467 void TestRunner::addOriginAccessWhitelistEntry(JSStringRef sourceOrigin, JSStringRef destinationProtocol, JSStringRef destinationHost, bool allowDestinationSubdomains)
468 {
469     WKBundleAddOriginAccessWhitelistEntry(InjectedBundle::singleton().bundle(), toWK(sourceOrigin).get(), toWK(destinationProtocol).get(), toWK(destinationHost).get(), allowDestinationSubdomains);
470 }
471
472 void TestRunner::removeOriginAccessWhitelistEntry(JSStringRef sourceOrigin, JSStringRef destinationProtocol, JSStringRef destinationHost, bool allowDestinationSubdomains)
473 {
474     WKBundleRemoveOriginAccessWhitelistEntry(InjectedBundle::singleton().bundle(), toWK(sourceOrigin).get(), toWK(destinationProtocol).get(), toWK(destinationHost).get(), allowDestinationSubdomains);
475 }
476
477 bool TestRunner::isPageBoxVisible(int pageIndex)
478 {
479     auto& injectedBundle = InjectedBundle::singleton();
480     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(injectedBundle.page()->page());
481     return WKBundleIsPageBoxVisible(injectedBundle.bundle(), mainFrame, pageIndex);
482 }
483
484 void TestRunner::setValueForUser(JSContextRef context, JSValueRef element, JSStringRef value)
485 {
486     if (!element || !JSValueIsObject(context, element))
487         return;
488
489     WKRetainPtr<WKBundleNodeHandleRef> nodeHandle(AdoptWK, WKBundleNodeHandleCreate(context, const_cast<JSObjectRef>(element)));
490     WKBundleNodeHandleSetHTMLInputElementValueForUser(nodeHandle.get(), toWK(value).get());
491 }
492
493 void TestRunner::setAudioResult(JSContextRef context, JSValueRef data)
494 {
495     auto& injectedBundle = InjectedBundle::singleton();
496     // FIXME (123058): Use a JSC API to get buffer contents once such is exposed.
497     WKRetainPtr<WKDataRef> audioData(AdoptWK, WKBundleCreateWKDataFromUInt8Array(injectedBundle.bundle(), context, data));
498     injectedBundle.setAudioResult(audioData.get());
499     m_whatToDump = Audio;
500     m_dumpPixels = false;
501 }
502
503 unsigned TestRunner::windowCount()
504 {
505     return InjectedBundle::singleton().pageCount();
506 }
507
508 void TestRunner::clearBackForwardList()
509 {
510     WKBundleBackForwardListClear(WKBundlePageGetBackForwardList(InjectedBundle::singleton().page()->page()));
511 }
512
513 // Object Creation
514
515 void TestRunner::makeWindowObject(JSContextRef context, JSObjectRef windowObject, JSValueRef* exception)
516 {
517     setProperty(context, windowObject, "testRunner", this, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete, exception);
518 }
519
520 void TestRunner::showWebInspector()
521 {
522     WKBundleInspectorShow(WKBundlePageGetInspector(InjectedBundle::singleton().page()->page()));
523 }
524
525 void TestRunner::closeWebInspector()
526 {
527     WKBundleInspectorClose(WKBundlePageGetInspector(InjectedBundle::singleton().page()->page()));
528 }
529
530 void TestRunner::evaluateInWebInspector(JSStringRef script)
531 {
532     WKRetainPtr<WKStringRef> scriptWK = toWK(script);
533     WKBundleInspectorEvaluateScriptForTest(WKBundlePageGetInspector(InjectedBundle::singleton().page()->page()), scriptWK.get());
534 }
535
536 typedef WTF::HashMap<unsigned, WKRetainPtr<WKBundleScriptWorldRef> > WorldMap;
537 static WorldMap& worldMap()
538 {
539     static WorldMap& map = *new WorldMap;
540     return map;
541 }
542
543 unsigned TestRunner::worldIDForWorld(WKBundleScriptWorldRef world)
544 {
545     WorldMap::const_iterator end = worldMap().end();
546     for (WorldMap::const_iterator it = worldMap().begin(); it != end; ++it) {
547         if (it->value == world)
548             return it->key;
549     }
550
551     return 0;
552 }
553
554 void TestRunner::evaluateScriptInIsolatedWorld(JSContextRef context, unsigned worldID, JSStringRef script)
555 {
556     // A worldID of 0 always corresponds to a new world. Any other worldID corresponds to a world
557     // that is created once and cached forever.
558     WKRetainPtr<WKBundleScriptWorldRef> world;
559     if (!worldID)
560         world.adopt(WKBundleScriptWorldCreateWorld());
561     else {
562         WKRetainPtr<WKBundleScriptWorldRef>& worldSlot = worldMap().add(worldID, nullptr).iterator->value;
563         if (!worldSlot)
564             worldSlot.adopt(WKBundleScriptWorldCreateWorld());
565         world = worldSlot;
566     }
567
568     WKBundleFrameRef frame = WKBundleFrameForJavaScriptContext(context);
569     if (!frame)
570         frame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
571
572     JSGlobalContextRef jsContext = WKBundleFrameGetJavaScriptContextForWorld(frame, world.get());
573     JSEvaluateScript(jsContext, script, 0, 0, 0, 0); 
574 }
575
576 void TestRunner::setPOSIXLocale(JSStringRef locale)
577 {
578     char localeBuf[32];
579     JSStringGetUTF8CString(locale, localeBuf, sizeof(localeBuf));
580     setlocale(LC_ALL, localeBuf);
581 }
582
583 void TestRunner::setTextDirection(JSStringRef direction)
584 {
585     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
586     return WKBundleFrameSetTextDirection(mainFrame, toWK(direction).get());
587 }
588     
589 void TestRunner::setShouldStayOnPageAfterHandlingBeforeUnload(bool shouldStayOnPage)
590 {
591     InjectedBundle::singleton().postNewBeforeUnloadReturnValue(!shouldStayOnPage);
592 }
593
594 void TestRunner::setDefersLoading(bool shouldDeferLoading)
595 {
596     WKBundlePageSetDefersLoading(InjectedBundle::singleton().page()->page(), shouldDeferLoading);
597 }
598
599 void TestRunner::setPageVisibility(JSStringRef state)
600 {
601     InjectedBundle::singleton().setHidden(JSStringIsEqualToUTF8CString(state, "hidden") || JSStringIsEqualToUTF8CString(state, "prerender"));
602 }
603
604 void TestRunner::resetPageVisibility()
605 {
606     InjectedBundle::singleton().setHidden(false);
607 }
608
609 typedef WTF::HashMap<unsigned, JSValueRef> CallbackMap;
610 static CallbackMap& callbackMap()
611 {
612     static CallbackMap& map = *new CallbackMap;
613     return map;
614 }
615
616 enum {
617     AddChromeInputFieldCallbackID = 1,
618     RemoveChromeInputFieldCallbackID,
619     FocusWebViewCallbackID,
620     SetBackingScaleFactorCallbackID,
621     DidBeginSwipeCallbackID,
622     WillEndSwipeCallbackID,
623     DidEndSwipeCallbackID,
624     DidRemoveSwipeSnapshotCallbackID,
625     FirstUIScriptCallbackID = 100
626 };
627
628 static void cacheTestRunnerCallback(unsigned index, JSValueRef callback)
629 {
630     if (!callback)
631         return;
632
633     if (callbackMap().contains(index)) {
634         InjectedBundle::singleton().outputText(String::format("FAIL: Tried to install a second TestRunner callback for the same event (id %d)\n\n", index));
635         return;
636     }
637
638     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
639     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
640     JSValueProtect(context, callback);
641     callbackMap().add(index, callback);
642 }
643
644 static void callTestRunnerCallback(unsigned index, size_t argumentCount = 0, const JSValueRef arguments[] = nullptr)
645 {
646     if (!callbackMap().contains(index))
647         return;
648     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
649     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
650     JSObjectRef callback = JSValueToObject(context, callbackMap().take(index), 0);
651     JSObjectCallAsFunction(context, callback, JSContextGetGlobalObject(context), argumentCount, arguments, 0);
652     JSValueUnprotect(context, callback);
653 }
654
655 void TestRunner::clearTestRunnerCallbacks()
656 {
657     for (auto& iter : callbackMap()) {
658         WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
659         JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
660         JSObjectRef callback = JSValueToObject(context, iter.value, 0);
661         JSValueUnprotect(context, callback);
662     }
663
664     callbackMap().clear();
665 }
666
667 void TestRunner::accummulateLogsForChannel(JSStringRef)
668 {
669     // FIXME: Implement getting the call to all processes.
670 }
671
672 void TestRunner::addChromeInputField(JSValueRef callback)
673 {
674     cacheTestRunnerCallback(AddChromeInputFieldCallbackID, callback);
675     InjectedBundle::singleton().postAddChromeInputField();
676 }
677
678 void TestRunner::removeChromeInputField(JSValueRef callback)
679 {
680     cacheTestRunnerCallback(RemoveChromeInputFieldCallbackID, callback);
681     InjectedBundle::singleton().postRemoveChromeInputField();
682 }
683
684 void TestRunner::focusWebView(JSValueRef callback)
685 {
686     cacheTestRunnerCallback(FocusWebViewCallbackID, callback);
687     InjectedBundle::singleton().postFocusWebView();
688 }
689
690 void TestRunner::setBackingScaleFactor(double backingScaleFactor, JSValueRef callback)
691 {
692     cacheTestRunnerCallback(SetBackingScaleFactorCallbackID, callback);
693     InjectedBundle::singleton().postSetBackingScaleFactor(backingScaleFactor);
694 }
695
696 void TestRunner::setWindowIsKey(bool isKey)
697 {
698     InjectedBundle::singleton().postSetWindowIsKey(isKey);
699 }
700
701 void TestRunner::setViewSize(double width, double height)
702 {
703     InjectedBundle::singleton().postSetViewSize(width, height);
704 }
705
706 void TestRunner::callAddChromeInputFieldCallback()
707 {
708     callTestRunnerCallback(AddChromeInputFieldCallbackID);
709 }
710
711 void TestRunner::callRemoveChromeInputFieldCallback()
712 {
713     callTestRunnerCallback(RemoveChromeInputFieldCallbackID);
714 }
715
716 void TestRunner::callFocusWebViewCallback()
717 {
718     callTestRunnerCallback(FocusWebViewCallbackID);
719 }
720
721 void TestRunner::callSetBackingScaleFactorCallback()
722 {
723     callTestRunnerCallback(SetBackingScaleFactorCallbackID);
724 }
725
726 static inline bool toBool(JSStringRef value)
727 {
728     return JSStringIsEqualToUTF8CString(value, "true") || JSStringIsEqualToUTF8CString(value, "1");
729 }
730
731 void TestRunner::overridePreference(JSStringRef preference, JSStringRef value)
732 {
733     auto& injectedBundle = InjectedBundle::singleton();
734     // FIXME: handle non-boolean preferences.
735     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), toWK(preference).get(), toBool(value));
736 }
737
738 void TestRunner::setAlwaysAcceptCookies(bool accept)
739 {
740     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetAlwaysAcceptCookies"));
741
742     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(accept));
743
744     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
745 }
746
747 double TestRunner::preciseTime()
748 {
749     return currentTime();
750 }
751
752 void TestRunner::setUserStyleSheetEnabled(bool enabled)
753 {
754     m_userStyleSheetEnabled = enabled;
755
756     WKRetainPtr<WKStringRef> emptyUrl = adoptWK(WKStringCreateWithUTF8CString(""));
757     WKStringRef location = enabled ? m_userStyleSheetLocation.get() : emptyUrl.get();
758     auto& injectedBundle = InjectedBundle::singleton();
759     WKBundleSetUserStyleSheetLocation(injectedBundle.bundle(), injectedBundle.pageGroup(), location);
760 }
761
762 void TestRunner::setUserStyleSheetLocation(JSStringRef location)
763 {
764     m_userStyleSheetLocation = adoptWK(WKStringCreateWithJSString(location));
765
766     if (m_userStyleSheetEnabled)
767         setUserStyleSheetEnabled(true);
768 }
769
770 void TestRunner::setSpatialNavigationEnabled(bool enabled)
771 {
772     auto& injectedBundle = InjectedBundle::singleton();
773     WKBundleSetSpatialNavigationEnabled(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
774 }
775
776 void TestRunner::setTabKeyCyclesThroughElements(bool enabled)
777 {
778     auto& injectedBundle = InjectedBundle::singleton();
779     WKBundleSetTabKeyCyclesThroughElements(injectedBundle.bundle(), injectedBundle.page()->page(), enabled);
780 }
781
782 void TestRunner::setSerializeHTTPLoads()
783 {
784     // WK2 doesn't reorder loads.
785 }
786
787 void TestRunner::dispatchPendingLoadRequests()
788 {
789     // WK2 doesn't keep pending requests.
790 }
791
792 void TestRunner::setCacheModel(int model)
793 {
794     InjectedBundle::singleton().setCacheModel(model);
795 }
796
797 void TestRunner::setAsynchronousSpellCheckingEnabled(bool enabled)
798 {
799     auto& injectedBundle = InjectedBundle::singleton();
800     WKBundleSetAsynchronousSpellCheckingEnabled(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
801 }
802
803 void TestRunner::grantWebNotificationPermission(JSStringRef origin)
804 {
805     WKRetainPtr<WKStringRef> originWK = toWK(origin);
806     auto& injectedBundle = InjectedBundle::singleton();
807     WKBundleSetWebNotificationPermission(injectedBundle.bundle(), injectedBundle.page()->page(), originWK.get(), true);
808 }
809
810 void TestRunner::denyWebNotificationPermission(JSStringRef origin)
811 {
812     WKRetainPtr<WKStringRef> originWK = toWK(origin);
813     auto& injectedBundle = InjectedBundle::singleton();
814     WKBundleSetWebNotificationPermission(injectedBundle.bundle(), injectedBundle.page()->page(), originWK.get(), false);
815 }
816
817 void TestRunner::removeAllWebNotificationPermissions()
818 {
819     auto& injectedBundle = InjectedBundle::singleton();
820     WKBundleRemoveAllWebNotificationPermissions(injectedBundle.bundle(), injectedBundle.page()->page());
821 }
822
823 void TestRunner::simulateWebNotificationClick(JSValueRef notification)
824 {
825     auto& injectedBundle = InjectedBundle::singleton();
826     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(injectedBundle.page()->page());
827     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
828     uint64_t notificationID = WKBundleGetWebNotificationID(injectedBundle.bundle(), context, notification);
829     injectedBundle.postSimulateWebNotificationClick(notificationID);
830 }
831
832 void TestRunner::setGeolocationPermission(bool enabled)
833 {
834     // FIXME: this should be done by frame.
835     InjectedBundle::singleton().setGeolocationPermission(enabled);
836 }
837
838 bool TestRunner::isGeolocationProviderActive()
839 {
840     return InjectedBundle::singleton().isGeolocationProviderActive();
841 }
842
843 void TestRunner::setMockGeolocationPosition(double latitude, double longitude, double accuracy, JSValueRef jsAltitude, JSValueRef jsAltitudeAccuracy, JSValueRef jsHeading, JSValueRef jsSpeed)
844 {
845     auto& injectedBundle = InjectedBundle::singleton();
846     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(injectedBundle.page()->page());
847     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
848
849     bool providesAltitude = false;
850     double altitude = 0.;
851     if (!JSValueIsUndefined(context, jsAltitude)) {
852         providesAltitude = true;
853         altitude = JSValueToNumber(context, jsAltitude, 0);
854     }
855
856     bool providesAltitudeAccuracy = false;
857     double altitudeAccuracy = 0.;
858     if (!JSValueIsUndefined(context, jsAltitudeAccuracy)) {
859         providesAltitudeAccuracy = true;
860         altitudeAccuracy = JSValueToNumber(context, jsAltitudeAccuracy, 0);
861     }
862
863     bool providesHeading = false;
864     double heading = 0.;
865     if (!JSValueIsUndefined(context, jsHeading)) {
866         providesHeading = true;
867         heading = JSValueToNumber(context, jsHeading, 0);
868     }
869
870     bool providesSpeed = false;
871     double speed = 0.;
872     if (!JSValueIsUndefined(context, jsSpeed)) {
873         providesSpeed = true;
874         speed = JSValueToNumber(context, jsSpeed, 0);
875     }
876
877     injectedBundle.setMockGeolocationPosition(latitude, longitude, accuracy, providesAltitude, altitude, providesAltitudeAccuracy, altitudeAccuracy, providesHeading, heading, providesSpeed, speed);
878 }
879
880 void TestRunner::setMockGeolocationPositionUnavailableError(JSStringRef message)
881 {
882     WKRetainPtr<WKStringRef> messageWK = toWK(message);
883     InjectedBundle::singleton().setMockGeolocationPositionUnavailableError(messageWK.get());
884 }
885
886 void TestRunner::setUserMediaPermission(bool enabled)
887 {
888     // FIXME: this should be done by frame.
889     InjectedBundle::singleton().setUserMediaPermission(enabled);
890 }
891
892 void TestRunner::setUserMediaPermissionForOrigin(bool permission, JSStringRef origin, JSStringRef parentOrigin)
893 {
894     WKRetainPtr<WKStringRef> originWK = toWK(origin);
895     WKRetainPtr<WKStringRef> parentOriginWK = toWK(parentOrigin);
896     InjectedBundle::singleton().setUserMediaPermissionForOrigin(permission, originWK.get(), parentOriginWK.get());
897 }
898
899 bool TestRunner::callShouldCloseOnWebView()
900 {
901     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
902     return WKBundleFrameCallShouldCloseOnWebView(mainFrame);
903 }
904
905 void TestRunner::queueBackNavigation(unsigned howFarBackward)
906 {
907     InjectedBundle::singleton().queueBackNavigation(howFarBackward);
908 }
909
910 void TestRunner::queueForwardNavigation(unsigned howFarForward)
911 {
912     InjectedBundle::singleton().queueForwardNavigation(howFarForward);
913 }
914
915 void TestRunner::queueLoad(JSStringRef url, JSStringRef target, bool shouldOpenExternalURLs)
916 {
917     auto& injectedBundle = InjectedBundle::singleton();
918     WKRetainPtr<WKURLRef> baseURLWK(AdoptWK, WKBundleFrameCopyURL(WKBundlePageGetMainFrame(injectedBundle.page()->page())));
919     WKRetainPtr<WKURLRef> urlWK(AdoptWK, WKURLCreateWithBaseURL(baseURLWK.get(), toWTFString(toWK(url)).utf8().data()));
920     WKRetainPtr<WKStringRef> urlStringWK(AdoptWK, WKURLCopyString(urlWK.get()));
921
922     injectedBundle.queueLoad(urlStringWK.get(), toWK(target).get(), shouldOpenExternalURLs);
923 }
924
925 void TestRunner::queueLoadHTMLString(JSStringRef content, JSStringRef baseURL, JSStringRef unreachableURL)
926 {
927     WKRetainPtr<WKStringRef> contentWK = toWK(content);
928     WKRetainPtr<WKStringRef> baseURLWK = baseURL ? toWK(baseURL) : WKRetainPtr<WKStringRef>();
929     WKRetainPtr<WKStringRef> unreachableURLWK = unreachableURL ? toWK(unreachableURL) : WKRetainPtr<WKStringRef>();
930
931     InjectedBundle::singleton().queueLoadHTMLString(contentWK.get(), baseURLWK.get(), unreachableURLWK.get());
932 }
933
934 void TestRunner::queueReload()
935 {
936     InjectedBundle::singleton().queueReload();
937 }
938
939 void TestRunner::queueLoadingScript(JSStringRef script)
940 {
941     WKRetainPtr<WKStringRef> scriptWK = toWK(script);
942     InjectedBundle::singleton().queueLoadingScript(scriptWK.get());
943 }
944
945 void TestRunner::queueNonLoadingScript(JSStringRef script)
946 {
947     WKRetainPtr<WKStringRef> scriptWK = toWK(script);
948     InjectedBundle::singleton().queueNonLoadingScript(scriptWK.get());
949 }
950
951 void TestRunner::setRejectsProtectionSpaceAndContinueForAuthenticationChallenges(bool value)
952 {
953     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetRejectsProtectionSpaceAndContinueForAuthenticationChallenges"));
954     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(value));
955     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
956 }
957     
958 void TestRunner::setHandlesAuthenticationChallenges(bool handlesAuthenticationChallenges)
959 {
960     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetHandlesAuthenticationChallenges"));
961     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(handlesAuthenticationChallenges));
962     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
963 }
964
965 void TestRunner::setShouldLogCanAuthenticateAgainstProtectionSpace(bool value)
966 {
967     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetShouldLogCanAuthenticateAgainstProtectionSpace"));
968     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(value));
969     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
970 }
971
972 void TestRunner::setAuthenticationUsername(JSStringRef username)
973 {
974     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetAuthenticationUsername"));
975     WKRetainPtr<WKStringRef> messageBody(AdoptWK, WKStringCreateWithJSString(username));
976     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
977 }
978
979 void TestRunner::setAuthenticationPassword(JSStringRef password)
980 {
981     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetAuthenticationPassword"));
982     WKRetainPtr<WKStringRef> messageBody(AdoptWK, WKStringCreateWithJSString(password));
983     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
984 }
985
986 bool TestRunner::secureEventInputIsEnabled() const
987 {
988     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SecureEventInputIsEnabled"));
989     WKTypeRef returnData = 0;
990
991     WKBundlePagePostSynchronousMessageForTesting(InjectedBundle::singleton().page()->page(), messageName.get(), 0, &returnData);
992     return WKBooleanGetValue(static_cast<WKBooleanRef>(returnData));
993 }
994
995 void TestRunner::setBlockAllPlugins(bool shouldBlock)
996 {
997     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetBlockAllPlugins"));
998     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(shouldBlock));
999     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
1000 }
1001
1002 JSValueRef TestRunner::failNextNewCodeBlock()
1003 {
1004     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
1005     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
1006     return JSC::failNextNewCodeBlock(context);
1007 }
1008
1009 JSValueRef TestRunner::numberOfDFGCompiles(JSValueRef theFunction)
1010 {
1011     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
1012     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
1013     return JSC::numberOfDFGCompiles(context, theFunction);
1014 }
1015
1016 JSValueRef TestRunner::neverInlineFunction(JSValueRef theFunction)
1017 {
1018     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
1019     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
1020     return JSC::setNeverInline(context, theFunction);
1021 }
1022
1023 void TestRunner::setShouldDecideNavigationPolicyAfterDelay(bool value)
1024 {
1025     m_shouldDecideNavigationPolicyAfterDelay = value;
1026     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetShouldDecideNavigationPolicyAfterDelay"));
1027     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(value));
1028     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
1029 }
1030
1031 void TestRunner::setNavigationGesturesEnabled(bool value)
1032 {
1033     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetNavigationGesturesEnabled"));
1034     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(value));
1035     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
1036 }
1037
1038 void TestRunner::setIgnoresViewportScaleLimits(bool value)
1039 {
1040     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetIgnoresViewportScaleLimits"));
1041     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(value));
1042     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
1043 }
1044
1045 void TestRunner::setShouldDownloadUndisplayableMIMETypes(bool value)
1046 {
1047     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetShouldDownloadUndisplayableMIMETypes"));
1048     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(value));
1049     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
1050 }
1051
1052 static unsigned nextUIScriptCallbackID()
1053 {
1054     static unsigned callbackID = FirstUIScriptCallbackID;
1055     return callbackID++;
1056 }
1057
1058 void TestRunner::runUIScript(JSStringRef script, JSValueRef callback)
1059 {
1060     unsigned callbackID = nextUIScriptCallbackID();
1061     cacheTestRunnerCallback(callbackID, callback);
1062
1063     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("RunUIProcessScript"));
1064
1065     WKRetainPtr<WKMutableDictionaryRef> testDictionary(AdoptWK, WKMutableDictionaryCreate());
1066
1067     WKRetainPtr<WKStringRef> scriptKey(AdoptWK, WKStringCreateWithUTF8CString("Script"));
1068     WKRetainPtr<WKStringRef> scriptValue(AdoptWK, WKStringCreateWithJSString(script));
1069
1070     WKRetainPtr<WKStringRef> callbackIDKey(AdoptWK, WKStringCreateWithUTF8CString("CallbackID"));
1071     WKRetainPtr<WKUInt64Ref> callbackIDValue = adoptWK(WKUInt64Create(callbackID));
1072
1073     WKDictionarySetItem(testDictionary.get(), scriptKey.get(), scriptValue.get());
1074     WKDictionarySetItem(testDictionary.get(), callbackIDKey.get(), callbackIDValue.get());
1075
1076     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), testDictionary.get());
1077 }
1078
1079 void TestRunner::runUIScriptCallback(unsigned callbackID, JSStringRef result)
1080 {
1081     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
1082     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
1083
1084     JSValueRef resultValue = JSValueMakeString(context, result);
1085     callTestRunnerCallback(callbackID, 1, &resultValue);
1086 }
1087
1088 void TestRunner::installDidBeginSwipeCallback(JSValueRef callback)
1089 {
1090     cacheTestRunnerCallback(DidBeginSwipeCallbackID, callback);
1091 }
1092
1093 void TestRunner::installWillEndSwipeCallback(JSValueRef callback)
1094 {
1095     cacheTestRunnerCallback(WillEndSwipeCallbackID, callback);
1096 }
1097
1098 void TestRunner::installDidEndSwipeCallback(JSValueRef callback)
1099 {
1100     cacheTestRunnerCallback(DidEndSwipeCallbackID, callback);
1101 }
1102
1103 void TestRunner::installDidRemoveSwipeSnapshotCallback(JSValueRef callback)
1104 {
1105     cacheTestRunnerCallback(DidRemoveSwipeSnapshotCallbackID, callback);
1106 }
1107
1108 void TestRunner::callDidBeginSwipeCallback()
1109 {
1110     callTestRunnerCallback(DidBeginSwipeCallbackID);
1111 }
1112
1113 void TestRunner::callWillEndSwipeCallback()
1114 {
1115     callTestRunnerCallback(WillEndSwipeCallbackID);
1116 }
1117
1118 void TestRunner::callDidEndSwipeCallback()
1119 {
1120     callTestRunnerCallback(DidEndSwipeCallbackID);
1121 }
1122
1123 void TestRunner::callDidRemoveSwipeSnapshotCallback()
1124 {
1125     callTestRunnerCallback(DidRemoveSwipeSnapshotCallbackID);
1126 }
1127
1128 #if PLATFORM(MAC)
1129 void TestRunner::connectMockGamepad(unsigned index)
1130 {
1131     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("ConnectMockGamepad"));
1132     WKRetainPtr<WKTypeRef> messageBody(AdoptWK, WKUInt64Create(index));
1133
1134     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1135 }
1136
1137 void TestRunner::disconnectMockGamepad(unsigned index)
1138 {
1139     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("DisconnectMockGamepad"));
1140     WKRetainPtr<WKTypeRef> messageBody(AdoptWK, WKUInt64Create(index));
1141
1142     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1143 }
1144
1145 void TestRunner::setMockGamepadDetails(unsigned index, JSStringRef gamepadID, unsigned axisCount, unsigned buttonCount)
1146 {
1147     Vector<WKRetainPtr<WKStringRef>> keys;
1148     Vector<WKRetainPtr<WKTypeRef>> values;
1149
1150     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("GamepadID") });
1151     values.append(toWK(gamepadID));
1152
1153     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("GamepadIndex") });
1154     values.append({ AdoptWK, WKUInt64Create(index) });
1155
1156     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("AxisCount") });
1157     values.append({ AdoptWK, WKUInt64Create(axisCount) });
1158
1159     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("ButtonCount") });
1160     values.append({ AdoptWK, WKUInt64Create(buttonCount) });
1161
1162     Vector<WKStringRef> rawKeys;
1163     Vector<WKTypeRef> rawValues;
1164     rawKeys.resize(keys.size());
1165     rawValues.resize(values.size());
1166
1167     for (size_t i = 0; i < keys.size(); ++i) {
1168         rawKeys[i] = keys[i].get();
1169         rawValues[i] = values[i].get();
1170     }
1171
1172     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetMockGamepadDetails"));
1173     WKRetainPtr<WKDictionaryRef> messageBody(AdoptWK, WKDictionaryCreate(rawKeys.data(), rawValues.data(), rawKeys.size()));
1174
1175     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1176 }
1177
1178 void TestRunner::setMockGamepadAxisValue(unsigned index, unsigned axisIndex, double value)
1179 {
1180     Vector<WKRetainPtr<WKStringRef>> keys;
1181     Vector<WKRetainPtr<WKTypeRef>> values;
1182
1183     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("GamepadIndex") });
1184     values.append({ AdoptWK, WKUInt64Create(index) });
1185
1186     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("AxisIndex") });
1187     values.append({ AdoptWK, WKUInt64Create(axisIndex) });
1188
1189     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("Value") });
1190     values.append({ AdoptWK, WKDoubleCreate(value) });
1191
1192     Vector<WKStringRef> rawKeys;
1193     Vector<WKTypeRef> rawValues;
1194     rawKeys.resize(keys.size());
1195     rawValues.resize(values.size());
1196
1197     for (size_t i = 0; i < keys.size(); ++i) {
1198         rawKeys[i] = keys[i].get();
1199         rawValues[i] = values[i].get();
1200     }
1201
1202     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetMockGamepadAxisValue"));
1203     WKRetainPtr<WKDictionaryRef> messageBody(AdoptWK, WKDictionaryCreate(rawKeys.data(), rawValues.data(), rawKeys.size()));
1204
1205     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1206 }
1207
1208 void TestRunner::setMockGamepadButtonValue(unsigned index, unsigned buttonIndex, double value)
1209 {
1210     Vector<WKRetainPtr<WKStringRef>> keys;
1211     Vector<WKRetainPtr<WKTypeRef>> values;
1212
1213     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("GamepadIndex") });
1214     values.append({ AdoptWK, WKUInt64Create(index) });
1215
1216     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("ButtonIndex") });
1217     values.append({ AdoptWK, WKUInt64Create(buttonIndex) });
1218
1219     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("Value") });
1220     values.append({ AdoptWK, WKDoubleCreate(value) });
1221
1222     Vector<WKStringRef> rawKeys;
1223     Vector<WKTypeRef> rawValues;
1224     rawKeys.resize(keys.size());
1225     rawValues.resize(values.size());
1226
1227     for (size_t i = 0; i < keys.size(); ++i) {
1228         rawKeys[i] = keys[i].get();
1229         rawValues[i] = values[i].get();
1230     }
1231
1232     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetMockGamepadButtonValue"));
1233     WKRetainPtr<WKDictionaryRef> messageBody(AdoptWK, WKDictionaryCreate(rawKeys.data(), rawValues.data(), rawKeys.size()));
1234
1235     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1236 }
1237 #else
1238 void TestRunner::connectMockGamepad(unsigned)
1239 {
1240 }
1241
1242 void TestRunner::disconnectMockGamepad(unsigned)
1243 {
1244 }
1245
1246 void TestRunner::setMockGamepadDetails(unsigned, JSStringRef, unsigned, unsigned)
1247 {
1248 }
1249
1250 void TestRunner::setMockGamepadAxisValue(unsigned, unsigned, double)
1251 {
1252 }
1253
1254 void TestRunner::setMockGamepadButtonValue(unsigned, unsigned, double)
1255 {
1256 }
1257 #endif // PLATFORM(MAC)
1258
1259 } // namespace WTR