[WK2] TestRunner does not support overridePreference with value "0"
[WebKit-https.git] / Tools / WebKitTestRunner / InjectedBundle / TestRunner.cpp
1 /*
2  * Copyright (C) 2010, 2011, 2012 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 <WebCore/PageVisibilityState.h>
36 #include <WebKit2/WKBundleBackForwardList.h>
37 #include <WebKit2/WKBundleFrame.h>
38 #include <WebKit2/WKBundleFramePrivate.h>
39 #include <WebKit2/WKBundleInspector.h>
40 #include <WebKit2/WKBundleNodeHandlePrivate.h>
41 #include <WebKit2/WKBundlePagePrivate.h>
42 #include <WebKit2/WKBundlePrivate.h>
43 #include <WebKit2/WKBundleScriptWorld.h>
44 #include <WebKit2/WKRetainPtr.h>
45 #include <WebKit2/WKSerializedScriptValue.h>
46 #include <WebKit2/WebKit2_C.h>
47 #include <wtf/CurrentTime.h>
48 #include <wtf/HashMap.h>
49 #include <wtf/OwnArrayPtr.h>
50 #include <wtf/PassOwnArrayPtr.h>
51 #include <wtf/text/StringBuilder.h>
52
53 #if ENABLE(WEB_INTENTS)
54 #include <WebKit2/WKBundleIntent.h>
55 #include <WebKit2/WKBundleIntentRequest.h>
56 #endif
57
58 namespace WTR {
59
60 const double TestRunner::waitToDumpWatchdogTimerInterval = 30;
61
62 PassRefPtr<TestRunner> TestRunner::create()
63 {
64     return adoptRef(new TestRunner);
65 }
66
67 TestRunner::TestRunner()
68     : m_whatToDump(RenderTree)
69     , m_shouldDumpAllFrameScrollPositions(false)
70     , m_shouldDumpBackForwardListsForAllWindows(false)
71     , m_shouldAllowEditing(true)
72     , m_shouldCloseExtraWindows(false)
73     , m_dumpEditingCallbacks(false)
74     , m_dumpStatusCallbacks(false)
75     , m_dumpTitleChanges(false)
76     , m_dumpPixels(true)
77     , m_dumpFullScreenCallbacks(false)
78     , m_dumpFrameLoadCallbacks(false)
79     , m_dumpProgressFinishedCallback(false)
80     , m_dumpResourceLoadCallbacks(false)
81     , m_dumpResourceResponseMIMETypes(false)
82     , m_dumpWillCacheResponse(false)
83     , m_dumpApplicationCacheDelegateCallbacks(false)
84     , m_dumpDatabaseCallbacks(false)
85     , m_disallowIncreaseForApplicationCacheQuota(false)
86     , m_waitToDump(false)
87     , m_testRepaint(false)
88     , m_testRepaintSweepHorizontally(false)
89     , m_willSendRequestReturnsNull(false)
90     , m_shouldStopProvisionalFrameLoads(false)
91     , m_policyDelegateEnabled(false)
92     , m_policyDelegatePermissive(false)
93     , m_globalFlag(false)
94     , m_customFullScreenBehavior(false)
95     , m_userStyleSheetEnabled(false)
96     , m_userStyleSheetLocation(adoptWK(WKStringCreateWithUTF8CString("")))
97 {
98     platformInitialize();
99 }
100
101 TestRunner::~TestRunner()
102 {
103 }
104
105 JSClassRef TestRunner::wrapperClass()
106 {
107     return JSTestRunner::testRunnerClass();
108 }
109
110 void TestRunner::display()
111 {
112     WKBundlePageRef page = InjectedBundle::shared().page()->page();
113     WKBundlePageForceRepaint(page);
114     WKBundlePageSetTracksRepaints(page, true);
115     WKBundlePageResetTrackedRepaints(page);
116 }
117
118 void TestRunner::dumpAsText(bool dumpPixels)
119 {
120     if (m_whatToDump < MainFrameText)
121         m_whatToDump = MainFrameText;
122     m_dumpPixels = dumpPixels;
123 }
124
125 // FIXME: Needs a full implementation see https://bugs.webkit.org/show_bug.cgi?id=42546
126 void TestRunner::setCustomPolicyDelegate(bool enabled, bool permissive)
127 {
128     m_policyDelegateEnabled = enabled;
129     m_policyDelegatePermissive = permissive;
130 }
131
132 void TestRunner::waitForPolicyDelegate()
133 {
134     setCustomPolicyDelegate(true);
135     waitUntilDone();
136 }
137
138 void TestRunner::waitUntilDone()
139 {
140     m_waitToDump = true;
141     if (InjectedBundle::shared().useWaitToDumpWatchdogTimer())
142         initializeWaitToDumpWatchdogTimerIfNeeded();
143 }
144
145 void TestRunner::waitToDumpWatchdogTimerFired()
146 {
147     invalidateWaitToDumpWatchdogTimer();
148     const char* message = "FAIL: Timed out waiting for notifyDone to be called\n";
149     InjectedBundle::shared().stringBuilder()->append(message);
150     InjectedBundle::shared().stringBuilder()->append("\n");
151     InjectedBundle::shared().done();
152 }
153
154 void TestRunner::notifyDone()
155 {
156     if (!InjectedBundle::shared().isTestRunning())
157         return;
158
159     if (m_waitToDump && !InjectedBundle::shared().topLoadingFrame())
160         InjectedBundle::shared().page()->dump();
161
162     m_waitToDump = false;
163 }
164
165 unsigned TestRunner::numberOfActiveAnimations() const
166 {
167     // FIXME: Is it OK this works only for the main frame?
168     // FIXME: If this is needed only for the main frame, then why is the function on WKBundleFrame instead of WKBundlePage?
169     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::shared().page()->page());
170     return WKBundleFrameGetNumberOfActiveAnimations(mainFrame);
171 }
172
173 bool TestRunner::pauseAnimationAtTimeOnElementWithId(JSStringRef animationName, double time, JSStringRef elementId)
174 {
175     // FIXME: Is it OK this works only for the main frame?
176     // FIXME: If this is needed only for the main frame, then why is the function on WKBundleFrame instead of WKBundlePage?
177     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::shared().page()->page());
178     return WKBundleFramePauseAnimationOnElementWithId(mainFrame, toWK(animationName).get(), toWK(elementId).get(), time);
179 }
180
181 bool TestRunner::pauseTransitionAtTimeOnElementWithId(JSStringRef propertyName, double time, JSStringRef elementId)
182 {
183     // FIXME: Is it OK this works only for the main frame?
184     // FIXME: If this is needed only for the main frame, then why is the function on WKBundleFrame instead of WKBundlePage?
185     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::shared().page()->page());
186     return WKBundleFramePauseTransitionOnElementWithId(mainFrame, toWK(propertyName).get(), toWK(elementId).get(), time);
187 }
188
189 void TestRunner::suspendAnimations()
190 {
191     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::shared().page()->page());
192     WKBundleFrameSuspendAnimations(mainFrame);
193 }
194
195 JSRetainPtr<JSStringRef> TestRunner::layerTreeAsText() const
196 {
197     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::shared().page()->page());
198     WKRetainPtr<WKStringRef> text(AdoptWK, WKBundleFrameCopyLayerTreeAsText(mainFrame));
199     return toJS(text);
200 }
201
202 void TestRunner::addUserScript(JSStringRef source, bool runAtStart, bool allFrames)
203 {
204     WKRetainPtr<WKStringRef> sourceWK = toWK(source);
205     WKRetainPtr<WKBundleScriptWorldRef> scriptWorld(AdoptWK, WKBundleScriptWorldCreateWorld());
206
207     WKBundleAddUserScript(InjectedBundle::shared().bundle(), InjectedBundle::shared().pageGroup(), scriptWorld.get(), sourceWK.get(), 0, 0, 0,
208         (runAtStart ? kWKInjectAtDocumentStart : kWKInjectAtDocumentEnd),
209         (allFrames ? kWKInjectInAllFrames : kWKInjectInTopFrameOnly));
210 }
211
212 void TestRunner::addUserStyleSheet(JSStringRef source, bool allFrames)
213 {
214     WKRetainPtr<WKStringRef> sourceWK = toWK(source);
215     WKRetainPtr<WKBundleScriptWorldRef> scriptWorld(AdoptWK, WKBundleScriptWorldCreateWorld());
216
217     WKBundleAddUserStyleSheet(InjectedBundle::shared().bundle(), InjectedBundle::shared().pageGroup(), scriptWorld.get(), sourceWK.get(), 0, 0, 0,
218         (allFrames ? kWKInjectInAllFrames : kWKInjectInTopFrameOnly));
219 }
220
221 void TestRunner::keepWebHistory()
222 {
223     WKBundleSetShouldTrackVisitedLinks(InjectedBundle::shared().bundle(), true);
224 }
225
226 JSValueRef TestRunner::computedStyleIncludingVisitedInfo(JSValueRef element)
227 {
228     // FIXME: Is it OK this works only for the main frame?
229     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::shared().page()->page());
230     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
231     if (!JSValueIsObject(context, element))
232         return JSValueMakeUndefined(context);
233     JSValueRef value = WKBundleFrameGetComputedStyleIncludingVisitedInfo(mainFrame, const_cast<JSObjectRef>(element));
234     if (!value)
235         return JSValueMakeUndefined(context);
236     return value;
237 }
238
239 JSRetainPtr<JSStringRef> TestRunner::markerTextForListItem(JSValueRef element)
240 {
241     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::shared().page()->page());
242     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
243     if (!element || !JSValueIsObject(context, element))
244         return 0;
245     WKRetainPtr<WKStringRef> text(AdoptWK, WKBundleFrameCopyMarkerText(mainFrame, const_cast<JSObjectRef>(element)));
246     if (WKStringIsEmpty(text.get()))
247         return 0;
248     return toJS(text);
249 }
250
251 void TestRunner::execCommand(JSStringRef name, JSStringRef argument)
252 {
253     WKBundlePageExecuteEditingCommand(InjectedBundle::shared().page()->page(), toWK(name).get(), toWK(argument).get());
254 }
255
256 bool TestRunner::findString(JSStringRef target, JSValueRef optionsArrayAsValue)
257 {
258     WKFindOptions options = 0;
259
260     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::shared().page()->page());
261     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
262     JSRetainPtr<JSStringRef> lengthPropertyName(Adopt, JSStringCreateWithUTF8CString("length"));
263     JSObjectRef optionsArray = JSValueToObject(context, optionsArrayAsValue, 0);
264     JSValueRef lengthValue = JSObjectGetProperty(context, optionsArray, lengthPropertyName.get(), 0);
265     if (!JSValueIsNumber(context, lengthValue))
266         return false;
267
268     size_t length = static_cast<size_t>(JSValueToNumber(context, lengthValue, 0));
269     for (size_t i = 0; i < length; ++i) {
270         JSValueRef value = JSObjectGetPropertyAtIndex(context, optionsArray, i, 0);
271         if (!JSValueIsString(context, value))
272             continue;
273
274         JSRetainPtr<JSStringRef> optionName(Adopt, JSValueToStringCopy(context, value, 0));
275
276         if (JSStringIsEqualToUTF8CString(optionName.get(), "CaseInsensitive"))
277             options |= kWKFindOptionsCaseInsensitive;
278         else if (JSStringIsEqualToUTF8CString(optionName.get(), "AtWordStarts"))
279             options |= kWKFindOptionsAtWordStarts;
280         else if (JSStringIsEqualToUTF8CString(optionName.get(), "TreatMedialCapitalAsWordStart"))
281             options |= kWKFindOptionsTreatMedialCapitalAsWordStart;
282         else if (JSStringIsEqualToUTF8CString(optionName.get(), "Backwards"))
283             options |= kWKFindOptionsBackwards;
284         else if (JSStringIsEqualToUTF8CString(optionName.get(), "WrapAround"))
285             options |= kWKFindOptionsWrapAround;
286         else if (JSStringIsEqualToUTF8CString(optionName.get(), "StartInSelection")) {
287             // FIXME: No kWKFindOptionsStartInSelection.
288         }
289     }
290
291     return WKBundlePageFindString(InjectedBundle::shared().page()->page(), toWK(target).get(), options);
292 }
293
294 void TestRunner::clearAllDatabases()
295 {
296     WKBundleClearAllDatabases(InjectedBundle::shared().bundle());
297 }
298
299 void TestRunner::setDatabaseQuota(uint64_t quota)
300 {
301     return WKBundleSetDatabaseQuota(InjectedBundle::shared().bundle(), quota);
302 }
303
304 void TestRunner::clearAllApplicationCaches()
305 {
306     WKBundleClearApplicationCache(InjectedBundle::shared().bundle());
307 }
308
309 void TestRunner::clearApplicationCacheForOrigin(JSStringRef origin)
310 {
311     WKBundleClearApplicationCacheForOrigin(InjectedBundle::shared().bundle(), toWK(origin).get());
312 }
313
314 void TestRunner::setAppCacheMaximumSize(uint64_t size)
315 {
316     WKBundleSetAppCacheMaximumSize(InjectedBundle::shared().bundle(), size);
317 }
318
319 long long TestRunner::applicationCacheDiskUsageForOrigin(JSStringRef origin)
320 {
321     return WKBundleGetAppCacheUsageForOrigin(InjectedBundle::shared().bundle(), toWK(origin).get());
322 }
323
324 void TestRunner::setApplicationCacheOriginQuota(unsigned long long bytes)
325 {
326     WKRetainPtr<WKStringRef> origin(AdoptWK, WKStringCreateWithUTF8CString("http://127.0.0.1:8000"));
327     WKBundleSetApplicationCacheOriginQuota(InjectedBundle::shared().bundle(), origin.get(), bytes);
328 }
329
330 void TestRunner::disallowIncreaseForApplicationCacheQuota()
331 {
332     m_disallowIncreaseForApplicationCacheQuota = true;
333 }
334
335 static inline JSValueRef stringArrayToJS(JSContextRef context, WKArrayRef strings)
336 {
337     const size_t count = WKArrayGetSize(strings);
338
339     OwnArrayPtr<JSValueRef> jsStringsArray = adoptArrayPtr(new JSValueRef[count]);
340     for (size_t i = 0; i < count; ++i) {
341         WKStringRef stringRef = static_cast<WKStringRef>(WKArrayGetItemAtIndex(strings, i));
342         JSRetainPtr<JSStringRef> stringJS = toJS(stringRef);
343         jsStringsArray[i] = JSValueMakeString(context, stringJS.get());
344     }
345
346     return JSObjectMakeArray(context, count, jsStringsArray.get(), 0);
347 }
348
349 JSValueRef TestRunner::originsWithApplicationCache()
350 {
351     WKRetainPtr<WKArrayRef> origins(AdoptWK, WKBundleCopyOriginsWithApplicationCache(InjectedBundle::shared().bundle()));
352
353     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::shared().page()->page());
354     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
355
356     return stringArrayToJS(context, origins.get());
357 }
358
359 bool TestRunner::isCommandEnabled(JSStringRef name)
360 {
361     return WKBundlePageIsEditingCommandEnabled(InjectedBundle::shared().page()->page(), toWK(name).get());
362 }
363
364 void TestRunner::setCanOpenWindows(bool)
365 {
366     // It's not clear if or why any tests require opening windows be forbidden.
367     // For now, just ignore this setting, and if we find later it's needed we can add it.
368 }
369
370 void TestRunner::setXSSAuditorEnabled(bool enabled)
371 {
372     WKRetainPtr<WKStringRef> key(AdoptWK, WKStringCreateWithUTF8CString("WebKitXSSAuditorEnabled"));
373     WKBundleOverrideBoolPreferenceForTestRunner(InjectedBundle::shared().bundle(), InjectedBundle::shared().pageGroup(), key.get(), enabled);
374 }
375
376 void TestRunner::setAllowUniversalAccessFromFileURLs(bool enabled)
377 {
378     WKBundleSetAllowUniversalAccessFromFileURLs(InjectedBundle::shared().bundle(), InjectedBundle::shared().pageGroup(), enabled);
379 }
380
381 void TestRunner::setAllowFileAccessFromFileURLs(bool enabled)
382 {
383     WKBundleSetAllowFileAccessFromFileURLs(InjectedBundle::shared().bundle(), InjectedBundle::shared().pageGroup(), enabled);
384 }
385
386 void TestRunner::setFrameFlatteningEnabled(bool enabled)
387 {
388     WKBundleSetFrameFlatteningEnabled(InjectedBundle::shared().bundle(), InjectedBundle::shared().pageGroup(), enabled);
389 }
390
391 void TestRunner::setPluginsEnabled(bool enabled)
392 {
393     WKBundleSetPluginsEnabled(InjectedBundle::shared().bundle(), InjectedBundle::shared().pageGroup(), enabled);
394 }
395
396 void TestRunner::setJavaScriptCanAccessClipboard(bool enabled)
397 {
398      WKBundleSetJavaScriptCanAccessClipboard(InjectedBundle::shared().bundle(), InjectedBundle::shared().pageGroup(), enabled);
399 }
400
401 void TestRunner::setPrivateBrowsingEnabled(bool enabled)
402 {
403      WKBundleSetPrivateBrowsingEnabled(InjectedBundle::shared().bundle(), InjectedBundle::shared().pageGroup(), enabled);
404 }
405
406 void TestRunner::setPopupBlockingEnabled(bool enabled)
407 {
408      WKBundleSetPopupBlockingEnabled(InjectedBundle::shared().bundle(), InjectedBundle::shared().pageGroup(), enabled);
409 }
410
411 void TestRunner::setAuthorAndUserStylesEnabled(bool enabled)
412 {
413      WKBundleSetAuthorAndUserStylesEnabled(InjectedBundle::shared().bundle(), InjectedBundle::shared().pageGroup(), enabled);
414 }
415
416 void TestRunner::addOriginAccessWhitelistEntry(JSStringRef sourceOrigin, JSStringRef destinationProtocol, JSStringRef destinationHost, bool allowDestinationSubdomains)
417 {
418     WKBundleAddOriginAccessWhitelistEntry(InjectedBundle::shared().bundle(), toWK(sourceOrigin).get(), toWK(destinationProtocol).get(), toWK(destinationHost).get(), allowDestinationSubdomains);
419 }
420
421 void TestRunner::removeOriginAccessWhitelistEntry(JSStringRef sourceOrigin, JSStringRef destinationProtocol, JSStringRef destinationHost, bool allowDestinationSubdomains)
422 {
423     WKBundleRemoveOriginAccessWhitelistEntry(InjectedBundle::shared().bundle(), toWK(sourceOrigin).get(), toWK(destinationProtocol).get(), toWK(destinationHost).get(), allowDestinationSubdomains);
424 }
425
426 bool TestRunner::isPageBoxVisible(int pageIndex)
427 {
428     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::shared().page()->page());
429     return WKBundleIsPageBoxVisible(InjectedBundle::shared().bundle(), mainFrame, pageIndex);
430 }
431
432 void TestRunner::setValueForUser(JSContextRef context, JSValueRef element, JSStringRef value)
433 {
434     if (!element || !JSValueIsObject(context, element))
435         return;
436
437     WKRetainPtr<WKBundleNodeHandleRef> nodeHandle(AdoptWK, WKBundleNodeHandleCreate(context, const_cast<JSObjectRef>(element)));
438     WKBundleNodeHandleSetHTMLInputElementValueForUser(nodeHandle.get(), toWK(value).get());
439 }
440
441 unsigned TestRunner::windowCount()
442 {
443     return InjectedBundle::shared().pageCount();
444 }
445
446 void TestRunner::clearBackForwardList()
447 {
448     WKBundleBackForwardListClear(WKBundlePageGetBackForwardList(InjectedBundle::shared().page()->page()));
449 }
450
451 // Object Creation
452
453 void TestRunner::makeWindowObject(JSContextRef context, JSObjectRef windowObject, JSValueRef* exception)
454 {
455     setProperty(context, windowObject, "testRunner", this, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete, exception);
456 }
457
458 void TestRunner::showWebInspector()
459 {
460 #if ENABLE(INSPECTOR)
461     WKBundleInspectorShow(WKBundlePageGetInspector(InjectedBundle::shared().page()->page()));
462 #endif // ENABLE(INSPECTOR)
463 }
464
465 void TestRunner::closeWebInspector()
466 {
467 #if ENABLE(INSPECTOR)
468     WKBundleInspectorClose(WKBundlePageGetInspector(InjectedBundle::shared().page()->page()));
469 #endif // ENABLE(INSPECTOR)
470 }
471
472 void TestRunner::evaluateInWebInspector(long callID, JSStringRef script)
473 {
474 #if ENABLE(INSPECTOR)
475     WKRetainPtr<WKStringRef> scriptWK = toWK(script);
476     WKBundleInspectorEvaluateScriptForTest(WKBundlePageGetInspector(InjectedBundle::shared().page()->page()), callID, scriptWK.get());
477 #endif // ENABLE(INSPECTOR)
478 }
479
480 typedef WTF::HashMap<unsigned, WKRetainPtr<WKBundleScriptWorldRef> > WorldMap;
481 static WorldMap& worldMap()
482 {
483     static WorldMap& map = *new WorldMap;
484     return map;
485 }
486
487 unsigned TestRunner::worldIDForWorld(WKBundleScriptWorldRef world)
488 {
489     WorldMap::const_iterator end = worldMap().end();
490     for (WorldMap::const_iterator it = worldMap().begin(); it != end; ++it) {
491         if (it->second == world)
492             return it->first;
493     }
494
495     return 0;
496 }
497
498 void TestRunner::evaluateScriptInIsolatedWorld(JSContextRef context, unsigned worldID, JSStringRef script)
499 {
500     // A worldID of 0 always corresponds to a new world. Any other worldID corresponds to a world
501     // that is created once and cached forever.
502     WKRetainPtr<WKBundleScriptWorldRef> world;
503     if (!worldID)
504         world.adopt(WKBundleScriptWorldCreateWorld());
505     else {
506         WKRetainPtr<WKBundleScriptWorldRef>& worldSlot = worldMap().add(worldID, 0).iterator->second;
507         if (!worldSlot)
508             worldSlot.adopt(WKBundleScriptWorldCreateWorld());
509         world = worldSlot;
510     }
511
512     WKBundleFrameRef frame = WKBundleFrameForJavaScriptContext(context);
513     if (!frame)
514         frame = WKBundlePageGetMainFrame(InjectedBundle::shared().page()->page());
515
516     JSGlobalContextRef jsContext = WKBundleFrameGetJavaScriptContextForWorld(frame, world.get());
517     JSEvaluateScript(jsContext, script, 0, 0, 0, 0); 
518 }
519
520 void TestRunner::setPOSIXLocale(JSStringRef locale)
521 {
522     char localeBuf[32];
523     JSStringGetUTF8CString(locale, localeBuf, sizeof(localeBuf));
524     setlocale(LC_ALL, localeBuf);
525 }
526
527 void TestRunner::setTextDirection(JSStringRef direction)
528 {
529     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::shared().page()->page());
530     return WKBundleFrameSetTextDirection(mainFrame, toWK(direction).get());
531 }
532     
533 void TestRunner::setShouldStayOnPageAfterHandlingBeforeUnload(bool shouldStayOnPage)
534 {
535     InjectedBundle::shared().postNewBeforeUnloadReturnValue(!shouldStayOnPage);
536 }
537
538 void TestRunner::setDefersLoading(bool shouldDeferLoading)
539 {
540     WKBundlePageSetDefersLoading(InjectedBundle::shared().page()->page(), shouldDeferLoading);
541 }
542
543 void TestRunner::setPageVisibility(JSStringRef state)
544 {
545     WebCore::PageVisibilityState visibilityState = WebCore::PageVisibilityStateVisible;
546
547     if (JSStringIsEqualToUTF8CString(state, "hidden"))
548         visibilityState = WebCore::PageVisibilityStateHidden;
549     else if (JSStringIsEqualToUTF8CString(state, "prerender"))
550         visibilityState = WebCore::PageVisibilityStatePrerender;
551     else if (JSStringIsEqualToUTF8CString(state, "preview"))
552         visibilityState = WebCore::PageVisibilityStatePreview;
553
554     WKBundleSetPageVisibilityState(InjectedBundle::shared().bundle(), InjectedBundle::shared().page()->page(), visibilityState, /* isInitialState */ false);
555 }
556
557 void TestRunner::resetPageVisibility()
558 {
559     WKBundleSetPageVisibilityState(InjectedBundle::shared().bundle(), InjectedBundle::shared().page()->page(), WebCore::PageVisibilityStateVisible, /* isInitialState */ true);
560 }
561
562 typedef WTF::HashMap<unsigned, JSValueRef> CallbackMap;
563 static CallbackMap& callbackMap()
564 {
565     static CallbackMap& map = *new CallbackMap;
566     return map;
567 }
568
569 enum {
570     AddChromeInputFieldCallbackID = 1,
571     RemoveChromeInputFieldCallbackID,
572     FocusWebViewCallbackID,
573     SetBackingScaleFactorCallbackID
574 };
575
576 static void cacheTestRunnerCallback(unsigned index, JSValueRef callback)
577 {
578     if (!callback)
579         return;
580
581     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::shared().page()->page());
582     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
583     JSValueProtect(context, callback);
584     callbackMap().add(index, callback);
585 }
586
587 static void callTestRunnerCallback(unsigned index)
588 {
589     if (!callbackMap().contains(index))
590         return;
591     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::shared().page()->page());
592     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
593     JSObjectRef callback = JSValueToObject(context, callbackMap().take(index), 0);
594     JSObjectCallAsFunction(context, callback, JSContextGetGlobalObject(context), 0, 0, 0);
595     JSValueUnprotect(context, callback);
596 }
597
598 unsigned TestRunner::workerThreadCount()
599 {
600     return WKBundleGetWorkerThreadCount(InjectedBundle::shared().bundle());
601 }
602
603 void TestRunner::addChromeInputField(JSValueRef callback)
604 {
605     cacheTestRunnerCallback(AddChromeInputFieldCallbackID, callback);
606     InjectedBundle::shared().postAddChromeInputField();
607 }
608
609 void TestRunner::removeChromeInputField(JSValueRef callback)
610 {
611     cacheTestRunnerCallback(RemoveChromeInputFieldCallbackID, callback);
612     InjectedBundle::shared().postRemoveChromeInputField();
613 }
614
615 void TestRunner::focusWebView(JSValueRef callback)
616 {
617     cacheTestRunnerCallback(FocusWebViewCallbackID, callback);
618     InjectedBundle::shared().postFocusWebView();
619 }
620
621 void TestRunner::setBackingScaleFactor(double backingScaleFactor, JSValueRef callback)
622 {
623     cacheTestRunnerCallback(SetBackingScaleFactorCallbackID, callback);
624     InjectedBundle::shared().postSetBackingScaleFactor(backingScaleFactor);
625 }
626
627 void TestRunner::setWindowIsKey(bool isKey)
628 {
629     InjectedBundle::shared().postSetWindowIsKey(isKey);
630 }
631
632 void TestRunner::callAddChromeInputFieldCallback()
633 {
634     callTestRunnerCallback(AddChromeInputFieldCallbackID);
635 }
636
637 void TestRunner::callRemoveChromeInputFieldCallback()
638 {
639     callTestRunnerCallback(RemoveChromeInputFieldCallbackID);
640 }
641
642 void TestRunner::callFocusWebViewCallback()
643 {
644     callTestRunnerCallback(FocusWebViewCallbackID);
645 }
646
647 void TestRunner::callSetBackingScaleFactorCallback()
648 {
649     callTestRunnerCallback(SetBackingScaleFactorCallbackID);
650 }
651
652 static inline bool toBool(JSStringRef value)
653 {
654     return JSStringIsEqualToUTF8CString(value, "true") || JSStringIsEqualToUTF8CString(value, "1");
655 }
656
657 void TestRunner::overridePreference(JSStringRef preference, JSStringRef value)
658 {
659     // FIXME: handle non-boolean preferences.
660     WKBundleOverrideBoolPreferenceForTestRunner(InjectedBundle::shared().bundle(), InjectedBundle::shared().pageGroup(), toWK(preference).get(), toBool(value));
661 }
662
663 void TestRunner::sendWebIntentResponse(JSStringRef reply)
664 {
665 #if ENABLE(WEB_INTENTS)
666     WKRetainPtr<WKBundleIntentRequestRef> currentRequest = InjectedBundle::shared().page()->currentIntentRequest();
667     if (!currentRequest)
668         return;
669
670     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::shared().page()->page());
671     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
672
673     if (reply) {
674         WKRetainPtr<WKSerializedScriptValueRef> serializedData(AdoptWK, WKSerializedScriptValueCreate(context, JSValueMakeString(context, reply), 0));
675         WKBundleIntentRequestPostResult(currentRequest.get(), serializedData.get());
676     } else {
677         JSRetainPtr<JSStringRef> errorReply(JSStringCreateWithUTF8CString("ERROR"));
678         WKRetainPtr<WKSerializedScriptValueRef> serializedData(AdoptWK, WKSerializedScriptValueCreate(context, JSValueMakeString(context, errorReply.get()), 0));
679         WKBundleIntentRequestPostFailure(currentRequest.get(), serializedData.get());
680     }
681 #endif
682 }
683
684 void TestRunner::deliverWebIntent(JSStringRef action, JSStringRef type, JSStringRef data)
685 {
686 #if ENABLE(WEB_INTENTS)
687     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::shared().page()->page());
688     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
689
690     WKRetainPtr<WKStringRef> actionWK = toWK(action);
691     WKRetainPtr<WKStringRef> typeWK = toWK(type);
692     WKRetainPtr<WKSerializedScriptValueRef> dataWK(AdoptWK, WKSerializedScriptValueCreate(context, JSValueMakeString(context, data), 0));
693
694     WKRetainPtr<WKMutableDictionaryRef> intentInitDict(AdoptWK, WKMutableDictionaryCreate());
695     WKRetainPtr<WKStringRef> actionKey(AdoptWK, WKStringCreateWithUTF8CString("action"));
696     WKDictionaryAddItem(intentInitDict.get(), actionKey.get(), actionWK.get());
697
698     WKRetainPtr<WKStringRef> typeKey(AdoptWK, WKStringCreateWithUTF8CString("type"));
699     WKDictionaryAddItem(intentInitDict.get(), typeKey.get(), typeWK.get());
700
701     WKRetainPtr<WKStringRef> dataKey(AdoptWK, WKStringCreateWithUTF8CString("data"));
702     WKDictionaryAddItem(intentInitDict.get(), dataKey.get(), dataWK.get());
703
704     WKRetainPtr<WKBundleIntentRef> wkIntent(AdoptWK, WKBundleIntentCreate(intentInitDict.get()));
705     WKBundlePageDeliverIntentToFrame(InjectedBundle::shared().page()->page(), mainFrame, wkIntent.get());
706 #endif
707 }
708
709 void TestRunner::setAlwaysAcceptCookies(bool accept)
710 {
711     WKBundleSetAlwaysAcceptCookies(InjectedBundle::shared().bundle(), accept);
712 }
713
714 double TestRunner::preciseTime()
715 {
716     return currentTime();
717 }
718
719 void TestRunner::setUserStyleSheetEnabled(bool enabled)
720 {
721     m_userStyleSheetEnabled = enabled;
722
723     WKRetainPtr<WKStringRef> emptyUrl = adoptWK(WKStringCreateWithUTF8CString(""));
724     WKStringRef location = enabled ? m_userStyleSheetLocation.get() : emptyUrl.get();
725     WKBundleSetUserStyleSheetLocation(InjectedBundle::shared().bundle(), InjectedBundle::shared().pageGroup(), location);
726 }
727
728 void TestRunner::setUserStyleSheetLocation(JSStringRef location)
729 {
730     m_userStyleSheetLocation = adoptWK(WKStringCreateWithJSString(location));
731
732     if (m_userStyleSheetEnabled)
733         setUserStyleSheetEnabled(true);
734 }
735
736 void TestRunner::setMinimumTimerInterval(double seconds)
737 {
738     WKBundleSetMinimumTimerInterval(InjectedBundle::shared().bundle(), InjectedBundle::shared().pageGroup(), seconds);
739 }
740
741 void TestRunner::setSpatialNavigationEnabled(bool enabled)
742 {
743     WKBundleSetSpatialNavigationEnabled(InjectedBundle::shared().bundle(), InjectedBundle::shared().pageGroup(), enabled);
744 }
745
746 void TestRunner::setTabKeyCyclesThroughElements(bool enabled)
747 {
748     WKBundleSetTabKeyCyclesThroughElements(InjectedBundle::shared().bundle(), InjectedBundle::shared().page()->page(), enabled);
749 }
750
751 void TestRunner::grantWebNotificationPermission(JSStringRef origin)
752 {
753     WKRetainPtr<WKStringRef> originWK = toWK(origin);
754     WKBundleSetWebNotificationPermission(InjectedBundle::shared().bundle(), InjectedBundle::shared().page()->page(), originWK.get(), true);
755 }
756
757 void TestRunner::denyWebNotificationPermission(JSStringRef origin)
758 {
759     WKRetainPtr<WKStringRef> originWK = toWK(origin);
760     WKBundleSetWebNotificationPermission(InjectedBundle::shared().bundle(), InjectedBundle::shared().page()->page(), originWK.get(), false);
761 }
762
763 void TestRunner::removeAllWebNotificationPermissions()
764 {
765     WKBundleRemoveAllWebNotificationPermissions(InjectedBundle::shared().bundle(), InjectedBundle::shared().page()->page());
766 }
767
768 void TestRunner::simulateWebNotificationClick(JSValueRef notification)
769 {
770     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::shared().page()->page());
771     JSContextRef context = WKBundleFrameGetJavaScriptContext(mainFrame);
772     uint64_t notificationID = WKBundleGetWebNotificationID(InjectedBundle::shared().bundle(), context, notification);
773     InjectedBundle::shared().postSimulateWebNotificationClick(notificationID);
774 }
775
776 void TestRunner::setGeolocationPermission(bool enabled)
777 {
778     // FIXME: this should be done by frame.
779     InjectedBundle::shared().setGeolocationPermission(enabled);
780 }
781
782 void TestRunner::setMockGeolocationPosition(double latitude, double longitude, double accuracy)
783 {
784     InjectedBundle::shared().setMockGeolocationPosition(latitude, longitude, accuracy);
785 }
786
787 bool TestRunner::callShouldCloseOnWebView()
788 {
789     WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(InjectedBundle::shared().page()->page());
790     return WKBundleFrameCallShouldCloseOnWebView(mainFrame);
791 }
792
793 } // namespace WTR