[Cache API] Add Cache and CacheStorage IDL definitions
[WebKit-https.git] / Tools / WebKitTestRunner / InjectedBundle / TestRunner.cpp
1 /*
2  * Copyright (C) 2010-2017 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "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 <WebCore/ResourceLoadObserver.h>
37 #include <WebKit/WKBundle.h>
38 #include <WebKit/WKBundleBackForwardList.h>
39 #include <WebKit/WKBundleFrame.h>
40 #include <WebKit/WKBundleFramePrivate.h>
41 #include <WebKit/WKBundleInspector.h>
42 #include <WebKit/WKBundleNodeHandlePrivate.h>
43 #include <WebKit/WKBundlePage.h>
44 #include <WebKit/WKBundlePagePrivate.h>
45 #include <WebKit/WKBundlePrivate.h>
46 #include <WebKit/WKBundleScriptWorld.h>
47 #include <WebKit/WKData.h>
48 #include <WebKit/WKPagePrivate.h>
49 #include <WebKit/WKRetainPtr.h>
50 #include <WebKit/WKSerializedScriptValue.h>
51 #include <WebKit/WebKit2_C.h>
52 #include <wtf/CurrentTime.h>
53 #include <wtf/HashMap.h>
54 #include <wtf/StdLibExtras.h>
55 #include <wtf/text/CString.h>
56 #include <wtf/text/StringBuilder.h>
57
58 namespace WTR {
59
60 Ref<TestRunner> TestRunner::create()
61 {
62     return adoptRef(*new TestRunner);
63 }
64
65 TestRunner::TestRunner()
66     : m_whatToDump(RenderTree)
67     , m_shouldDumpAllFrameScrollPositions(false)
68     , m_shouldDumpBackForwardListsForAllWindows(false)
69     , m_shouldAllowEditing(true)
70     , m_shouldCloseExtraWindows(false)
71     , m_dumpEditingCallbacks(false)
72     , m_dumpStatusCallbacks(false)
73     , m_dumpTitleChanges(false)
74     , m_dumpPixels(true)
75     , m_dumpSelectionRect(false)
76     , m_dumpFullScreenCallbacks(false)
77     , m_dumpFrameLoadCallbacks(false)
78     , m_dumpProgressFinishedCallback(false)
79     , m_dumpResourceLoadCallbacks(false)
80     , m_dumpResourceResponseMIMETypes(false)
81     , m_dumpWillCacheResponse(false)
82     , m_dumpApplicationCacheDelegateCallbacks(false)
83     , m_dumpDatabaseCallbacks(false)
84     , m_disallowIncreaseForApplicationCacheQuota(false)
85     , m_waitToDump(false)
86     , m_testRepaint(false)
87     , m_testRepaintSweepHorizontally(false)
88     , m_isPrinting(false)
89     , m_willSendRequestReturnsNull(false)
90     , m_willSendRequestReturnsNullOnRedirect(false)
91     , m_shouldStopProvisionalFrameLoads(false)
92     , m_policyDelegateEnabled(false)
93     , m_policyDelegatePermissive(false)
94     , m_globalFlag(false)
95     , m_customFullScreenBehavior(false)
96     , m_timeout(30000)
97     , m_databaseDefaultQuota(-1)
98     , m_databaseMaxQuota(-1)
99     , m_userStyleSheetEnabled(false)
100     , m_userStyleSheetLocation(adoptWK(WKStringCreateWithUTF8CString("")))
101 #if PLATFORM(GTK) || PLATFORM(WPE)
102     , m_waitToDumpWatchdogTimer(RunLoop::main(), this, &TestRunner::waitToDumpWatchdogTimerFired)
103 #endif
104 {
105     platformInitialize();
106 }
107
108 TestRunner::~TestRunner()
109 {
110 }
111
112 JSClassRef TestRunner::wrapperClass()
113 {
114     return JSTestRunner::testRunnerClass();
115 }
116
117 void TestRunner::display()
118 {
119     WKBundlePageRef page = InjectedBundle::singleton().page()->page();
120     WKBundlePageForceRepaint(page);
121 }
122
123 void TestRunner::displayAndTrackRepaints()
124 {
125     WKBundlePageRef page = InjectedBundle::singleton().page()->page();
126     WKBundlePageForceRepaint(page);
127     WKBundlePageSetTracksRepaints(page, true);
128     WKBundlePageResetTrackedRepaints(page);
129 }
130
131 void TestRunner::dumpAsText(bool dumpPixels)
132 {
133     if (m_whatToDump < MainFrameText)
134         m_whatToDump = MainFrameText;
135     m_dumpPixels = dumpPixels;
136 }
137
138 void TestRunner::setCustomPolicyDelegate(bool enabled, bool permissive)
139 {
140     m_policyDelegateEnabled = enabled;
141     m_policyDelegatePermissive = permissive;
142
143     InjectedBundle::singleton().setCustomPolicyDelegate(enabled, permissive);
144 }
145
146 void TestRunner::waitForPolicyDelegate()
147 {
148     setCustomPolicyDelegate(true);
149     waitUntilDone();
150 }
151
152 void TestRunner::waitUntilDownloadFinished()
153 {
154     m_shouldFinishAfterDownload = true;
155     waitUntilDone();
156 }
157
158 void TestRunner::waitUntilDone()
159 {
160     m_waitToDump = true;
161     if (InjectedBundle::singleton().useWaitToDumpWatchdogTimer())
162         initializeWaitToDumpWatchdogTimerIfNeeded();
163 }
164
165 void TestRunner::waitToDumpWatchdogTimerFired()
166 {
167     invalidateWaitToDumpWatchdogTimer();
168     auto& injectedBundle = InjectedBundle::singleton();
169 #if PLATFORM(COCOA)
170     char buffer[1024];
171     snprintf(buffer, sizeof(buffer), "#PID UNRESPONSIVE - %s (pid %d)\n", getprogname(), getpid());
172     injectedBundle.outputText(buffer);
173 #endif
174     injectedBundle.outputText("FAIL: Timed out waiting for notifyDone to be called\n\n");
175     injectedBundle.done();
176 }
177
178 void TestRunner::notifyDone()
179 {
180     auto& injectedBundle = InjectedBundle::singleton();
181     if (!injectedBundle.isTestRunning())
182         return;
183
184     if (m_waitToDump && !injectedBundle.topLoadingFrame())
185         injectedBundle.page()->dump();
186
187     // We don't call invalidateWaitToDumpWatchdogTimer() here, even if we continue to wait for a load to finish.
188     // The test is still subject to timeout checking - it is better to detect an async timeout inside WebKitTestRunner
189     // than to let webkitpy do that, because WebKitTestRunner will dump partial results.
190
191     m_waitToDump = false;
192 }
193
194 unsigned TestRunner::imageCountInGeneralPasteboard() const
195 {
196     return InjectedBundle::singleton().imageCountInGeneralPasteboard();
197 }
198
199 void TestRunner::addUserScript(JSStringRef source, bool runAtStart, bool allFrames)
200 {
201     WKRetainPtr<WKStringRef> sourceWK = toWK(source);
202
203     WKBundlePageAddUserScript(InjectedBundle::singleton().page()->page(), sourceWK.get(),
204         (runAtStart ? kWKInjectAtDocumentStart : kWKInjectAtDocumentEnd),
205         (allFrames ? kWKInjectInAllFrames : kWKInjectInTopFrameOnly));
206 }
207
208 void TestRunner::addUserStyleSheet(JSStringRef source, bool allFrames)
209 {
210     WKRetainPtr<WKStringRef> sourceWK = toWK(source);
211
212     WKBundlePageAddUserStyleSheet(InjectedBundle::singleton().page()->page(), sourceWK.get(),
213         (allFrames ? kWKInjectInAllFrames : kWKInjectInTopFrameOnly));
214 }
215
216 void TestRunner::keepWebHistory()
217 {
218     InjectedBundle::singleton().postSetAddsVisitedLinks(true);
219 }
220
221 void TestRunner::execCommand(JSStringRef name, JSStringRef argument)
222 {
223     WKBundlePageExecuteEditingCommand(InjectedBundle::singleton().page()->page(), toWK(name).get(), toWK(argument).get());
224 }
225
226 bool TestRunner::findString(JSStringRef target, JSValueRef optionsArrayAsValue)
227 {
228     WKFindOptions options = 0;
229
230     auto& injectedBundle = InjectedBundle::singleton();
231     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(injectedBundle.page()->page());
232     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
233     JSRetainPtr<JSStringRef> lengthPropertyName(Adopt, JSStringCreateWithUTF8CString("length"));
234     JSObjectRef optionsArray = JSValueToObject(context, optionsArrayAsValue, 0);
235     JSValueRef lengthValue = JSObjectGetProperty(context, optionsArray, lengthPropertyName.get(), 0);
236     if (!JSValueIsNumber(context, lengthValue))
237         return false;
238
239     size_t length = static_cast<size_t>(JSValueToNumber(context, lengthValue, 0));
240     for (size_t i = 0; i < length; ++i) {
241         JSValueRef value = JSObjectGetPropertyAtIndex(context, optionsArray, i, 0);
242         if (!JSValueIsString(context, value))
243             continue;
244
245         JSRetainPtr<JSStringRef> optionName(Adopt, JSValueToStringCopy(context, value, 0));
246
247         if (JSStringIsEqualToUTF8CString(optionName.get(), "CaseInsensitive"))
248             options |= kWKFindOptionsCaseInsensitive;
249         else if (JSStringIsEqualToUTF8CString(optionName.get(), "AtWordStarts"))
250             options |= kWKFindOptionsAtWordStarts;
251         else if (JSStringIsEqualToUTF8CString(optionName.get(), "TreatMedialCapitalAsWordStart"))
252             options |= kWKFindOptionsTreatMedialCapitalAsWordStart;
253         else if (JSStringIsEqualToUTF8CString(optionName.get(), "Backwards"))
254             options |= kWKFindOptionsBackwards;
255         else if (JSStringIsEqualToUTF8CString(optionName.get(), "WrapAround"))
256             options |= kWKFindOptionsWrapAround;
257         else if (JSStringIsEqualToUTF8CString(optionName.get(), "StartInSelection")) {
258             // FIXME: No kWKFindOptionsStartInSelection.
259         }
260     }
261
262     return WKBundlePageFindString(injectedBundle.page()->page(), toWK(target).get(), options);
263 }
264
265 void TestRunner::clearAllDatabases()
266 {
267     WKBundleClearAllDatabases(InjectedBundle::singleton().bundle());
268
269     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("DeleteAllIndexedDatabases"));
270     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(true));
271
272     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
273 }
274
275 void TestRunner::setDatabaseQuota(uint64_t quota)
276 {
277     return WKBundleSetDatabaseQuota(InjectedBundle::singleton().bundle(), quota);
278 }
279
280 void TestRunner::clearAllApplicationCaches()
281 {
282     WKBundlePageClearApplicationCache(InjectedBundle::singleton().page()->page());
283 }
284
285 void TestRunner::clearApplicationCacheForOrigin(JSStringRef origin)
286 {
287     WKBundlePageClearApplicationCacheForOrigin(InjectedBundle::singleton().page()->page(), toWK(origin).get());
288 }
289
290 void TestRunner::setAppCacheMaximumSize(uint64_t size)
291 {
292     WKBundlePageSetAppCacheMaximumSize(InjectedBundle::singleton().page()->page(), size);
293 }
294
295 long long TestRunner::applicationCacheDiskUsageForOrigin(JSStringRef origin)
296 {
297     return WKBundlePageGetAppCacheUsageForOrigin(InjectedBundle::singleton().page()->page(), toWK(origin).get());
298 }
299
300 void TestRunner::disallowIncreaseForApplicationCacheQuota()
301 {
302     m_disallowIncreaseForApplicationCacheQuota = true;
303 }
304
305 static inline JSValueRef stringArrayToJS(JSContextRef context, WKArrayRef strings)
306 {
307     const size_t count = WKArrayGetSize(strings);
308
309     JSValueRef arrayResult = JSObjectMakeArray(context, 0, 0, 0);
310     JSObjectRef arrayObj = JSValueToObject(context, arrayResult, 0);
311     for (size_t i = 0; i < count; ++i) {
312         WKStringRef stringRef = static_cast<WKStringRef>(WKArrayGetItemAtIndex(strings, i));
313         JSRetainPtr<JSStringRef> stringJS = toJS(stringRef);
314         JSObjectSetPropertyAtIndex(context, arrayObj, i, JSValueMakeString(context, stringJS.get()), 0);
315     }
316
317     return arrayResult;
318 }
319
320 JSValueRef TestRunner::originsWithApplicationCache()
321 {
322     WKBundlePageRef page = InjectedBundle::singleton().page()->page();
323
324     WKRetainPtr<WKArrayRef> origins(AdoptWK, WKBundlePageCopyOriginsWithApplicationCache(page));
325
326     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(page);
327     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
328
329     return stringArrayToJS(context, origins.get());
330 }
331
332 bool TestRunner::isCommandEnabled(JSStringRef name)
333 {
334     return WKBundlePageIsEditingCommandEnabled(InjectedBundle::singleton().page()->page(), toWK(name).get());
335 }
336
337 void TestRunner::setCanOpenWindows(bool)
338 {
339     // The test plugins/get-url-with-blank-target.html requires that the embedding client forbid
340     // opening windows (by omitting a call to this function) so as to test that NPN_GetURL()
341     // with a blank target will return an error.
342     //
343     // It is not clear if we should implement this functionality or remove it and plugins/get-url-with-blank-target.html
344     // per the remark in <https://trac.webkit.org/changeset/64504/trunk/LayoutTests/platform/mac-wk2/Skipped>.
345     // For now, just ignore this setting.
346 }
347
348 void TestRunner::setXSSAuditorEnabled(bool enabled)
349 {
350     WKRetainPtr<WKStringRef> key(AdoptWK, WKStringCreateWithUTF8CString("WebKitXSSAuditorEnabled"));
351     auto& injectedBundle = InjectedBundle::singleton();
352     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), key.get(), enabled);
353 }
354
355 void TestRunner::setMediaDevicesEnabled(bool enabled)
356 {
357     WKRetainPtr<WKStringRef> key(AdoptWK, WKStringCreateWithUTF8CString("WebKitMediaDevicesEnabled"));
358     auto& injectedBundle = InjectedBundle::singleton();
359     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), key.get(), enabled);
360 }
361
362 void TestRunner::setWebRTCLegacyAPIEnabled(bool enabled)
363 {
364     WKRetainPtr<WKStringRef> key(AdoptWK, WKStringCreateWithUTF8CString("WebKitWebRTCLegacyAPIEnabled"));
365     auto& injectedBundle = InjectedBundle::singleton();
366     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), key.get(), enabled);
367 }
368
369 void TestRunner::setModernMediaControlsEnabled(bool enabled)
370 {
371     WKRetainPtr<WKStringRef> key(AdoptWK, WKStringCreateWithUTF8CString("WebKitModernMediaControlsEnabled"));
372     auto& injectedBundle = InjectedBundle::singleton();
373     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), key.get(), enabled);
374 }
375
376 void TestRunner::setWebGL2Enabled(bool enabled)
377 {
378     WKRetainPtr<WKStringRef> key(AdoptWK, WKStringCreateWithUTF8CString("WebKitWebGL2Enabled"));
379     auto& injectedBundle = InjectedBundle::singleton();
380     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), key.get(), enabled);
381 }
382
383 void TestRunner::setWebGPUEnabled(bool enabled)
384 {
385     WKRetainPtr<WKStringRef> key(AdoptWK, WKStringCreateWithUTF8CString("WebKitWebGPUEnabled"));
386     auto& injectedBundle = InjectedBundle::singleton();
387     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), key.get(), enabled);
388 }
389
390 void TestRunner::setCacheAPIEnabled(bool enabled)
391 {
392     WKRetainPtr<WKStringRef> key(AdoptWK, WKStringCreateWithUTF8CString("WebKitCacheAPIEnabled"));
393     auto& injectedBundle = InjectedBundle::singleton();
394     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), key.get(), enabled);
395 }
396
397 void TestRunner::setWritableStreamAPIEnabled(bool enabled)
398 {
399     WKRetainPtr<WKStringRef> key(AdoptWK, WKStringCreateWithUTF8CString("WebKitWritableStreamAPIEnabled"));
400     auto& injectedBundle = InjectedBundle::singleton();
401     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), key.get(), enabled);
402 }
403
404 void TestRunner::setReadableByteStreamAPIEnabled(bool enabled)
405 {
406     WKRetainPtr<WKStringRef> key(AdoptWK, WKStringCreateWithUTF8CString("WebKitReadableByteStreamAPIEnabled"));
407     auto& injectedBundle = InjectedBundle::singleton();
408     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), key.get(), enabled);
409 }
410
411 void TestRunner::setEncryptedMediaAPIEnabled(bool enabled)
412 {
413     WKRetainPtr<WKStringRef> key(AdoptWK, WKStringCreateWithUTF8CString("WebKitEncryptedMediaAPIEnabled"));
414     auto& injectedBundle = InjectedBundle::singleton();
415     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), key.get(), enabled);
416 }
417
418 void TestRunner::setAllowsAnySSLCertificate(bool enabled)
419 {
420     auto& injectedBundle = InjectedBundle::singleton();
421     injectedBundle.setAllowsAnySSLCertificate(enabled);
422
423     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetAllowsAnySSLCertificate"));
424     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(enabled));
425     WKBundlePagePostSynchronousMessageForTesting(injectedBundle.page()->page(), messageName.get(), messageBody.get(), nullptr);
426 }
427
428 void TestRunner::setAllowUniversalAccessFromFileURLs(bool enabled)
429 {
430     auto& injectedBundle = InjectedBundle::singleton();
431     WKBundleSetAllowUniversalAccessFromFileURLs(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
432 }
433
434 void TestRunner::setAllowFileAccessFromFileURLs(bool enabled)
435 {
436     auto& injectedBundle = InjectedBundle::singleton();
437     WKBundleSetAllowFileAccessFromFileURLs(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
438 }
439
440 void TestRunner::setNeedsStorageAccessFromFileURLsQuirk(bool needsQuirk)
441 {
442     auto& injectedBundle = InjectedBundle::singleton();
443     WKBundleSetAllowStorageAccessFromFileURLS(injectedBundle.bundle(), injectedBundle.pageGroup(), needsQuirk);
444 }
445     
446 void TestRunner::setPluginsEnabled(bool enabled)
447 {
448     WKRetainPtr<WKStringRef> key(AdoptWK, WKStringCreateWithUTF8CString("WebKitPluginsEnabled"));
449     auto& injectedBundle = InjectedBundle::singleton();
450     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), key.get(), enabled);
451 }
452
453 void TestRunner::setJavaScriptCanAccessClipboard(bool enabled)
454 {
455     auto& injectedBundle = InjectedBundle::singleton();
456     WKBundleSetJavaScriptCanAccessClipboard(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
457 }
458
459 void TestRunner::setPrivateBrowsingEnabled(bool enabled)
460 {
461     auto& injectedBundle = InjectedBundle::singleton();
462     WKBundleSetPrivateBrowsingEnabled(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
463 }
464
465 void TestRunner::setUseDashboardCompatibilityMode(bool enabled)
466 {
467 #if ENABLE(DASHBOARD_SUPPORT)
468     auto& injectedBundle = InjectedBundle::singleton();
469     WKBundleSetUseDashboardCompatibilityMode(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
470 #endif
471 }
472     
473 void TestRunner::setPopupBlockingEnabled(bool enabled)
474 {
475     auto& injectedBundle = InjectedBundle::singleton();
476     WKBundleSetPopupBlockingEnabled(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
477 }
478
479 void TestRunner::setAuthorAndUserStylesEnabled(bool enabled)
480 {
481     auto& injectedBundle = InjectedBundle::singleton();
482     WKBundleSetAuthorAndUserStylesEnabled(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
483 }
484
485 void TestRunner::addOriginAccessWhitelistEntry(JSStringRef sourceOrigin, JSStringRef destinationProtocol, JSStringRef destinationHost, bool allowDestinationSubdomains)
486 {
487     WKBundleAddOriginAccessWhitelistEntry(InjectedBundle::singleton().bundle(), toWK(sourceOrigin).get(), toWK(destinationProtocol).get(), toWK(destinationHost).get(), allowDestinationSubdomains);
488 }
489
490 void TestRunner::removeOriginAccessWhitelistEntry(JSStringRef sourceOrigin, JSStringRef destinationProtocol, JSStringRef destinationHost, bool allowDestinationSubdomains)
491 {
492     WKBundleRemoveOriginAccessWhitelistEntry(InjectedBundle::singleton().bundle(), toWK(sourceOrigin).get(), toWK(destinationProtocol).get(), toWK(destinationHost).get(), allowDestinationSubdomains);
493 }
494
495 bool TestRunner::isPageBoxVisible(int pageIndex)
496 {
497     auto& injectedBundle = InjectedBundle::singleton();
498     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(injectedBundle.page()->page());
499     return WKBundleIsPageBoxVisible(injectedBundle.bundle(), mainFrame, pageIndex);
500 }
501
502 void TestRunner::setValueForUser(JSContextRef context, JSValueRef element, JSStringRef value)
503 {
504     if (!element || !JSValueIsObject(context, element))
505         return;
506
507     WKRetainPtr<WKBundleNodeHandleRef> nodeHandle(AdoptWK, WKBundleNodeHandleCreate(context, const_cast<JSObjectRef>(element)));
508     WKBundleNodeHandleSetHTMLInputElementValueForUser(nodeHandle.get(), toWK(value).get());
509 }
510
511 void TestRunner::setAudioResult(JSContextRef context, JSValueRef data)
512 {
513     auto& injectedBundle = InjectedBundle::singleton();
514     // FIXME (123058): Use a JSC API to get buffer contents once such is exposed.
515     WKRetainPtr<WKDataRef> audioData(AdoptWK, WKBundleCreateWKDataFromUInt8Array(injectedBundle.bundle(), context, data));
516     injectedBundle.setAudioResult(audioData.get());
517     m_whatToDump = Audio;
518     m_dumpPixels = false;
519 }
520
521 unsigned TestRunner::windowCount()
522 {
523     return InjectedBundle::singleton().pageCount();
524 }
525
526 void TestRunner::clearBackForwardList()
527 {
528     WKBundleBackForwardListClear(WKBundlePageGetBackForwardList(InjectedBundle::singleton().page()->page()));
529 }
530
531 // Object Creation
532
533 void TestRunner::makeWindowObject(JSContextRef context, JSObjectRef windowObject, JSValueRef* exception)
534 {
535     setProperty(context, windowObject, "testRunner", this, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete, exception);
536 }
537
538 void TestRunner::showWebInspector()
539 {
540     WKBundleInspectorShow(WKBundlePageGetInspector(InjectedBundle::singleton().page()->page()));
541 }
542
543 void TestRunner::closeWebInspector()
544 {
545     WKBundleInspectorClose(WKBundlePageGetInspector(InjectedBundle::singleton().page()->page()));
546 }
547
548 void TestRunner::evaluateInWebInspector(JSStringRef script)
549 {
550     WKRetainPtr<WKStringRef> scriptWK = toWK(script);
551     WKBundleInspectorEvaluateScriptForTest(WKBundlePageGetInspector(InjectedBundle::singleton().page()->page()), scriptWK.get());
552 }
553
554 typedef WTF::HashMap<unsigned, WKRetainPtr<WKBundleScriptWorldRef> > WorldMap;
555 static WorldMap& worldMap()
556 {
557     static WorldMap& map = *new WorldMap;
558     return map;
559 }
560
561 unsigned TestRunner::worldIDForWorld(WKBundleScriptWorldRef world)
562 {
563     WorldMap::const_iterator end = worldMap().end();
564     for (WorldMap::const_iterator it = worldMap().begin(); it != end; ++it) {
565         if (it->value == world)
566             return it->key;
567     }
568
569     return 0;
570 }
571
572 void TestRunner::evaluateScriptInIsolatedWorld(JSContextRef context, unsigned worldID, JSStringRef script)
573 {
574     // A worldID of 0 always corresponds to a new world. Any other worldID corresponds to a world
575     // that is created once and cached forever.
576     WKRetainPtr<WKBundleScriptWorldRef> world;
577     if (!worldID)
578         world.adopt(WKBundleScriptWorldCreateWorld());
579     else {
580         WKRetainPtr<WKBundleScriptWorldRef>& worldSlot = worldMap().add(worldID, nullptr).iterator->value;
581         if (!worldSlot)
582             worldSlot.adopt(WKBundleScriptWorldCreateWorld());
583         world = worldSlot;
584     }
585
586     WKBundleFrameRef frame = WKBundleFrameForJavaScriptContext(context);
587     if (!frame)
588         frame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
589
590     JSGlobalContextRef jsContext = WKBundleFrameGetJavaScriptContextForWorld(frame, world.get());
591     JSEvaluateScript(jsContext, script, 0, 0, 0, 0); 
592 }
593
594 void TestRunner::setPOSIXLocale(JSStringRef locale)
595 {
596     char localeBuf[32];
597     JSStringGetUTF8CString(locale, localeBuf, sizeof(localeBuf));
598     setlocale(LC_ALL, localeBuf);
599 }
600
601 void TestRunner::setTextDirection(JSStringRef direction)
602 {
603     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
604     return WKBundleFrameSetTextDirection(mainFrame, toWK(direction).get());
605 }
606     
607 void TestRunner::setShouldStayOnPageAfterHandlingBeforeUnload(bool shouldStayOnPage)
608 {
609     InjectedBundle::singleton().postNewBeforeUnloadReturnValue(!shouldStayOnPage);
610 }
611
612 void TestRunner::setDefersLoading(bool shouldDeferLoading)
613 {
614     WKBundlePageSetDefersLoading(InjectedBundle::singleton().page()->page(), shouldDeferLoading);
615 }
616
617 void TestRunner::setPageVisibility(JSStringRef state)
618 {
619     InjectedBundle::singleton().setHidden(JSStringIsEqualToUTF8CString(state, "hidden") || JSStringIsEqualToUTF8CString(state, "prerender"));
620 }
621
622 void TestRunner::resetPageVisibility()
623 {
624     InjectedBundle::singleton().setHidden(false);
625 }
626
627 typedef WTF::HashMap<unsigned, JSValueRef> CallbackMap;
628 static CallbackMap& callbackMap()
629 {
630     static CallbackMap& map = *new CallbackMap;
631     return map;
632 }
633
634 enum {
635     AddChromeInputFieldCallbackID = 1,
636     RemoveChromeInputFieldCallbackID,
637     FocusWebViewCallbackID,
638     SetBackingScaleFactorCallbackID,
639     DidBeginSwipeCallbackID,
640     WillEndSwipeCallbackID,
641     DidEndSwipeCallbackID,
642     DidRemoveSwipeSnapshotCallbackID,
643     StatisticsDidModifyDataRecordsCallbackID,
644     StatisticsDidScanDataRecordsCallbackID,
645     StatisticsDidRunTelemetryCallbackID,
646     DidRemoveAllSessionCredentialsCallbackID,
647     FirstUIScriptCallbackID = 100
648 };
649
650 static void cacheTestRunnerCallback(unsigned index, JSValueRef callback)
651 {
652     if (!callback)
653         return;
654
655     if (callbackMap().contains(index)) {
656         InjectedBundle::singleton().outputText(String::format("FAIL: Tried to install a second TestRunner callback for the same event (id %d)\n\n", index));
657         return;
658     }
659
660     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
661     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
662     JSValueProtect(context, callback);
663     callbackMap().add(index, callback);
664 }
665
666 static void callTestRunnerCallback(unsigned index, size_t argumentCount = 0, const JSValueRef arguments[] = nullptr)
667 {
668     if (!callbackMap().contains(index))
669         return;
670     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
671     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
672     JSObjectRef callback = JSValueToObject(context, callbackMap().take(index), 0);
673     JSObjectCallAsFunction(context, callback, JSContextGetGlobalObject(context), argumentCount, arguments, 0);
674     JSValueUnprotect(context, callback);
675 }
676
677 void TestRunner::clearTestRunnerCallbacks()
678 {
679     for (auto& iter : callbackMap()) {
680         WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
681         JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
682         JSObjectRef callback = JSValueToObject(context, iter.value, 0);
683         JSValueUnprotect(context, callback);
684     }
685
686     callbackMap().clear();
687 }
688
689 void TestRunner::accummulateLogsForChannel(JSStringRef)
690 {
691     // FIXME: Implement getting the call to all processes.
692 }
693
694 void TestRunner::addChromeInputField(JSValueRef callback)
695 {
696     cacheTestRunnerCallback(AddChromeInputFieldCallbackID, callback);
697     InjectedBundle::singleton().postAddChromeInputField();
698 }
699
700 void TestRunner::removeChromeInputField(JSValueRef callback)
701 {
702     cacheTestRunnerCallback(RemoveChromeInputFieldCallbackID, callback);
703     InjectedBundle::singleton().postRemoveChromeInputField();
704 }
705
706 void TestRunner::focusWebView(JSValueRef callback)
707 {
708     cacheTestRunnerCallback(FocusWebViewCallbackID, callback);
709     InjectedBundle::singleton().postFocusWebView();
710 }
711
712 void TestRunner::setBackingScaleFactor(double backingScaleFactor, JSValueRef callback)
713 {
714     cacheTestRunnerCallback(SetBackingScaleFactorCallbackID, callback);
715     InjectedBundle::singleton().postSetBackingScaleFactor(backingScaleFactor);
716 }
717
718 void TestRunner::setWindowIsKey(bool isKey)
719 {
720     InjectedBundle::singleton().postSetWindowIsKey(isKey);
721 }
722
723 void TestRunner::setViewSize(double width, double height)
724 {
725     InjectedBundle::singleton().postSetViewSize(width, height);
726 }
727
728 void TestRunner::callAddChromeInputFieldCallback()
729 {
730     callTestRunnerCallback(AddChromeInputFieldCallbackID);
731 }
732
733 void TestRunner::callRemoveChromeInputFieldCallback()
734 {
735     callTestRunnerCallback(RemoveChromeInputFieldCallbackID);
736 }
737
738 void TestRunner::callFocusWebViewCallback()
739 {
740     callTestRunnerCallback(FocusWebViewCallbackID);
741 }
742
743 void TestRunner::callSetBackingScaleFactorCallback()
744 {
745     callTestRunnerCallback(SetBackingScaleFactorCallbackID);
746 }
747
748 static inline bool toBool(JSStringRef value)
749 {
750     return JSStringIsEqualToUTF8CString(value, "true") || JSStringIsEqualToUTF8CString(value, "1");
751 }
752
753 void TestRunner::overridePreference(JSStringRef preference, JSStringRef value)
754 {
755     auto& injectedBundle = InjectedBundle::singleton();
756     // FIXME: handle non-boolean preferences.
757     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), toWK(preference).get(), toBool(value));
758 }
759
760 void TestRunner::setAlwaysAcceptCookies(bool accept)
761 {
762     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetAlwaysAcceptCookies"));
763
764     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(accept));
765
766     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
767 }
768
769 void TestRunner::setCookieStoragePartitioningEnabled(bool enabled)
770 {
771     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetCookieStoragePartitioningEnabled"));
772
773     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(enabled));
774
775     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
776 }
777
778 double TestRunner::preciseTime()
779 {
780     return currentTime();
781 }
782
783 void TestRunner::setUserStyleSheetEnabled(bool enabled)
784 {
785     m_userStyleSheetEnabled = enabled;
786
787     WKRetainPtr<WKStringRef> emptyUrl = adoptWK(WKStringCreateWithUTF8CString(""));
788     WKStringRef location = enabled ? m_userStyleSheetLocation.get() : emptyUrl.get();
789     auto& injectedBundle = InjectedBundle::singleton();
790     WKBundleSetUserStyleSheetLocation(injectedBundle.bundle(), injectedBundle.pageGroup(), location);
791 }
792
793 void TestRunner::setUserStyleSheetLocation(JSStringRef location)
794 {
795     m_userStyleSheetLocation = adoptWK(WKStringCreateWithJSString(location));
796
797     if (m_userStyleSheetEnabled)
798         setUserStyleSheetEnabled(true);
799 }
800
801 void TestRunner::setSpatialNavigationEnabled(bool enabled)
802 {
803     auto& injectedBundle = InjectedBundle::singleton();
804     WKBundleSetSpatialNavigationEnabled(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
805 }
806
807 void TestRunner::setTabKeyCyclesThroughElements(bool enabled)
808 {
809     auto& injectedBundle = InjectedBundle::singleton();
810     WKBundleSetTabKeyCyclesThroughElements(injectedBundle.bundle(), injectedBundle.page()->page(), enabled);
811 }
812
813 void TestRunner::setSerializeHTTPLoads()
814 {
815     // WK2 doesn't reorder loads.
816 }
817
818 void TestRunner::dispatchPendingLoadRequests()
819 {
820     // WK2 doesn't keep pending requests.
821 }
822
823 void TestRunner::setCacheModel(int model)
824 {
825     InjectedBundle::singleton().setCacheModel(model);
826 }
827
828 void TestRunner::setAsynchronousSpellCheckingEnabled(bool enabled)
829 {
830     auto& injectedBundle = InjectedBundle::singleton();
831     WKBundleSetAsynchronousSpellCheckingEnabled(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
832 }
833
834 void TestRunner::grantWebNotificationPermission(JSStringRef origin)
835 {
836     WKRetainPtr<WKStringRef> originWK = toWK(origin);
837     auto& injectedBundle = InjectedBundle::singleton();
838     WKBundleSetWebNotificationPermission(injectedBundle.bundle(), injectedBundle.page()->page(), originWK.get(), true);
839 }
840
841 void TestRunner::denyWebNotificationPermission(JSStringRef origin)
842 {
843     WKRetainPtr<WKStringRef> originWK = toWK(origin);
844     auto& injectedBundle = InjectedBundle::singleton();
845     WKBundleSetWebNotificationPermission(injectedBundle.bundle(), injectedBundle.page()->page(), originWK.get(), false);
846 }
847
848 void TestRunner::removeAllWebNotificationPermissions()
849 {
850     auto& injectedBundle = InjectedBundle::singleton();
851     WKBundleRemoveAllWebNotificationPermissions(injectedBundle.bundle(), injectedBundle.page()->page());
852 }
853
854 void TestRunner::simulateWebNotificationClick(JSValueRef notification)
855 {
856     auto& injectedBundle = InjectedBundle::singleton();
857     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(injectedBundle.page()->page());
858     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
859     uint64_t notificationID = WKBundleGetWebNotificationID(injectedBundle.bundle(), context, notification);
860     injectedBundle.postSimulateWebNotificationClick(notificationID);
861 }
862
863 void TestRunner::setGeolocationPermission(bool enabled)
864 {
865     // FIXME: this should be done by frame.
866     InjectedBundle::singleton().setGeolocationPermission(enabled);
867 }
868
869 bool TestRunner::isGeolocationProviderActive()
870 {
871     return InjectedBundle::singleton().isGeolocationProviderActive();
872 }
873
874 void TestRunner::setMockGeolocationPosition(double latitude, double longitude, double accuracy, JSValueRef jsAltitude, JSValueRef jsAltitudeAccuracy, JSValueRef jsHeading, JSValueRef jsSpeed)
875 {
876     auto& injectedBundle = InjectedBundle::singleton();
877     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(injectedBundle.page()->page());
878     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
879
880     bool providesAltitude = false;
881     double altitude = 0.;
882     if (!JSValueIsUndefined(context, jsAltitude)) {
883         providesAltitude = true;
884         altitude = JSValueToNumber(context, jsAltitude, 0);
885     }
886
887     bool providesAltitudeAccuracy = false;
888     double altitudeAccuracy = 0.;
889     if (!JSValueIsUndefined(context, jsAltitudeAccuracy)) {
890         providesAltitudeAccuracy = true;
891         altitudeAccuracy = JSValueToNumber(context, jsAltitudeAccuracy, 0);
892     }
893
894     bool providesHeading = false;
895     double heading = 0.;
896     if (!JSValueIsUndefined(context, jsHeading)) {
897         providesHeading = true;
898         heading = JSValueToNumber(context, jsHeading, 0);
899     }
900
901     bool providesSpeed = false;
902     double speed = 0.;
903     if (!JSValueIsUndefined(context, jsSpeed)) {
904         providesSpeed = true;
905         speed = JSValueToNumber(context, jsSpeed, 0);
906     }
907
908     injectedBundle.setMockGeolocationPosition(latitude, longitude, accuracy, providesAltitude, altitude, providesAltitudeAccuracy, altitudeAccuracy, providesHeading, heading, providesSpeed, speed);
909 }
910
911 void TestRunner::setMockGeolocationPositionUnavailableError(JSStringRef message)
912 {
913     WKRetainPtr<WKStringRef> messageWK = toWK(message);
914     InjectedBundle::singleton().setMockGeolocationPositionUnavailableError(messageWK.get());
915 }
916
917 void TestRunner::setUserMediaPermission(bool enabled)
918 {
919     // FIXME: this should be done by frame.
920     InjectedBundle::singleton().setUserMediaPermission(enabled);
921 }
922
923 void TestRunner::resetUserMediaPermission()
924 {
925     // FIXME: this should be done by frame.
926     InjectedBundle::singleton().resetUserMediaPermission();
927 }
928
929 void TestRunner::setUserMediaPersistentPermissionForOrigin(bool permission, JSStringRef origin, JSStringRef parentOrigin)
930 {
931     WKRetainPtr<WKStringRef> originWK = toWK(origin);
932     WKRetainPtr<WKStringRef> parentOriginWK = toWK(parentOrigin);
933     InjectedBundle::singleton().setUserMediaPersistentPermissionForOrigin(permission, originWK.get(), parentOriginWK.get());
934 }
935
936 unsigned TestRunner::userMediaPermissionRequestCountForOrigin(JSStringRef origin, JSStringRef parentOrigin) const
937 {
938     WKRetainPtr<WKStringRef> originWK = toWK(origin);
939     WKRetainPtr<WKStringRef> parentOriginWK = toWK(parentOrigin);
940     return InjectedBundle::singleton().userMediaPermissionRequestCountForOrigin(originWK.get(), parentOriginWK.get());
941 }
942
943 void TestRunner::resetUserMediaPermissionRequestCountForOrigin(JSStringRef origin, JSStringRef parentOrigin)
944 {
945     WKRetainPtr<WKStringRef> originWK = toWK(origin);
946     WKRetainPtr<WKStringRef> parentOriginWK = toWK(parentOrigin);
947     InjectedBundle::singleton().resetUserMediaPermissionRequestCountForOrigin(originWK.get(), parentOriginWK.get());
948 }
949
950 bool TestRunner::callShouldCloseOnWebView()
951 {
952     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
953     return WKBundleFrameCallShouldCloseOnWebView(mainFrame);
954 }
955
956 void TestRunner::queueBackNavigation(unsigned howFarBackward)
957 {
958     InjectedBundle::singleton().queueBackNavigation(howFarBackward);
959 }
960
961 void TestRunner::queueForwardNavigation(unsigned howFarForward)
962 {
963     InjectedBundle::singleton().queueForwardNavigation(howFarForward);
964 }
965
966 void TestRunner::queueLoad(JSStringRef url, JSStringRef target, bool shouldOpenExternalURLs)
967 {
968     auto& injectedBundle = InjectedBundle::singleton();
969     WKRetainPtr<WKURLRef> baseURLWK(AdoptWK, WKBundleFrameCopyURL(WKBundlePageGetMainFrame(injectedBundle.page()->page())));
970     WKRetainPtr<WKURLRef> urlWK(AdoptWK, WKURLCreateWithBaseURL(baseURLWK.get(), toWTFString(toWK(url)).utf8().data()));
971     WKRetainPtr<WKStringRef> urlStringWK(AdoptWK, WKURLCopyString(urlWK.get()));
972
973     injectedBundle.queueLoad(urlStringWK.get(), toWK(target).get(), shouldOpenExternalURLs);
974 }
975
976 void TestRunner::queueLoadHTMLString(JSStringRef content, JSStringRef baseURL, JSStringRef unreachableURL)
977 {
978     WKRetainPtr<WKStringRef> contentWK = toWK(content);
979     WKRetainPtr<WKStringRef> baseURLWK = baseURL ? toWK(baseURL) : WKRetainPtr<WKStringRef>();
980     WKRetainPtr<WKStringRef> unreachableURLWK = unreachableURL ? toWK(unreachableURL) : WKRetainPtr<WKStringRef>();
981
982     InjectedBundle::singleton().queueLoadHTMLString(contentWK.get(), baseURLWK.get(), unreachableURLWK.get());
983 }
984
985 void TestRunner::queueReload()
986 {
987     InjectedBundle::singleton().queueReload();
988 }
989
990 void TestRunner::queueLoadingScript(JSStringRef script)
991 {
992     WKRetainPtr<WKStringRef> scriptWK = toWK(script);
993     InjectedBundle::singleton().queueLoadingScript(scriptWK.get());
994 }
995
996 void TestRunner::queueNonLoadingScript(JSStringRef script)
997 {
998     WKRetainPtr<WKStringRef> scriptWK = toWK(script);
999     InjectedBundle::singleton().queueNonLoadingScript(scriptWK.get());
1000 }
1001
1002 void TestRunner::setRejectsProtectionSpaceAndContinueForAuthenticationChallenges(bool value)
1003 {
1004     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetRejectsProtectionSpaceAndContinueForAuthenticationChallenges"));
1005     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(value));
1006     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
1007 }
1008     
1009 void TestRunner::setHandlesAuthenticationChallenges(bool handlesAuthenticationChallenges)
1010 {
1011     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetHandlesAuthenticationChallenges"));
1012     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(handlesAuthenticationChallenges));
1013     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
1014 }
1015
1016 void TestRunner::setShouldLogCanAuthenticateAgainstProtectionSpace(bool value)
1017 {
1018     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetShouldLogCanAuthenticateAgainstProtectionSpace"));
1019     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(value));
1020     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
1021 }
1022
1023 void TestRunner::setAuthenticationUsername(JSStringRef username)
1024 {
1025     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetAuthenticationUsername"));
1026     WKRetainPtr<WKStringRef> messageBody(AdoptWK, WKStringCreateWithJSString(username));
1027     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
1028 }
1029
1030 void TestRunner::setAuthenticationPassword(JSStringRef password)
1031 {
1032     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetAuthenticationPassword"));
1033     WKRetainPtr<WKStringRef> messageBody(AdoptWK, WKStringCreateWithJSString(password));
1034     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
1035 }
1036
1037 bool TestRunner::secureEventInputIsEnabled() const
1038 {
1039     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SecureEventInputIsEnabled"));
1040     WKTypeRef returnData = 0;
1041
1042     WKBundlePagePostSynchronousMessageForTesting(InjectedBundle::singleton().page()->page(), messageName.get(), 0, &returnData);
1043     return WKBooleanGetValue(static_cast<WKBooleanRef>(returnData));
1044 }
1045
1046 void TestRunner::setBlockAllPlugins(bool shouldBlock)
1047 {
1048     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetBlockAllPlugins"));
1049     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(shouldBlock));
1050     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
1051 }
1052
1053 JSValueRef TestRunner::failNextNewCodeBlock()
1054 {
1055     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
1056     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
1057     return JSC::failNextNewCodeBlock(context);
1058 }
1059
1060 JSValueRef TestRunner::numberOfDFGCompiles(JSValueRef theFunction)
1061 {
1062     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
1063     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
1064     return JSC::numberOfDFGCompiles(context, theFunction);
1065 }
1066
1067 JSValueRef TestRunner::neverInlineFunction(JSValueRef theFunction)
1068 {
1069     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
1070     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
1071     return JSC::setNeverInline(context, theFunction);
1072 }
1073
1074 void TestRunner::setShouldDecideNavigationPolicyAfterDelay(bool value)
1075 {
1076     m_shouldDecideNavigationPolicyAfterDelay = value;
1077     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetShouldDecideNavigationPolicyAfterDelay"));
1078     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(value));
1079     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
1080 }
1081
1082 void TestRunner::setNavigationGesturesEnabled(bool value)
1083 {
1084     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetNavigationGesturesEnabled"));
1085     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(value));
1086     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
1087 }
1088
1089 void TestRunner::setIgnoresViewportScaleLimits(bool value)
1090 {
1091     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetIgnoresViewportScaleLimits"));
1092     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(value));
1093     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
1094 }
1095
1096 void TestRunner::setShouldDownloadUndisplayableMIMETypes(bool value)
1097 {
1098     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetShouldDownloadUndisplayableMIMETypes"));
1099     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(value));
1100     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
1101 }
1102
1103 void TestRunner::terminateNetworkProcess()
1104 {
1105     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("TerminateNetworkProcess"));
1106     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), nullptr);
1107 }
1108
1109 static unsigned nextUIScriptCallbackID()
1110 {
1111     static unsigned callbackID = FirstUIScriptCallbackID;
1112     return callbackID++;
1113 }
1114
1115 void TestRunner::runUIScript(JSStringRef script, JSValueRef callback)
1116 {
1117     unsigned callbackID = nextUIScriptCallbackID();
1118     cacheTestRunnerCallback(callbackID, callback);
1119
1120     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("RunUIProcessScript"));
1121
1122     WKRetainPtr<WKMutableDictionaryRef> testDictionary(AdoptWK, WKMutableDictionaryCreate());
1123
1124     WKRetainPtr<WKStringRef> scriptKey(AdoptWK, WKStringCreateWithUTF8CString("Script"));
1125     WKRetainPtr<WKStringRef> scriptValue(AdoptWK, WKStringCreateWithJSString(script));
1126
1127     WKRetainPtr<WKStringRef> callbackIDKey(AdoptWK, WKStringCreateWithUTF8CString("CallbackID"));
1128     WKRetainPtr<WKUInt64Ref> callbackIDValue = adoptWK(WKUInt64Create(callbackID));
1129
1130     WKDictionarySetItem(testDictionary.get(), scriptKey.get(), scriptValue.get());
1131     WKDictionarySetItem(testDictionary.get(), callbackIDKey.get(), callbackIDValue.get());
1132
1133     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), testDictionary.get());
1134 }
1135
1136 void TestRunner::runUIScriptCallback(unsigned callbackID, JSStringRef result)
1137 {
1138     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
1139     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
1140
1141     JSValueRef resultValue = JSValueMakeString(context, result);
1142     callTestRunnerCallback(callbackID, 1, &resultValue);
1143 }
1144
1145 void TestRunner::installDidBeginSwipeCallback(JSValueRef callback)
1146 {
1147     cacheTestRunnerCallback(DidBeginSwipeCallbackID, callback);
1148 }
1149
1150 void TestRunner::installWillEndSwipeCallback(JSValueRef callback)
1151 {
1152     cacheTestRunnerCallback(WillEndSwipeCallbackID, callback);
1153 }
1154
1155 void TestRunner::installDidEndSwipeCallback(JSValueRef callback)
1156 {
1157     cacheTestRunnerCallback(DidEndSwipeCallbackID, callback);
1158 }
1159
1160 void TestRunner::installDidRemoveSwipeSnapshotCallback(JSValueRef callback)
1161 {
1162     cacheTestRunnerCallback(DidRemoveSwipeSnapshotCallbackID, callback);
1163 }
1164
1165 void TestRunner::callDidBeginSwipeCallback()
1166 {
1167     callTestRunnerCallback(DidBeginSwipeCallbackID);
1168 }
1169
1170 void TestRunner::callWillEndSwipeCallback()
1171 {
1172     callTestRunnerCallback(WillEndSwipeCallbackID);
1173 }
1174
1175 void TestRunner::callDidEndSwipeCallback()
1176 {
1177     callTestRunnerCallback(DidEndSwipeCallbackID);
1178 }
1179
1180 void TestRunner::callDidRemoveSwipeSnapshotCallback()
1181 {
1182     callTestRunnerCallback(DidRemoveSwipeSnapshotCallbackID);
1183 }
1184
1185 void TestRunner::setStatisticsLastSeen(JSStringRef hostName, double seconds)
1186 {
1187     Vector<WKRetainPtr<WKStringRef>> keys;
1188     Vector<WKRetainPtr<WKTypeRef>> values;
1189     
1190     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("HostName") });
1191     values.append({ AdoptWK, WKStringCreateWithJSString(hostName) });
1192     
1193     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("Value") });
1194     values.append({ AdoptWK, WKDoubleCreate(seconds) });
1195     
1196     Vector<WKStringRef> rawKeys(keys.size());
1197     Vector<WKTypeRef> rawValues(values.size());
1198     
1199     for (size_t i = 0; i < keys.size(); ++i) {
1200         rawKeys[i] = keys[i].get();
1201         rawValues[i] = values[i].get();
1202     }
1203     
1204     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetStatisticsLastSeen"));
1205     WKRetainPtr<WKDictionaryRef> messageBody(AdoptWK, WKDictionaryCreate(rawKeys.data(), rawValues.data(), rawKeys.size()));
1206     
1207     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1208 }
1209     
1210 void TestRunner::setStatisticsPrevalentResource(JSStringRef hostName, bool value)
1211 {
1212     Vector<WKRetainPtr<WKStringRef>> keys;
1213     Vector<WKRetainPtr<WKTypeRef>> values;
1214
1215     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("HostName") });
1216     values.append({ AdoptWK, WKStringCreateWithJSString(hostName) });
1217     
1218     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("Value") });
1219     values.append({ AdoptWK, WKBooleanCreate(value) });
1220     
1221     Vector<WKStringRef> rawKeys;
1222     Vector<WKTypeRef> rawValues;
1223     rawKeys.resize(keys.size());
1224     rawValues.resize(values.size());
1225     
1226     for (size_t i = 0; i < keys.size(); ++i) {
1227         rawKeys[i] = keys[i].get();
1228         rawValues[i] = values[i].get();
1229     }
1230     
1231     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetStatisticsPrevalentResource"));
1232     WKRetainPtr<WKDictionaryRef> messageBody(AdoptWK, WKDictionaryCreate(rawKeys.data(), rawValues.data(), rawKeys.size()));
1233
1234     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1235 }
1236
1237 bool TestRunner::isStatisticsPrevalentResource(JSStringRef hostName)
1238 {
1239     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("IsStatisticsPrevalentResource"));
1240     WKRetainPtr<WKStringRef> messageBody(AdoptWK, WKStringCreateWithJSString(hostName));
1241     WKTypeRef returnData = 0;
1242     WKBundlePagePostSynchronousMessageForTesting(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get(), &returnData);
1243     return WKBooleanGetValue(static_cast<WKBooleanRef>(returnData));
1244 }
1245
1246 void TestRunner::setStatisticsHasHadUserInteraction(JSStringRef hostName, bool value)
1247 {
1248     Vector<WKRetainPtr<WKStringRef>> keys;
1249     Vector<WKRetainPtr<WKTypeRef>> values;
1250     
1251     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("HostName") });
1252     values.append({ AdoptWK, WKStringCreateWithJSString(hostName) });
1253     
1254     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("Value") });
1255     values.append({ AdoptWK, WKBooleanCreate(value) });
1256     
1257     Vector<WKStringRef> rawKeys;
1258     Vector<WKTypeRef> rawValues;
1259     rawKeys.resize(keys.size());
1260     rawValues.resize(values.size());
1261     
1262     for (size_t i = 0; i < keys.size(); ++i) {
1263         rawKeys[i] = keys[i].get();
1264         rawValues[i] = values[i].get();
1265     }
1266     
1267     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetStatisticsHasHadUserInteraction"));
1268     WKRetainPtr<WKDictionaryRef> messageBody(AdoptWK, WKDictionaryCreate(rawKeys.data(), rawValues.data(), rawKeys.size()));
1269     
1270     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1271 }
1272
1273 bool TestRunner::isStatisticsHasHadUserInteraction(JSStringRef hostName)
1274 {
1275     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("IsStatisticsHasHadUserInteraction"));
1276     WKRetainPtr<WKStringRef> messageBody(AdoptWK, WKStringCreateWithJSString(hostName));
1277     WKTypeRef returnData = 0;
1278     WKBundlePagePostSynchronousMessageForTesting(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get(), &returnData);
1279     return WKBooleanGetValue(static_cast<WKBooleanRef>(returnData));
1280 }
1281
1282 void TestRunner::setStatisticsGrandfathered(JSStringRef hostName, bool value)
1283 {
1284     Vector<WKRetainPtr<WKStringRef>> keys;
1285     Vector<WKRetainPtr<WKTypeRef>> values;
1286     
1287     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("HostName") });
1288     values.append({ AdoptWK, WKStringCreateWithJSString(hostName) });
1289     
1290     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("Value") });
1291     values.append({ AdoptWK, WKBooleanCreate(value) });
1292     
1293     Vector<WKStringRef> rawKeys;
1294     Vector<WKTypeRef> rawValues;
1295     rawKeys.resize(keys.size());
1296     rawValues.resize(values.size());
1297     
1298     for (size_t i = 0; i < keys.size(); ++i) {
1299         rawKeys[i] = keys[i].get();
1300         rawValues[i] = values[i].get();
1301     }
1302     
1303     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetStatisticsGrandfathered"));
1304     WKRetainPtr<WKDictionaryRef> messageBody(AdoptWK, WKDictionaryCreate(rawKeys.data(), rawValues.data(), rawKeys.size()));
1305     
1306     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1307 }
1308     
1309 bool TestRunner::isStatisticsGrandfathered(JSStringRef hostName)
1310 {
1311     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("IsStatisticsGrandfathered"));
1312     WKRetainPtr<WKStringRef> messageBody(AdoptWK, WKStringCreateWithJSString(hostName));
1313     WKTypeRef returnData = 0;
1314     WKBundlePagePostSynchronousMessageForTesting(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get(), &returnData);
1315     return WKBooleanGetValue(static_cast<WKBooleanRef>(returnData));
1316 }
1317
1318 void TestRunner::setStatisticsSubframeUnderTopFrameOrigin(JSStringRef hostName, JSStringRef topFrameHostName)
1319 {
1320     Vector<WKRetainPtr<WKStringRef>> keys;
1321     Vector<WKRetainPtr<WKTypeRef>> values;
1322     
1323     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("HostName") });
1324     values.append({ AdoptWK, WKStringCreateWithJSString(hostName) });
1325     
1326     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("TopFrameHostName") });
1327     values.append({ AdoptWK, WKStringCreateWithJSString(topFrameHostName) });
1328     
1329     Vector<WKStringRef> rawKeys(keys.size());
1330     Vector<WKTypeRef> rawValues(values.size());
1331     
1332     for (size_t i = 0; i < keys.size(); ++i) {
1333         rawKeys[i] = keys[i].get();
1334         rawValues[i] = values[i].get();
1335     }
1336     
1337     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetStatisticsSubframeUnderTopFrameOrigin"));
1338     WKRetainPtr<WKDictionaryRef> messageBody(AdoptWK, WKDictionaryCreate(rawKeys.data(), rawValues.data(), rawKeys.size()));
1339     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1340 }
1341
1342 void TestRunner::setStatisticsSubresourceUnderTopFrameOrigin(JSStringRef hostName, JSStringRef topFrameHostName)
1343 {
1344     Vector<WKRetainPtr<WKStringRef>> keys;
1345     Vector<WKRetainPtr<WKTypeRef>> values;
1346     
1347     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("HostName") });
1348     values.append({ AdoptWK, WKStringCreateWithJSString(hostName) });
1349     
1350     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("TopFrameHostName") });
1351     values.append({ AdoptWK, WKStringCreateWithJSString(topFrameHostName) });
1352     
1353     Vector<WKStringRef> rawKeys(keys.size());
1354     Vector<WKTypeRef> rawValues(values.size());
1355     
1356     for (size_t i = 0; i < keys.size(); ++i) {
1357         rawKeys[i] = keys[i].get();
1358         rawValues[i] = values[i].get();
1359     }
1360     
1361     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetStatisticsSubresourceUnderTopFrameOrigin"));
1362     WKRetainPtr<WKDictionaryRef> messageBody(AdoptWK, WKDictionaryCreate(rawKeys.data(), rawValues.data(), rawKeys.size()));
1363     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1364 }
1365
1366 void TestRunner::setStatisticsSubresourceUniqueRedirectTo(JSStringRef hostName, JSStringRef hostNameRedirectedTo)
1367 {
1368     Vector<WKRetainPtr<WKStringRef>> keys;
1369     Vector<WKRetainPtr<WKTypeRef>> values;
1370     
1371     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("HostName") });
1372     values.append({ AdoptWK, WKStringCreateWithJSString(hostName) });
1373     
1374     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("HostNameRedirectedTo") });
1375     values.append({ AdoptWK, WKStringCreateWithJSString(hostNameRedirectedTo) });
1376     
1377     Vector<WKStringRef> rawKeys(keys.size());
1378     Vector<WKTypeRef> rawValues(values.size());
1379     
1380     for (size_t i = 0; i < keys.size(); ++i) {
1381         rawKeys[i] = keys[i].get();
1382         rawValues[i] = values[i].get();
1383     }
1384     
1385     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetStatisticsSubresourceUniqueRedirectTo"));
1386     WKRetainPtr<WKDictionaryRef> messageBody(AdoptWK, WKDictionaryCreate(rawKeys.data(), rawValues.data(), rawKeys.size()));
1387     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1388 }
1389
1390 void TestRunner::setStatisticsTimeToLiveUserInteraction(double seconds)
1391 {
1392     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetStatisticsTimeToLiveUserInteraction"));
1393     WKRetainPtr<WKDoubleRef> messageBody(AdoptWK, WKDoubleCreate(seconds));
1394     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1395 }
1396
1397 void TestRunner::setStatisticsTimeToLiveCookiePartitionFree(double seconds)
1398 {
1399     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetStatisticsTimeToLiveCookiePartitionFree"));
1400     WKRetainPtr<WKDoubleRef> messageBody(AdoptWK, WKDoubleCreate(seconds));
1401     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1402 }
1403
1404 void TestRunner::installStatisticsDidModifyDataRecordsCallback(JSValueRef callback)
1405 {
1406     cacheTestRunnerCallback(StatisticsDidModifyDataRecordsCallbackID, callback);
1407 }
1408
1409 void TestRunner::statisticsDidModifyDataRecordsCallback()
1410 {
1411     callTestRunnerCallback(StatisticsDidModifyDataRecordsCallbackID);
1412 }
1413
1414 void TestRunner::installStatisticsDidScanDataRecordsCallback(JSValueRef callback)
1415 {
1416     cacheTestRunnerCallback(StatisticsDidScanDataRecordsCallbackID, callback);
1417 }
1418
1419 void TestRunner::statisticsDidScanDataRecordsCallback()
1420 {
1421     callTestRunnerCallback(StatisticsDidScanDataRecordsCallbackID);
1422 }
1423
1424 void TestRunner::installStatisticsDidRunTelemetryCallback(JSValueRef callback)
1425 {
1426     cacheTestRunnerCallback(StatisticsDidRunTelemetryCallbackID, callback);
1427 }
1428     
1429 void TestRunner::statisticsDidRunTelemetryCallback(unsigned totalPrevalentResources, unsigned totalPrevalentResourcesWithUserInteraction, unsigned top3SubframeUnderTopFrameOrigins)
1430 {
1431     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
1432     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
1433     
1434     StringBuilder stringBuilder;
1435     stringBuilder.appendLiteral("{ \"totalPrevalentResources\" : ");
1436     stringBuilder.appendNumber(totalPrevalentResources);
1437     stringBuilder.appendLiteral(", \"totalPrevalentResourcesWithUserInteraction\" : ");
1438     stringBuilder.appendNumber(totalPrevalentResourcesWithUserInteraction);
1439     stringBuilder.appendLiteral(", \"top3SubframeUnderTopFrameOrigins\" : ");
1440     stringBuilder.appendNumber(top3SubframeUnderTopFrameOrigins);
1441     stringBuilder.appendLiteral(" }");
1442     
1443     JSValueRef result = JSValueMakeFromJSONString(context, JSStringCreateWithUTF8CString(stringBuilder.toString().utf8().data()));
1444     
1445     callTestRunnerCallback(StatisticsDidRunTelemetryCallbackID, 1, &result);
1446 }
1447     
1448 void TestRunner::statisticsProcessStatisticsAndDataRecords()
1449 {
1450     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("StatisticsProcessStatisticsAndDataRecords"));
1451     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), 0, nullptr);
1452 }
1453
1454 void TestRunner::statisticsUpdateCookiePartitioning()
1455 {
1456     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("StatisticsUpdateCookiePartitioning"));
1457     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), 0, nullptr);
1458 }
1459
1460 void TestRunner::statisticsSetShouldPartitionCookiesForHost(JSStringRef hostName, bool value)
1461 {
1462     Vector<WKRetainPtr<WKStringRef>> keys;
1463     Vector<WKRetainPtr<WKTypeRef>> values;
1464     
1465     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("HostName") });
1466     values.append({ AdoptWK, WKStringCreateWithJSString(hostName) });
1467     
1468     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("Value") });
1469     values.append({ AdoptWK, WKBooleanCreate(value) });
1470     
1471     Vector<WKStringRef> rawKeys(keys.size());
1472     Vector<WKTypeRef> rawValues(values.size());
1473     
1474     for (size_t i = 0; i < keys.size(); ++i) {
1475         rawKeys[i] = keys[i].get();
1476         rawValues[i] = values[i].get();
1477     }
1478     
1479     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("StatisticsSetShouldPartitionCookiesForHost"));
1480     WKRetainPtr<WKDictionaryRef> messageBody(AdoptWK, WKDictionaryCreate(rawKeys.data(), rawValues.data(), rawKeys.size()));
1481     
1482     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1483 }
1484
1485 void TestRunner::statisticsSubmitTelemetry()
1486 {
1487     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("StatisticsSubmitTelemetry"));
1488     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), 0, nullptr);
1489 }
1490
1491 void TestRunner::setStatisticsNotifyPagesWhenDataRecordsWereScanned(bool value)
1492 {
1493     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("StatisticsNotifyPagesWhenDataRecordsWereScanned"));
1494     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(value));
1495     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1496 }
1497
1498 void TestRunner::setStatisticsShouldClassifyResourcesBeforeDataRecordsRemoval(bool value)
1499 {
1500     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("StatisticsShouldClassifyResourcesBeforeDataRecordsRemoval"));
1501     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(value));
1502     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1503 }
1504
1505 void TestRunner::setStatisticsNotifyPagesWhenTelemetryWasCaptured(bool value)
1506 {
1507     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("StatisticsNotifyPagesWhenTelemetryWasCaptured"));
1508     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(value));
1509     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1510 }
1511
1512 void TestRunner::setStatisticsMinimumTimeBetweenDataRecordsRemoval(double seconds)
1513 {
1514     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetStatisticsMinimumTimeBetweenDataRecordsRemoval"));
1515     WKRetainPtr<WKDoubleRef> messageBody(AdoptWK, WKDoubleCreate(seconds));
1516     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1517 }
1518
1519 void TestRunner::setStatisticsGrandfatheringTime(double seconds)
1520 {
1521     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetStatisticsGrandfatheringTime"));
1522     WKRetainPtr<WKDoubleRef> messageBody(AdoptWK, WKDoubleCreate(seconds));
1523     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1524 }
1525
1526 void TestRunner::setStatisticsMaxStatisticsEntries(unsigned entries)
1527 {
1528     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetMaxStatisticsEntries"));
1529     WKRetainPtr<WKTypeRef> messageBody(AdoptWK, WKUInt64Create(entries));
1530     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1531 }
1532     
1533 void TestRunner::setStatisticsPruneEntriesDownTo(unsigned entries)
1534 {
1535     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetPruneEntriesDownTo"));
1536     WKRetainPtr<WKTypeRef> messageBody(AdoptWK, WKUInt64Create(entries));
1537     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1538 }
1539     
1540 void TestRunner::statisticsClearInMemoryAndPersistentStore()
1541 {
1542     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("StatisticsClearInMemoryAndPersistentStore"));
1543     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), 0, nullptr);
1544 }
1545
1546 void TestRunner::statisticsClearInMemoryAndPersistentStoreModifiedSinceHours(unsigned hours)
1547 {
1548     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("StatisticsClearInMemoryAndPersistentStoreModifiedSinceHours"));
1549     WKRetainPtr<WKTypeRef> messageBody(AdoptWK, WKUInt64Create(hours));
1550     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1551 }
1552
1553 void TestRunner::statisticsResetToConsistentState()
1554 {
1555     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("StatisticsResetToConsistentState"));
1556     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), 0, nullptr);
1557 }
1558
1559 #if PLATFORM(MAC)
1560 void TestRunner::connectMockGamepad(unsigned index)
1561 {
1562     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("ConnectMockGamepad"));
1563     WKRetainPtr<WKTypeRef> messageBody(AdoptWK, WKUInt64Create(index));
1564
1565     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1566 }
1567
1568 void TestRunner::disconnectMockGamepad(unsigned index)
1569 {
1570     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("DisconnectMockGamepad"));
1571     WKRetainPtr<WKTypeRef> messageBody(AdoptWK, WKUInt64Create(index));
1572
1573     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1574 }
1575
1576 void TestRunner::setMockGamepadDetails(unsigned index, JSStringRef gamepadID, unsigned axisCount, unsigned buttonCount)
1577 {
1578     Vector<WKRetainPtr<WKStringRef>> keys;
1579     Vector<WKRetainPtr<WKTypeRef>> values;
1580
1581     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("GamepadID") });
1582     values.append(toWK(gamepadID));
1583
1584     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("GamepadIndex") });
1585     values.append({ AdoptWK, WKUInt64Create(index) });
1586
1587     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("AxisCount") });
1588     values.append({ AdoptWK, WKUInt64Create(axisCount) });
1589
1590     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("ButtonCount") });
1591     values.append({ AdoptWK, WKUInt64Create(buttonCount) });
1592
1593     Vector<WKStringRef> rawKeys;
1594     Vector<WKTypeRef> rawValues;
1595     rawKeys.resize(keys.size());
1596     rawValues.resize(values.size());
1597
1598     for (size_t i = 0; i < keys.size(); ++i) {
1599         rawKeys[i] = keys[i].get();
1600         rawValues[i] = values[i].get();
1601     }
1602
1603     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetMockGamepadDetails"));
1604     WKRetainPtr<WKDictionaryRef> messageBody(AdoptWK, WKDictionaryCreate(rawKeys.data(), rawValues.data(), rawKeys.size()));
1605
1606     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1607 }
1608
1609 void TestRunner::setMockGamepadAxisValue(unsigned index, unsigned axisIndex, double value)
1610 {
1611     Vector<WKRetainPtr<WKStringRef>> keys;
1612     Vector<WKRetainPtr<WKTypeRef>> values;
1613
1614     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("GamepadIndex") });
1615     values.append({ AdoptWK, WKUInt64Create(index) });
1616
1617     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("AxisIndex") });
1618     values.append({ AdoptWK, WKUInt64Create(axisIndex) });
1619
1620     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("Value") });
1621     values.append({ AdoptWK, WKDoubleCreate(value) });
1622
1623     Vector<WKStringRef> rawKeys;
1624     Vector<WKTypeRef> rawValues;
1625     rawKeys.resize(keys.size());
1626     rawValues.resize(values.size());
1627
1628     for (size_t i = 0; i < keys.size(); ++i) {
1629         rawKeys[i] = keys[i].get();
1630         rawValues[i] = values[i].get();
1631     }
1632
1633     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetMockGamepadAxisValue"));
1634     WKRetainPtr<WKDictionaryRef> messageBody(AdoptWK, WKDictionaryCreate(rawKeys.data(), rawValues.data(), rawKeys.size()));
1635
1636     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1637 }
1638
1639 void TestRunner::setMockGamepadButtonValue(unsigned index, unsigned buttonIndex, double value)
1640 {
1641     Vector<WKRetainPtr<WKStringRef>> keys;
1642     Vector<WKRetainPtr<WKTypeRef>> values;
1643
1644     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("GamepadIndex") });
1645     values.append({ AdoptWK, WKUInt64Create(index) });
1646
1647     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("ButtonIndex") });
1648     values.append({ AdoptWK, WKUInt64Create(buttonIndex) });
1649
1650     keys.append({ AdoptWK, WKStringCreateWithUTF8CString("Value") });
1651     values.append({ AdoptWK, WKDoubleCreate(value) });
1652
1653     Vector<WKStringRef> rawKeys;
1654     Vector<WKTypeRef> rawValues;
1655     rawKeys.resize(keys.size());
1656     rawValues.resize(values.size());
1657
1658     for (size_t i = 0; i < keys.size(); ++i) {
1659         rawKeys[i] = keys[i].get();
1660         rawValues[i] = values[i].get();
1661     }
1662
1663     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetMockGamepadButtonValue"));
1664     WKRetainPtr<WKDictionaryRef> messageBody(AdoptWK, WKDictionaryCreate(rawKeys.data(), rawValues.data(), rawKeys.size()));
1665
1666     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1667 }
1668 #else
1669 void TestRunner::connectMockGamepad(unsigned)
1670 {
1671 }
1672
1673 void TestRunner::disconnectMockGamepad(unsigned)
1674 {
1675 }
1676
1677 void TestRunner::setMockGamepadDetails(unsigned, JSStringRef, unsigned, unsigned)
1678 {
1679 }
1680
1681 void TestRunner::setMockGamepadAxisValue(unsigned, unsigned, double)
1682 {
1683 }
1684
1685 void TestRunner::setMockGamepadButtonValue(unsigned, unsigned, double)
1686 {
1687 }
1688 #endif // PLATFORM(MAC)
1689
1690 void TestRunner::setOpenPanelFiles(JSValueRef filesValue)
1691 {
1692     WKBundlePageRef page = InjectedBundle::singleton().page()->page();
1693     JSContextRef context = WKBundleFrameGetJavaScriptContext(WKBundlePageGetMainFrame(page));
1694
1695     if (!JSValueIsArray(context, filesValue))
1696         return;
1697
1698     JSObjectRef files = JSValueToObject(context, filesValue, nullptr);
1699     static auto lengthProperty = JSRetainPtr<JSStringRef>(Adopt, JSStringCreateWithUTF8CString("length"));
1700     JSValueRef filesLengthValue = JSObjectGetProperty(context, files, lengthProperty.get(), nullptr);
1701     if (!JSValueIsNumber(context, filesLengthValue))
1702         return;
1703
1704     auto fileURLs = adoptWK(WKMutableArrayCreate());
1705     auto filesLength = static_cast<size_t>(JSValueToNumber(context, filesLengthValue, nullptr));
1706     for (size_t i = 0; i < filesLength; ++i) {
1707         JSValueRef fileValue = JSObjectGetPropertyAtIndex(context, files, i, nullptr);
1708         if (!JSValueIsString(context, fileValue))
1709             continue;
1710
1711         auto file = JSRetainPtr<JSStringRef>(Adopt, JSValueToStringCopy(context, fileValue, nullptr));
1712         size_t fileBufferSize = JSStringGetMaximumUTF8CStringSize(file.get()) + 1;
1713         auto fileBuffer = std::make_unique<char[]>(fileBufferSize);
1714         JSStringGetUTF8CString(file.get(), fileBuffer.get(), fileBufferSize);
1715
1716         WKArrayAppendItem(fileURLs.get(), adoptWK(WKURLCreateWithBaseURL(m_testURL.get(), fileBuffer.get())).get());
1717     }
1718
1719     static auto messageName = adoptWK(WKStringCreateWithUTF8CString("SetOpenPanelFileURLs"));
1720     WKBundlePagePostMessage(page, messageName.get(), fileURLs.get());
1721 }
1722
1723 void TestRunner::removeAllSessionCredentials(JSValueRef callback)
1724 {
1725     cacheTestRunnerCallback(DidRemoveAllSessionCredentialsCallbackID, callback);
1726     
1727     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("RemoveAllSessionCredentials"));
1728     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(true));
1729     
1730     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), nullptr);
1731 }
1732
1733 void TestRunner::callDidRemoveAllSessionCredentialsCallback()
1734 {
1735     callTestRunnerCallback(DidRemoveAllSessionCredentialsCallbackID);
1736 }
1737
1738 } // namespace WTR