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