Confirm <a download> satisfies specification criteria
[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::setAllowUniversalAccessFromFileURLs(bool enabled)
342 {
343     auto& injectedBundle = InjectedBundle::singleton();
344     WKBundleSetAllowUniversalAccessFromFileURLs(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
345 }
346
347 void TestRunner::setAllowFileAccessFromFileURLs(bool enabled)
348 {
349     auto& injectedBundle = InjectedBundle::singleton();
350     WKBundleSetAllowFileAccessFromFileURLs(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
351 }
352
353 void TestRunner::setPluginsEnabled(bool enabled)
354 {
355     auto& injectedBundle = InjectedBundle::singleton();
356     WKBundleSetPluginsEnabled(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
357 }
358
359 void TestRunner::setJavaScriptCanAccessClipboard(bool enabled)
360 {
361     auto& injectedBundle = InjectedBundle::singleton();
362      WKBundleSetJavaScriptCanAccessClipboard(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
363 }
364
365 void TestRunner::setPrivateBrowsingEnabled(bool enabled)
366 {
367     auto& injectedBundle = InjectedBundle::singleton();
368      WKBundleSetPrivateBrowsingEnabled(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
369 }
370
371 void TestRunner::setPopupBlockingEnabled(bool enabled)
372 {
373     auto& injectedBundle = InjectedBundle::singleton();
374      WKBundleSetPopupBlockingEnabled(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
375 }
376
377 void TestRunner::setAuthorAndUserStylesEnabled(bool enabled)
378 {
379     auto& injectedBundle = InjectedBundle::singleton();
380      WKBundleSetAuthorAndUserStylesEnabled(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
381 }
382
383 void TestRunner::addOriginAccessWhitelistEntry(JSStringRef sourceOrigin, JSStringRef destinationProtocol, JSStringRef destinationHost, bool allowDestinationSubdomains)
384 {
385     WKBundleAddOriginAccessWhitelistEntry(InjectedBundle::singleton().bundle(), toWK(sourceOrigin).get(), toWK(destinationProtocol).get(), toWK(destinationHost).get(), allowDestinationSubdomains);
386 }
387
388 void TestRunner::removeOriginAccessWhitelistEntry(JSStringRef sourceOrigin, JSStringRef destinationProtocol, JSStringRef destinationHost, bool allowDestinationSubdomains)
389 {
390     WKBundleRemoveOriginAccessWhitelistEntry(InjectedBundle::singleton().bundle(), toWK(sourceOrigin).get(), toWK(destinationProtocol).get(), toWK(destinationHost).get(), allowDestinationSubdomains);
391 }
392
393 bool TestRunner::isPageBoxVisible(int pageIndex)
394 {
395     auto& injectedBundle = InjectedBundle::singleton();
396     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(injectedBundle.page()->page());
397     return WKBundleIsPageBoxVisible(injectedBundle.bundle(), mainFrame, pageIndex);
398 }
399
400 void TestRunner::setValueForUser(JSContextRef context, JSValueRef element, JSStringRef value)
401 {
402     if (!element || !JSValueIsObject(context, element))
403         return;
404
405     WKRetainPtr<WKBundleNodeHandleRef> nodeHandle(AdoptWK, WKBundleNodeHandleCreate(context, const_cast<JSObjectRef>(element)));
406     WKBundleNodeHandleSetHTMLInputElementValueForUser(nodeHandle.get(), toWK(value).get());
407 }
408
409 void TestRunner::setAudioResult(JSContextRef context, JSValueRef data)
410 {
411     auto& injectedBundle = InjectedBundle::singleton();
412     // FIXME (123058): Use a JSC API to get buffer contents once such is exposed.
413     WKRetainPtr<WKDataRef> audioData(AdoptWK, WKBundleCreateWKDataFromUInt8Array(injectedBundle.bundle(), context, data));
414     injectedBundle.setAudioResult(audioData.get());
415     m_whatToDump = Audio;
416     m_dumpPixels = false;
417 }
418
419 unsigned TestRunner::windowCount()
420 {
421     return InjectedBundle::singleton().pageCount();
422 }
423
424 void TestRunner::clearBackForwardList()
425 {
426     WKBundleBackForwardListClear(WKBundlePageGetBackForwardList(InjectedBundle::singleton().page()->page()));
427 }
428
429 // Object Creation
430
431 void TestRunner::makeWindowObject(JSContextRef context, JSObjectRef windowObject, JSValueRef* exception)
432 {
433     setProperty(context, windowObject, "testRunner", this, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete, exception);
434 }
435
436 void TestRunner::showWebInspector()
437 {
438     WKBundleInspectorShow(WKBundlePageGetInspector(InjectedBundle::singleton().page()->page()));
439 }
440
441 void TestRunner::closeWebInspector()
442 {
443     WKBundleInspectorClose(WKBundlePageGetInspector(InjectedBundle::singleton().page()->page()));
444 }
445
446 void TestRunner::evaluateInWebInspector(JSStringRef script)
447 {
448     WKRetainPtr<WKStringRef> scriptWK = toWK(script);
449     WKBundleInspectorEvaluateScriptForTest(WKBundlePageGetInspector(InjectedBundle::singleton().page()->page()), scriptWK.get());
450 }
451
452 typedef WTF::HashMap<unsigned, WKRetainPtr<WKBundleScriptWorldRef> > WorldMap;
453 static WorldMap& worldMap()
454 {
455     static WorldMap& map = *new WorldMap;
456     return map;
457 }
458
459 unsigned TestRunner::worldIDForWorld(WKBundleScriptWorldRef world)
460 {
461     WorldMap::const_iterator end = worldMap().end();
462     for (WorldMap::const_iterator it = worldMap().begin(); it != end; ++it) {
463         if (it->value == world)
464             return it->key;
465     }
466
467     return 0;
468 }
469
470 void TestRunner::evaluateScriptInIsolatedWorld(JSContextRef context, unsigned worldID, JSStringRef script)
471 {
472     // A worldID of 0 always corresponds to a new world. Any other worldID corresponds to a world
473     // that is created once and cached forever.
474     WKRetainPtr<WKBundleScriptWorldRef> world;
475     if (!worldID)
476         world.adopt(WKBundleScriptWorldCreateWorld());
477     else {
478         WKRetainPtr<WKBundleScriptWorldRef>& worldSlot = worldMap().add(worldID, nullptr).iterator->value;
479         if (!worldSlot)
480             worldSlot.adopt(WKBundleScriptWorldCreateWorld());
481         world = worldSlot;
482     }
483
484     WKBundleFrameRef frame = WKBundleFrameForJavaScriptContext(context);
485     if (!frame)
486         frame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
487
488     JSGlobalContextRef jsContext = WKBundleFrameGetJavaScriptContextForWorld(frame, world.get());
489     JSEvaluateScript(jsContext, script, 0, 0, 0, 0); 
490 }
491
492 void TestRunner::setPOSIXLocale(JSStringRef locale)
493 {
494     char localeBuf[32];
495     JSStringGetUTF8CString(locale, localeBuf, sizeof(localeBuf));
496     setlocale(LC_ALL, localeBuf);
497 }
498
499 void TestRunner::setTextDirection(JSStringRef direction)
500 {
501     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
502     return WKBundleFrameSetTextDirection(mainFrame, toWK(direction).get());
503 }
504     
505 void TestRunner::setShouldStayOnPageAfterHandlingBeforeUnload(bool shouldStayOnPage)
506 {
507     InjectedBundle::singleton().postNewBeforeUnloadReturnValue(!shouldStayOnPage);
508 }
509
510 void TestRunner::setDefersLoading(bool shouldDeferLoading)
511 {
512     WKBundlePageSetDefersLoading(InjectedBundle::singleton().page()->page(), shouldDeferLoading);
513 }
514
515 void TestRunner::setPageVisibility(JSStringRef state)
516 {
517     InjectedBundle::singleton().setHidden(JSStringIsEqualToUTF8CString(state, "hidden") || JSStringIsEqualToUTF8CString(state, "prerender"));
518 }
519
520 void TestRunner::resetPageVisibility()
521 {
522     InjectedBundle::singleton().setHidden(false);
523 }
524
525 typedef WTF::HashMap<unsigned, JSValueRef> CallbackMap;
526 static CallbackMap& callbackMap()
527 {
528     static CallbackMap& map = *new CallbackMap;
529     return map;
530 }
531
532 enum {
533     AddChromeInputFieldCallbackID = 1,
534     RemoveChromeInputFieldCallbackID,
535     FocusWebViewCallbackID,
536     SetBackingScaleFactorCallbackID,
537     DidBeginSwipeCallbackID,
538     WillEndSwipeCallbackID,
539     DidEndSwipeCallbackID,
540     DidRemoveSwipeSnapshotCallbackID,
541     FirstUIScriptCallbackID = 100
542 };
543
544 static void cacheTestRunnerCallback(unsigned index, JSValueRef callback)
545 {
546     if (!callback)
547         return;
548
549     if (callbackMap().contains(index)) {
550         InjectedBundle::singleton().outputText(String::format("FAIL: Tried to install a second TestRunner callback for the same event (id %d)\n\n", index));
551         return;
552     }
553
554     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
555     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
556     JSValueProtect(context, callback);
557     callbackMap().add(index, callback);
558 }
559
560 static void callTestRunnerCallback(unsigned index, size_t argumentCount = 0, const JSValueRef arguments[] = nullptr)
561 {
562     if (!callbackMap().contains(index))
563         return;
564     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
565     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
566     JSObjectRef callback = JSValueToObject(context, callbackMap().take(index), 0);
567     JSObjectCallAsFunction(context, callback, JSContextGetGlobalObject(context), argumentCount, arguments, 0);
568     JSValueUnprotect(context, callback);
569 }
570
571 void TestRunner::clearTestRunnerCallbacks()
572 {
573     for (auto& iter : callbackMap()) {
574         WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
575         JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
576         JSObjectRef callback = JSValueToObject(context, iter.value, 0);
577         JSValueUnprotect(context, callback);
578     }
579
580     callbackMap().clear();
581 }
582
583 void TestRunner::addChromeInputField(JSValueRef callback)
584 {
585     cacheTestRunnerCallback(AddChromeInputFieldCallbackID, callback);
586     InjectedBundle::singleton().postAddChromeInputField();
587 }
588
589 void TestRunner::removeChromeInputField(JSValueRef callback)
590 {
591     cacheTestRunnerCallback(RemoveChromeInputFieldCallbackID, callback);
592     InjectedBundle::singleton().postRemoveChromeInputField();
593 }
594
595 void TestRunner::focusWebView(JSValueRef callback)
596 {
597     cacheTestRunnerCallback(FocusWebViewCallbackID, callback);
598     InjectedBundle::singleton().postFocusWebView();
599 }
600
601 void TestRunner::setBackingScaleFactor(double backingScaleFactor, JSValueRef callback)
602 {
603     cacheTestRunnerCallback(SetBackingScaleFactorCallbackID, callback);
604     InjectedBundle::singleton().postSetBackingScaleFactor(backingScaleFactor);
605 }
606
607 void TestRunner::setWindowIsKey(bool isKey)
608 {
609     InjectedBundle::singleton().postSetWindowIsKey(isKey);
610 }
611
612 void TestRunner::callAddChromeInputFieldCallback()
613 {
614     callTestRunnerCallback(AddChromeInputFieldCallbackID);
615 }
616
617 void TestRunner::callRemoveChromeInputFieldCallback()
618 {
619     callTestRunnerCallback(RemoveChromeInputFieldCallbackID);
620 }
621
622 void TestRunner::callFocusWebViewCallback()
623 {
624     callTestRunnerCallback(FocusWebViewCallbackID);
625 }
626
627 void TestRunner::callSetBackingScaleFactorCallback()
628 {
629     callTestRunnerCallback(SetBackingScaleFactorCallbackID);
630 }
631
632 static inline bool toBool(JSStringRef value)
633 {
634     return JSStringIsEqualToUTF8CString(value, "true") || JSStringIsEqualToUTF8CString(value, "1");
635 }
636
637 void TestRunner::overridePreference(JSStringRef preference, JSStringRef value)
638 {
639     auto& injectedBundle = InjectedBundle::singleton();
640     // FIXME: handle non-boolean preferences.
641     WKBundleOverrideBoolPreferenceForTestRunner(injectedBundle.bundle(), injectedBundle.pageGroup(), toWK(preference).get(), toBool(value));
642 }
643
644 void TestRunner::setAlwaysAcceptCookies(bool accept)
645 {
646     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetAlwaysAcceptCookies"));
647
648     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(accept));
649
650     WKBundlePostSynchronousMessage(InjectedBundle::singleton().bundle(), messageName.get(), messageBody.get(), 0);
651 }
652
653 double TestRunner::preciseTime()
654 {
655     return currentTime();
656 }
657
658 void TestRunner::setUserStyleSheetEnabled(bool enabled)
659 {
660     m_userStyleSheetEnabled = enabled;
661
662     WKRetainPtr<WKStringRef> emptyUrl = adoptWK(WKStringCreateWithUTF8CString(""));
663     WKStringRef location = enabled ? m_userStyleSheetLocation.get() : emptyUrl.get();
664     auto& injectedBundle = InjectedBundle::singleton();
665     WKBundleSetUserStyleSheetLocation(injectedBundle.bundle(), injectedBundle.pageGroup(), location);
666 }
667
668 void TestRunner::setUserStyleSheetLocation(JSStringRef location)
669 {
670     m_userStyleSheetLocation = adoptWK(WKStringCreateWithJSString(location));
671
672     if (m_userStyleSheetEnabled)
673         setUserStyleSheetEnabled(true);
674 }
675
676 void TestRunner::setSpatialNavigationEnabled(bool enabled)
677 {
678     auto& injectedBundle = InjectedBundle::singleton();
679     WKBundleSetSpatialNavigationEnabled(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
680 }
681
682 void TestRunner::setTabKeyCyclesThroughElements(bool enabled)
683 {
684     auto& injectedBundle = InjectedBundle::singleton();
685     WKBundleSetTabKeyCyclesThroughElements(injectedBundle.bundle(), injectedBundle.page()->page(), enabled);
686 }
687
688 void TestRunner::setSerializeHTTPLoads()
689 {
690     // WK2 doesn't reorder loads.
691 }
692
693 void TestRunner::dispatchPendingLoadRequests()
694 {
695     // WK2 doesn't keep pending requests.
696 }
697
698 void TestRunner::setCacheModel(int model)
699 {
700     InjectedBundle::singleton().setCacheModel(model);
701 }
702
703 void TestRunner::setAsynchronousSpellCheckingEnabled(bool enabled)
704 {
705     auto& injectedBundle = InjectedBundle::singleton();
706     WKBundleSetAsynchronousSpellCheckingEnabled(injectedBundle.bundle(), injectedBundle.pageGroup(), enabled);
707 }
708
709 void TestRunner::grantWebNotificationPermission(JSStringRef origin)
710 {
711     WKRetainPtr<WKStringRef> originWK = toWK(origin);
712     auto& injectedBundle = InjectedBundle::singleton();
713     WKBundleSetWebNotificationPermission(injectedBundle.bundle(), injectedBundle.page()->page(), originWK.get(), true);
714 }
715
716 void TestRunner::denyWebNotificationPermission(JSStringRef origin)
717 {
718     WKRetainPtr<WKStringRef> originWK = toWK(origin);
719     auto& injectedBundle = InjectedBundle::singleton();
720     WKBundleSetWebNotificationPermission(injectedBundle.bundle(), injectedBundle.page()->page(), originWK.get(), false);
721 }
722
723 void TestRunner::removeAllWebNotificationPermissions()
724 {
725     auto& injectedBundle = InjectedBundle::singleton();
726     WKBundleRemoveAllWebNotificationPermissions(injectedBundle.bundle(), injectedBundle.page()->page());
727 }
728
729 void TestRunner::simulateWebNotificationClick(JSValueRef notification)
730 {
731     auto& injectedBundle = InjectedBundle::singleton();
732     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(injectedBundle.page()->page());
733     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
734     uint64_t notificationID = WKBundleGetWebNotificationID(injectedBundle.bundle(), context, notification);
735     injectedBundle.postSimulateWebNotificationClick(notificationID);
736 }
737
738 void TestRunner::setGeolocationPermission(bool enabled)
739 {
740     // FIXME: this should be done by frame.
741     InjectedBundle::singleton().setGeolocationPermission(enabled);
742 }
743
744 bool TestRunner::isGeolocationProviderActive()
745 {
746     return InjectedBundle::singleton().isGeolocationProviderActive();
747 }
748
749 void TestRunner::setMockGeolocationPosition(double latitude, double longitude, double accuracy, JSValueRef jsAltitude, JSValueRef jsAltitudeAccuracy, JSValueRef jsHeading, JSValueRef jsSpeed)
750 {
751     auto& injectedBundle = InjectedBundle::singleton();
752     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(injectedBundle.page()->page());
753     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
754
755     bool providesAltitude = false;
756     double altitude = 0.;
757     if (!JSValueIsUndefined(context, jsAltitude)) {
758         providesAltitude = true;
759         altitude = JSValueToNumber(context, jsAltitude, 0);
760     }
761
762     bool providesAltitudeAccuracy = false;
763     double altitudeAccuracy = 0.;
764     if (!JSValueIsUndefined(context, jsAltitudeAccuracy)) {
765         providesAltitudeAccuracy = true;
766         altitudeAccuracy = JSValueToNumber(context, jsAltitudeAccuracy, 0);
767     }
768
769     bool providesHeading = false;
770     double heading = 0.;
771     if (!JSValueIsUndefined(context, jsHeading)) {
772         providesHeading = true;
773         heading = JSValueToNumber(context, jsHeading, 0);
774     }
775
776     bool providesSpeed = false;
777     double speed = 0.;
778     if (!JSValueIsUndefined(context, jsSpeed)) {
779         providesSpeed = true;
780         speed = JSValueToNumber(context, jsSpeed, 0);
781     }
782
783     injectedBundle.setMockGeolocationPosition(latitude, longitude, accuracy, providesAltitude, altitude, providesAltitudeAccuracy, altitudeAccuracy, providesHeading, heading, providesSpeed, speed);
784 }
785
786 void TestRunner::setMockGeolocationPositionUnavailableError(JSStringRef message)
787 {
788     WKRetainPtr<WKStringRef> messageWK = toWK(message);
789     InjectedBundle::singleton().setMockGeolocationPositionUnavailableError(messageWK.get());
790 }
791
792 void TestRunner::setUserMediaPermission(bool enabled)
793 {
794     // FIXME: this should be done by frame.
795     InjectedBundle::singleton().setUserMediaPermission(enabled);
796 }
797
798 void TestRunner::setUserMediaPermissionForOrigin(bool permission, JSStringRef origin, JSStringRef parentOrigin)
799 {
800     WKRetainPtr<WKStringRef> originWK = toWK(origin);
801     WKRetainPtr<WKStringRef> parentOriginWK = toWK(parentOrigin);
802     InjectedBundle::singleton().setUserMediaPermissionForOrigin(permission, originWK.get(), parentOriginWK.get());
803 }
804
805 bool TestRunner::callShouldCloseOnWebView()
806 {
807     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
808     return WKBundleFrameCallShouldCloseOnWebView(mainFrame);
809 }
810
811 void TestRunner::queueBackNavigation(unsigned howFarBackward)
812 {
813     InjectedBundle::singleton().queueBackNavigation(howFarBackward);
814 }
815
816 void TestRunner::queueForwardNavigation(unsigned howFarForward)
817 {
818     InjectedBundle::singleton().queueForwardNavigation(howFarForward);
819 }
820
821 void TestRunner::queueLoad(JSStringRef url, JSStringRef target, bool shouldOpenExternalURLs)
822 {
823     auto& injectedBundle = InjectedBundle::singleton();
824     WKRetainPtr<WKURLRef> baseURLWK(AdoptWK, WKBundleFrameCopyURL(WKBundlePageGetMainFrame(injectedBundle.page()->page())));
825     WKRetainPtr<WKURLRef> urlWK(AdoptWK, WKURLCreateWithBaseURL(baseURLWK.get(), toWTFString(toWK(url)).utf8().data()));
826     WKRetainPtr<WKStringRef> urlStringWK(AdoptWK, WKURLCopyString(urlWK.get()));
827
828     injectedBundle.queueLoad(urlStringWK.get(), toWK(target).get(), shouldOpenExternalURLs);
829 }
830
831 void TestRunner::queueLoadHTMLString(JSStringRef content, JSStringRef baseURL, JSStringRef unreachableURL)
832 {
833     WKRetainPtr<WKStringRef> contentWK = toWK(content);
834     WKRetainPtr<WKStringRef> baseURLWK = baseURL ? toWK(baseURL) : WKRetainPtr<WKStringRef>();
835     WKRetainPtr<WKStringRef> unreachableURLWK = unreachableURL ? toWK(unreachableURL) : WKRetainPtr<WKStringRef>();
836
837     InjectedBundle::singleton().queueLoadHTMLString(contentWK.get(), baseURLWK.get(), unreachableURLWK.get());
838 }
839
840 void TestRunner::queueReload()
841 {
842     InjectedBundle::singleton().queueReload();
843 }
844
845 void TestRunner::queueLoadingScript(JSStringRef script)
846 {
847     WKRetainPtr<WKStringRef> scriptWK = toWK(script);
848     InjectedBundle::singleton().queueLoadingScript(scriptWK.get());
849 }
850
851 void TestRunner::queueNonLoadingScript(JSStringRef script)
852 {
853     WKRetainPtr<WKStringRef> scriptWK = toWK(script);
854     InjectedBundle::singleton().queueNonLoadingScript(scriptWK.get());
855 }
856
857 void TestRunner::setHandlesAuthenticationChallenges(bool handlesAuthenticationChallenges)
858 {
859     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetHandlesAuthenticationChallenge"));
860     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(handlesAuthenticationChallenges));
861     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
862 }
863
864 void TestRunner::setAuthenticationUsername(JSStringRef username)
865 {
866     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetAuthenticationUsername"));
867     WKRetainPtr<WKStringRef> messageBody(AdoptWK, WKStringCreateWithJSString(username));
868     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
869 }
870
871 void TestRunner::setAuthenticationPassword(JSStringRef password)
872 {
873     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetAuthenticationPassword"));
874     WKRetainPtr<WKStringRef> messageBody(AdoptWK, WKStringCreateWithJSString(password));
875     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
876 }
877
878 bool TestRunner::secureEventInputIsEnabled() const
879 {
880     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SecureEventInputIsEnabled"));
881     WKTypeRef returnData = 0;
882
883     WKBundlePagePostSynchronousMessageForTesting(InjectedBundle::singleton().page()->page(), messageName.get(), 0, &returnData);
884     return WKBooleanGetValue(static_cast<WKBooleanRef>(returnData));
885 }
886
887 void TestRunner::setBlockAllPlugins(bool shouldBlock)
888 {
889     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetBlockAllPlugins"));
890     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(shouldBlock));
891     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
892 }
893
894 JSValueRef TestRunner::failNextNewCodeBlock()
895 {
896     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
897     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
898     return JSC::failNextNewCodeBlock(context);
899 }
900
901 JSValueRef TestRunner::numberOfDFGCompiles(JSValueRef theFunction)
902 {
903     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
904     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
905     return JSC::numberOfDFGCompiles(context, theFunction);
906 }
907
908 JSValueRef TestRunner::neverInlineFunction(JSValueRef theFunction)
909 {
910     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
911     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
912     return JSC::setNeverInline(context, theFunction);
913 }
914
915 void TestRunner::setShouldDecideNavigationPolicyAfterDelay(bool value)
916 {
917     m_shouldDecideNavigationPolicyAfterDelay = value;
918     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetShouldDecideNavigationPolicyAfterDelay"));
919     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(value));
920     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
921 }
922
923 void TestRunner::setNavigationGesturesEnabled(bool value)
924 {
925     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("SetNavigationGesturesEnabled"));
926     WKRetainPtr<WKBooleanRef> messageBody(AdoptWK, WKBooleanCreate(value));
927     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), messageBody.get());
928 }
929
930 static unsigned nextUIScriptCallbackID()
931 {
932     static unsigned callbackID = FirstUIScriptCallbackID;
933     return callbackID++;
934 }
935
936 void TestRunner::runUIScript(JSStringRef script, JSValueRef callback)
937 {
938     unsigned callbackID = nextUIScriptCallbackID();
939     cacheTestRunnerCallback(callbackID, callback);
940
941     WKRetainPtr<WKStringRef> messageName(AdoptWK, WKStringCreateWithUTF8CString("RunUIProcessScript"));
942
943     WKRetainPtr<WKMutableDictionaryRef> testDictionary(AdoptWK, WKMutableDictionaryCreate());
944
945     WKRetainPtr<WKStringRef> scriptKey(AdoptWK, WKStringCreateWithUTF8CString("Script"));
946     WKRetainPtr<WKStringRef> scriptValue(AdoptWK, WKStringCreateWithJSString(script));
947
948     WKRetainPtr<WKStringRef> callbackIDKey(AdoptWK, WKStringCreateWithUTF8CString("CallbackID"));
949     WKRetainPtr<WKUInt64Ref> callbackIDValue = adoptWK(WKUInt64Create(callbackID));
950
951     WKDictionarySetItem(testDictionary.get(), scriptKey.get(), scriptValue.get());
952     WKDictionarySetItem(testDictionary.get(), callbackIDKey.get(), callbackIDValue.get());
953
954     WKBundlePagePostMessage(InjectedBundle::singleton().page()->page(), messageName.get(), testDictionary.get());
955 }
956
957 void TestRunner::runUIScriptCallback(unsigned callbackID, JSStringRef result)
958 {
959     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::singleton().page()->page());
960     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
961
962     JSValueRef resultValue = JSValueMakeString(context, result);
963     callTestRunnerCallback(callbackID, 1, &resultValue);
964 }
965
966 void TestRunner::installDidBeginSwipeCallback(JSValueRef callback)
967 {
968     cacheTestRunnerCallback(DidBeginSwipeCallbackID, callback);
969 }
970
971 void TestRunner::installWillEndSwipeCallback(JSValueRef callback)
972 {
973     cacheTestRunnerCallback(WillEndSwipeCallbackID, callback);
974 }
975
976 void TestRunner::installDidEndSwipeCallback(JSValueRef callback)
977 {
978     cacheTestRunnerCallback(DidEndSwipeCallbackID, callback);
979 }
980
981 void TestRunner::installDidRemoveSwipeSnapshotCallback(JSValueRef callback)
982 {
983     cacheTestRunnerCallback(DidRemoveSwipeSnapshotCallbackID, callback);
984 }
985
986 void TestRunner::callDidBeginSwipeCallback()
987 {
988     callTestRunnerCallback(DidBeginSwipeCallbackID);
989 }
990
991 void TestRunner::callWillEndSwipeCallback()
992 {
993     callTestRunnerCallback(WillEndSwipeCallbackID);
994 }
995
996 void TestRunner::callDidEndSwipeCallback()
997 {
998     callTestRunnerCallback(DidEndSwipeCallbackID);
999 }
1000
1001 void TestRunner::callDidRemoveSwipeSnapshotCallback()
1002 {
1003     callTestRunnerCallback(DidRemoveSwipeSnapshotCallbackID);
1004 }
1005
1006 } // namespace WTR