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