Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / content / shell / renderer / test_runner / test_runner.cc
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "content/shell/renderer/test_runner/test_runner.h"
6
7 #include <limits>
8
9 #include "base/logging.h"
10 #include "content/shell/common/test_runner/test_preferences.h"
11 #include "content/shell/renderer/test_runner/MockWebSpeechRecognizer.h"
12 #include "content/shell/renderer/test_runner/TestInterfaces.h"
13 #include "content/shell/renderer/test_runner/WebPermissions.h"
14 #include "content/shell/renderer/test_runner/WebTestDelegate.h"
15 #include "content/shell/renderer/test_runner/WebTestProxy.h"
16 #include "content/shell/renderer/test_runner/notification_presenter.h"
17 #include "gin/arguments.h"
18 #include "gin/array_buffer.h"
19 #include "gin/handle.h"
20 #include "gin/object_template_builder.h"
21 #include "gin/wrappable.h"
22 #include "third_party/WebKit/public/platform/WebCanvas.h"
23 #include "third_party/WebKit/public/platform/WebData.h"
24 #include "third_party/WebKit/public/platform/WebDeviceMotionData.h"
25 #include "third_party/WebKit/public/platform/WebDeviceOrientationData.h"
26 #include "third_party/WebKit/public/platform/WebPoint.h"
27 #include "third_party/WebKit/public/platform/WebURLResponse.h"
28 #include "third_party/WebKit/public/web/WebBindings.h"
29 #include "third_party/WebKit/public/web/WebDataSource.h"
30 #include "third_party/WebKit/public/web/WebDocument.h"
31 #include "third_party/WebKit/public/web/WebFindOptions.h"
32 #include "third_party/WebKit/public/web/WebFrame.h"
33 #include "third_party/WebKit/public/web/WebInputElement.h"
34 #include "third_party/WebKit/public/web/WebKit.h"
35 #include "third_party/WebKit/public/web/WebMIDIClientMock.h"
36 #include "third_party/WebKit/public/web/WebPageOverlay.h"
37 #include "third_party/WebKit/public/web/WebScriptSource.h"
38 #include "third_party/WebKit/public/web/WebSecurityPolicy.h"
39 #include "third_party/WebKit/public/web/WebSerializedScriptValue.h"
40 #include "third_party/WebKit/public/web/WebSettings.h"
41 #include "third_party/WebKit/public/web/WebSurroundingText.h"
42 #include "third_party/WebKit/public/web/WebView.h"
43 #include "third_party/skia/include/core/SkCanvas.h"
44
45 #if defined(__linux__) || defined(ANDROID)
46 #include "third_party/WebKit/public/web/linux/WebFontRendering.h"
47 #endif
48
49 using namespace blink;
50
51 namespace content {
52
53 namespace {
54
55 WebString V8StringToWebString(v8::Handle<v8::String> v8_str) {
56   int length = v8_str->Utf8Length() + 1;
57   scoped_ptr<char[]> chars(new char[length]);
58   v8_str->WriteUtf8(chars.get(), length);
59   return WebString::fromUTF8(chars.get());
60 }
61
62 class HostMethodTask : public WebMethodTask<TestRunner> {
63  public:
64   typedef void (TestRunner::*CallbackMethodType)();
65   HostMethodTask(TestRunner* object, CallbackMethodType callback)
66       : WebMethodTask<TestRunner>(object), callback_(callback) {}
67
68   virtual void runIfValid() OVERRIDE {
69     (m_object->*callback_)();
70   }
71
72  private:
73   CallbackMethodType callback_;
74 };
75
76 }  // namespace
77
78 class InvokeCallbackTask : public WebMethodTask<TestRunner> {
79  public:
80   InvokeCallbackTask(TestRunner* object, v8::Handle<v8::Function> callback)
81       : WebMethodTask<TestRunner>(object),
82         callback_(blink::mainThreadIsolate(), callback) {}
83
84   virtual void runIfValid() OVERRIDE {
85     v8::Isolate* isolate = blink::mainThreadIsolate();
86     v8::HandleScope handle_scope(isolate);
87     WebFrame* frame = m_object->web_view_->mainFrame();
88
89     v8::Handle<v8::Context> context = frame->mainWorldScriptContext();
90     if (context.IsEmpty())
91       return;
92
93     v8::Context::Scope context_scope(context);
94
95     frame->callFunctionEvenIfScriptDisabled(
96         v8::Local<v8::Function>::New(isolate, callback_),
97         context->Global(),
98         0,
99         NULL);
100   }
101
102  private:
103   v8::UniquePersistent<v8::Function> callback_;
104 };
105
106 class TestRunnerBindings : public gin::Wrappable<TestRunnerBindings> {
107  public:
108   static gin::WrapperInfo kWrapperInfo;
109
110   static void Install(base::WeakPtr<TestRunner> controller,
111                       WebFrame* frame);
112
113  private:
114   explicit TestRunnerBindings(
115       base::WeakPtr<TestRunner> controller);
116   virtual ~TestRunnerBindings();
117
118   // gin::Wrappable:
119   virtual gin::ObjectTemplateBuilder GetObjectTemplateBuilder(
120       v8::Isolate* isolate) OVERRIDE;
121
122   void NotifyDone();
123   void WaitUntilDone();
124   void QueueBackNavigation(int how_far_back);
125   void QueueForwardNavigation(int how_far_forward);
126   void QueueReload();
127   void QueueLoadingScript(const std::string& script);
128   void QueueNonLoadingScript(const std::string& script);
129   void QueueLoad(gin::Arguments* args);
130   void QueueLoadHTMLString(gin::Arguments* args);
131   void SetCustomPolicyDelegate(gin::Arguments* args);
132   void WaitForPolicyDelegate();
133   int WindowCount();
134   void SetCloseRemainingWindowsWhenComplete(gin::Arguments* args);
135   void ResetTestHelperControllers();
136   void SetTabKeyCyclesThroughElements(bool tab_key_cycles_through_elements);
137   void ExecCommand(gin::Arguments* args);
138   bool IsCommandEnabled(const std::string& command);
139   bool CallShouldCloseOnWebView();
140   void SetDomainRelaxationForbiddenForURLScheme(bool forbidden,
141                                                 const std::string& scheme);
142   v8::Handle<v8::Value> EvaluateScriptInIsolatedWorldAndReturnValue(
143       int world_id, const std::string& script);
144   void EvaluateScriptInIsolatedWorld(int world_id, const std::string& script);
145   void SetIsolatedWorldSecurityOrigin(int world_id,
146                                       v8::Handle<v8::Value> origin);
147   void SetIsolatedWorldContentSecurityPolicy(int world_id,
148                                              const std::string& policy);
149   void AddOriginAccessWhitelistEntry(const std::string& source_origin,
150                                      const std::string& destination_protocol,
151                                      const std::string& destination_host,
152                                      bool allow_destination_subdomains);
153   void RemoveOriginAccessWhitelistEntry(const std::string& source_origin,
154                                         const std::string& destination_protocol,
155                                         const std::string& destination_host,
156                                         bool allow_destination_subdomains);
157   bool HasCustomPageSizeStyle(int page_index);
158   void ForceRedSelectionColors();
159   void InjectStyleSheet(const std::string& source_code, bool all_frames);
160   bool FindString(const std::string& search_text,
161                   const std::vector<std::string>& options_array);
162   std::string SelectionAsMarkup();
163   void SetTextSubpixelPositioning(bool value);
164   void SetPageVisibility(const std::string& new_visibility);
165   void SetTextDirection(const std::string& direction_name);
166   void UseUnfortunateSynchronousResizeMode();
167   bool EnableAutoResizeMode(int min_width,
168                             int min_height,
169                             int max_width,
170                             int max_height);
171   bool DisableAutoResizeMode(int new_width, int new_height);
172   void SetMockDeviceMotion(gin::Arguments* args);
173   void SetMockDeviceOrientation(gin::Arguments* args);
174   void SetMockScreenOrientation(const std::string& orientation);
175   void DidAcquirePointerLock();
176   void DidNotAcquirePointerLock();
177   void DidLosePointerLock();
178   void SetPointerLockWillFailSynchronously();
179   void SetPointerLockWillRespondAsynchronously();
180   void SetPopupBlockingEnabled(bool block_popups);
181   void SetJavaScriptCanAccessClipboard(bool can_access);
182   void SetXSSAuditorEnabled(bool enabled);
183   void SetAllowUniversalAccessFromFileURLs(bool allow);
184   void SetAllowFileAccessFromFileURLs(bool allow);
185   void OverridePreference(const std::string key, v8::Handle<v8::Value> value);
186   void SetPluginsEnabled(bool enabled);
187   void DumpEditingCallbacks();
188   void DumpAsText();
189   void DumpAsTextWithPixelResults();
190   void DumpChildFrameScrollPositions();
191   void DumpChildFramesAsText();
192   void DumpIconChanges();
193   void SetAudioData(const gin::ArrayBufferView& view);
194   void DumpFrameLoadCallbacks();
195   void DumpPingLoaderCallbacks();
196   void DumpUserGestureInFrameLoadCallbacks();
197   void DumpTitleChanges();
198   void DumpCreateView();
199   void SetCanOpenWindows();
200   void DumpResourceLoadCallbacks();
201   void DumpResourceRequestCallbacks();
202   void DumpResourceResponseMIMETypes();
203   void SetImagesAllowed(bool allowed);
204   void SetScriptsAllowed(bool allowed);
205   void SetStorageAllowed(bool allowed);
206   void SetPluginsAllowed(bool allowed);
207   void SetAllowDisplayOfInsecureContent(bool allowed);
208   void SetAllowRunningOfInsecureContent(bool allowed);
209   void DumpPermissionClientCallbacks();
210   void DumpWindowStatusChanges();
211   void DumpProgressFinishedCallback();
212   void DumpSpellCheckCallbacks();
213   void DumpBackForwardList();
214   void DumpSelectionRect();
215   void SetPrinting();
216   void SetShouldStayOnPageAfterHandlingBeforeUnload(bool value);
217   void SetWillSendRequestClearHeader(const std::string& header);
218   void DumpResourceRequestPriorities();
219   void SetUseMockTheme(bool use);
220   void WaitUntilExternalURLLoad();
221   void ShowWebInspector(gin::Arguments* args);
222   void CloseWebInspector();
223   bool IsChooserShown();
224   void EvaluateInWebInspector(int call_id, const std::string& script);
225   void ClearAllDatabases();
226   void SetDatabaseQuota(int quota);
227   void SetAlwaysAcceptCookies(bool accept);
228   void SetWindowIsKey(bool value);
229   std::string PathToLocalResource(const std::string& path);
230   void SetBackingScaleFactor(double value, v8::Handle<v8::Function> callback);
231   void SetColorProfile(const std::string& name,
232                        v8::Handle<v8::Function> callback);
233   void SetPOSIXLocale(const std::string& locale);
234   void SetMIDIAccessorResult(bool result);
235   void SetMIDISysexPermission(bool value);
236   void GrantWebNotificationPermission(gin::Arguments* args);
237   bool SimulateWebNotificationClick(const std::string& value);
238   void AddMockSpeechRecognitionResult(const std::string& transcript,
239                                       double confidence);
240   void SetMockSpeechRecognitionError(const std::string& error,
241                                      const std::string& message);
242   bool WasMockSpeechRecognitionAborted();
243   void AddWebPageOverlay();
244   void RemoveWebPageOverlay();
245   void DisplayAsync();
246   void DisplayAsyncThen(v8::Handle<v8::Function> callback);
247   void SetCustomTextOutput(std::string output);
248
249   bool GlobalFlag();
250   void SetGlobalFlag(bool value);
251   std::string PlatformName();
252   std::string TooltipText();
253   bool DisableNotifyDone();
254   int WebHistoryItemCount();
255   bool InterceptPostMessage();
256   void SetInterceptPostMessage(bool value);
257
258   void NotImplemented(const gin::Arguments& args);
259
260   base::WeakPtr<TestRunner> runner_;
261
262   DISALLOW_COPY_AND_ASSIGN(TestRunnerBindings);
263 };
264
265 gin::WrapperInfo TestRunnerBindings::kWrapperInfo = {
266     gin::kEmbedderNativeGin};
267
268 // static
269 void TestRunnerBindings::Install(base::WeakPtr<TestRunner> runner,
270                                  WebFrame* frame) {
271   v8::Isolate* isolate = blink::mainThreadIsolate();
272   v8::HandleScope handle_scope(isolate);
273   v8::Handle<v8::Context> context = frame->mainWorldScriptContext();
274   if (context.IsEmpty())
275     return;
276
277   v8::Context::Scope context_scope(context);
278
279   gin::Handle<TestRunnerBindings> bindings =
280       gin::CreateHandle(isolate, new TestRunnerBindings(runner));
281   if (bindings.IsEmpty())
282     return;
283   v8::Handle<v8::Object> global = context->Global();
284   v8::Handle<v8::Value> v8_bindings = bindings.ToV8();
285   global->Set(gin::StringToV8(isolate, "testRunner"), v8_bindings);
286   global->Set(gin::StringToV8(isolate, "layoutTestController"), v8_bindings);
287 }
288
289 TestRunnerBindings::TestRunnerBindings(base::WeakPtr<TestRunner> runner)
290     : runner_(runner) {}
291
292 TestRunnerBindings::~TestRunnerBindings() {}
293
294 gin::ObjectTemplateBuilder TestRunnerBindings::GetObjectTemplateBuilder(
295     v8::Isolate* isolate) {
296   return gin::Wrappable<TestRunnerBindings>::GetObjectTemplateBuilder(isolate)
297       // Methods controlling test execution.
298       .SetMethod("notifyDone", &TestRunnerBindings::NotifyDone)
299       .SetMethod("waitUntilDone", &TestRunnerBindings::WaitUntilDone)
300       .SetMethod("queueBackNavigation",
301                  &TestRunnerBindings::QueueBackNavigation)
302       .SetMethod("queueForwardNavigation",
303                  &TestRunnerBindings::QueueForwardNavigation)
304       .SetMethod("queueReload", &TestRunnerBindings::QueueReload)
305       .SetMethod("queueLoadingScript", &TestRunnerBindings::QueueLoadingScript)
306       .SetMethod("queueNonLoadingScript",
307                  &TestRunnerBindings::QueueNonLoadingScript)
308       .SetMethod("queueLoad", &TestRunnerBindings::QueueLoad)
309       .SetMethod("queueLoadHTMLString",
310                  &TestRunnerBindings::QueueLoadHTMLString)
311       .SetMethod("setCustomPolicyDelegate",
312                  &TestRunnerBindings::SetCustomPolicyDelegate)
313       .SetMethod("waitForPolicyDelegate",
314                  &TestRunnerBindings::WaitForPolicyDelegate)
315       .SetMethod("windowCount", &TestRunnerBindings::WindowCount)
316       .SetMethod("setCloseRemainingWindowsWhenComplete",
317                  &TestRunnerBindings::SetCloseRemainingWindowsWhenComplete)
318       .SetMethod("resetTestHelperControllers",
319                  &TestRunnerBindings::ResetTestHelperControllers)
320       .SetMethod("setTabKeyCyclesThroughElements",
321                  &TestRunnerBindings::SetTabKeyCyclesThroughElements)
322       .SetMethod("execCommand", &TestRunnerBindings::ExecCommand)
323       .SetMethod("isCommandEnabled", &TestRunnerBindings::IsCommandEnabled)
324       .SetMethod("callShouldCloseOnWebView",
325                  &TestRunnerBindings::CallShouldCloseOnWebView)
326       .SetMethod("setDomainRelaxationForbiddenForURLScheme",
327                  &TestRunnerBindings::SetDomainRelaxationForbiddenForURLScheme)
328       .SetMethod(
329            "evaluateScriptInIsolatedWorldAndReturnValue",
330            &TestRunnerBindings::EvaluateScriptInIsolatedWorldAndReturnValue)
331       .SetMethod("evaluateScriptInIsolatedWorld",
332                  &TestRunnerBindings::EvaluateScriptInIsolatedWorld)
333       .SetMethod("setIsolatedWorldSecurityOrigin",
334                  &TestRunnerBindings::SetIsolatedWorldSecurityOrigin)
335       .SetMethod("setIsolatedWorldContentSecurityPolicy",
336                  &TestRunnerBindings::SetIsolatedWorldContentSecurityPolicy)
337       .SetMethod("addOriginAccessWhitelistEntry",
338                  &TestRunnerBindings::AddOriginAccessWhitelistEntry)
339       .SetMethod("removeOriginAccessWhitelistEntry",
340                  &TestRunnerBindings::RemoveOriginAccessWhitelistEntry)
341       .SetMethod("hasCustomPageSizeStyle",
342                  &TestRunnerBindings::HasCustomPageSizeStyle)
343       .SetMethod("forceRedSelectionColors",
344                  &TestRunnerBindings::ForceRedSelectionColors)
345       .SetMethod("injectStyleSheet", &TestRunnerBindings::InjectStyleSheet)
346       .SetMethod("findString", &TestRunnerBindings::FindString)
347       .SetMethod("selectionAsMarkup", &TestRunnerBindings::SelectionAsMarkup)
348       .SetMethod("setTextSubpixelPositioning",
349                  &TestRunnerBindings::SetTextSubpixelPositioning)
350       .SetMethod("setPageVisibility", &TestRunnerBindings::SetPageVisibility)
351       .SetMethod("setTextDirection", &TestRunnerBindings::SetTextDirection)
352       .SetMethod("useUnfortunateSynchronousResizeMode",
353                  &TestRunnerBindings::UseUnfortunateSynchronousResizeMode)
354       .SetMethod("enableAutoResizeMode",
355                  &TestRunnerBindings::EnableAutoResizeMode)
356       .SetMethod("disableAutoResizeMode",
357                  &TestRunnerBindings::DisableAutoResizeMode)
358       .SetMethod("setMockDeviceMotion",
359                  &TestRunnerBindings::SetMockDeviceMotion)
360       .SetMethod("setMockDeviceOrientation",
361                  &TestRunnerBindings::SetMockDeviceOrientation)
362       .SetMethod("setMockScreenOrientation",
363                  &TestRunnerBindings::SetMockScreenOrientation)
364       .SetMethod("didAcquirePointerLock",
365                  &TestRunnerBindings::DidAcquirePointerLock)
366       .SetMethod("didNotAcquirePointerLock",
367                  &TestRunnerBindings::DidNotAcquirePointerLock)
368       .SetMethod("didLosePointerLock", &TestRunnerBindings::DidLosePointerLock)
369       .SetMethod("setPointerLockWillFailSynchronously",
370                  &TestRunnerBindings::SetPointerLockWillFailSynchronously)
371       .SetMethod("setPointerLockWillRespondAsynchronously",
372                  &TestRunnerBindings::SetPointerLockWillRespondAsynchronously)
373       .SetMethod("setPopupBlockingEnabled",
374                  &TestRunnerBindings::SetPopupBlockingEnabled)
375       .SetMethod("setJavaScriptCanAccessClipboard",
376                  &TestRunnerBindings::SetJavaScriptCanAccessClipboard)
377       .SetMethod("setXSSAuditorEnabled",
378                  &TestRunnerBindings::SetXSSAuditorEnabled)
379       .SetMethod("setAllowUniversalAccessFromFileURLs",
380                  &TestRunnerBindings::SetAllowUniversalAccessFromFileURLs)
381       .SetMethod("setAllowFileAccessFromFileURLs",
382                  &TestRunnerBindings::SetAllowFileAccessFromFileURLs)
383       .SetMethod("overridePreference", &TestRunnerBindings::OverridePreference)
384       .SetMethod("setPluginsEnabled", &TestRunnerBindings::SetPluginsEnabled)
385       .SetMethod("dumpEditingCallbacks",
386                  &TestRunnerBindings::DumpEditingCallbacks)
387       .SetMethod("dumpAsText", &TestRunnerBindings::DumpAsText)
388       .SetMethod("dumpAsTextWithPixelResults",
389                  &TestRunnerBindings::DumpAsTextWithPixelResults)
390       .SetMethod("dumpChildFrameScrollPositions",
391                  &TestRunnerBindings::DumpChildFrameScrollPositions)
392       .SetMethod("dumpChildFramesAsText",
393                  &TestRunnerBindings::DumpChildFramesAsText)
394       .SetMethod("dumpIconChanges", &TestRunnerBindings::DumpIconChanges)
395       .SetMethod("setAudioData", &TestRunnerBindings::SetAudioData)
396       .SetMethod("dumpFrameLoadCallbacks",
397                  &TestRunnerBindings::DumpFrameLoadCallbacks)
398       .SetMethod("dumpPingLoaderCallbacks",
399                  &TestRunnerBindings::DumpPingLoaderCallbacks)
400       .SetMethod("dumpUserGestureInFrameLoadCallbacks",
401                  &TestRunnerBindings::DumpUserGestureInFrameLoadCallbacks)
402       .SetMethod("dumpTitleChanges", &TestRunnerBindings::DumpTitleChanges)
403       .SetMethod("dumpCreateView", &TestRunnerBindings::DumpCreateView)
404       .SetMethod("setCanOpenWindows", &TestRunnerBindings::SetCanOpenWindows)
405       .SetMethod("dumpResourceLoadCallbacks",
406                  &TestRunnerBindings::DumpResourceLoadCallbacks)
407       .SetMethod("dumpResourceRequestCallbacks",
408                  &TestRunnerBindings::DumpResourceRequestCallbacks)
409       .SetMethod("dumpResourceResponseMIMETypes",
410                  &TestRunnerBindings::DumpResourceResponseMIMETypes)
411       .SetMethod("setImagesAllowed", &TestRunnerBindings::SetImagesAllowed)
412       .SetMethod("setScriptsAllowed", &TestRunnerBindings::SetScriptsAllowed)
413       .SetMethod("setStorageAllowed", &TestRunnerBindings::SetStorageAllowed)
414       .SetMethod("setPluginsAllowed", &TestRunnerBindings::SetPluginsAllowed)
415       .SetMethod("setAllowDisplayOfInsecureContent",
416                  &TestRunnerBindings::SetAllowDisplayOfInsecureContent)
417       .SetMethod("setAllowRunningOfInsecureContent",
418                  &TestRunnerBindings::SetAllowRunningOfInsecureContent)
419       .SetMethod("dumpPermissionClientCallbacks",
420                  &TestRunnerBindings::DumpPermissionClientCallbacks)
421       .SetMethod("dumpWindowStatusChanges",
422                  &TestRunnerBindings::DumpWindowStatusChanges)
423       .SetMethod("dumpProgressFinishedCallback",
424                  &TestRunnerBindings::DumpProgressFinishedCallback)
425       .SetMethod("dumpSpellCheckCallbacks",
426                  &TestRunnerBindings::DumpSpellCheckCallbacks)
427       .SetMethod("dumpBackForwardList",
428                  &TestRunnerBindings::DumpBackForwardList)
429       .SetMethod("dumpSelectionRect", &TestRunnerBindings::DumpSelectionRect)
430       .SetMethod("setPrinting", &TestRunnerBindings::SetPrinting)
431       .SetMethod(
432            "setShouldStayOnPageAfterHandlingBeforeUnload",
433            &TestRunnerBindings::SetShouldStayOnPageAfterHandlingBeforeUnload)
434       .SetMethod("setWillSendRequestClearHeader",
435                  &TestRunnerBindings::SetWillSendRequestClearHeader)
436       .SetMethod("dumpResourceRequestPriorities",
437                  &TestRunnerBindings::DumpResourceRequestPriorities)
438       .SetMethod("setUseMockTheme", &TestRunnerBindings::SetUseMockTheme)
439       .SetMethod("waitUntilExternalURLLoad",
440                  &TestRunnerBindings::WaitUntilExternalURLLoad)
441       .SetMethod("showWebInspector", &TestRunnerBindings::ShowWebInspector)
442       .SetMethod("closeWebInspector", &TestRunnerBindings::CloseWebInspector)
443       .SetMethod("isChooserShown", &TestRunnerBindings::IsChooserShown)
444       .SetMethod("evaluateInWebInspector",
445                  &TestRunnerBindings::EvaluateInWebInspector)
446       .SetMethod("clearAllDatabases", &TestRunnerBindings::ClearAllDatabases)
447       .SetMethod("setDatabaseQuota", &TestRunnerBindings::SetDatabaseQuota)
448       .SetMethod("setAlwaysAcceptCookies",
449                  &TestRunnerBindings::SetAlwaysAcceptCookies)
450       .SetMethod("setWindowIsKey", &TestRunnerBindings::SetWindowIsKey)
451       .SetMethod("pathToLocalResource",
452                  &TestRunnerBindings::PathToLocalResource)
453       .SetMethod("setBackingScaleFactor",
454                  &TestRunnerBindings::SetBackingScaleFactor)
455       .SetMethod("setColorProfile",
456                  &TestRunnerBindings::SetColorProfile)
457       .SetMethod("setPOSIXLocale", &TestRunnerBindings::SetPOSIXLocale)
458       .SetMethod("setMIDIAccessorResult",
459                  &TestRunnerBindings::SetMIDIAccessorResult)
460       .SetMethod("setMIDISysexPermission",
461                  &TestRunnerBindings::SetMIDISysexPermission)
462       .SetMethod("grantWebNotificationPermission",
463                  &TestRunnerBindings::GrantWebNotificationPermission)
464       .SetMethod("simulateWebNotificationClick",
465                  &TestRunnerBindings::SimulateWebNotificationClick)
466       .SetMethod("addMockSpeechRecognitionResult",
467                  &TestRunnerBindings::AddMockSpeechRecognitionResult)
468       .SetMethod("setMockSpeechRecognitionError",
469                  &TestRunnerBindings::SetMockSpeechRecognitionError)
470       .SetMethod("wasMockSpeechRecognitionAborted",
471                  &TestRunnerBindings::WasMockSpeechRecognitionAborted)
472       .SetMethod("addWebPageOverlay", &TestRunnerBindings::AddWebPageOverlay)
473       .SetMethod("removeWebPageOverlay",
474                  &TestRunnerBindings::RemoveWebPageOverlay)
475       .SetMethod("displayAsync", &TestRunnerBindings::DisplayAsync)
476       .SetMethod("displayAsyncThen", &TestRunnerBindings::DisplayAsyncThen)
477       .SetMethod("setCustomTextOutput",
478                  &TestRunnerBindings::SetCustomTextOutput)
479
480       // Properties.
481       .SetProperty("globalFlag",
482                    &TestRunnerBindings::GlobalFlag,
483                    &TestRunnerBindings::SetGlobalFlag)
484       .SetProperty("platformName", &TestRunnerBindings::PlatformName)
485       .SetProperty("tooltipText", &TestRunnerBindings::TooltipText)
486       .SetProperty("disableNotifyDone", &TestRunnerBindings::DisableNotifyDone)
487       // webHistoryItemCount is used by tests in LayoutTests\http\tests\history
488       .SetProperty("webHistoryItemCount",
489                    &TestRunnerBindings::WebHistoryItemCount)
490       .SetProperty("interceptPostMessage",
491                    &TestRunnerBindings::InterceptPostMessage,
492                    &TestRunnerBindings::SetInterceptPostMessage)
493
494       // The following are stubs.
495       .SetMethod("dumpDatabaseCallbacks", &TestRunnerBindings::NotImplemented)
496       .SetMethod("setIconDatabaseEnabled", &TestRunnerBindings::NotImplemented)
497       .SetMethod("setScrollbarPolicy", &TestRunnerBindings::NotImplemented)
498       .SetMethod("clearAllApplicationCaches",
499                  &TestRunnerBindings::NotImplemented)
500       .SetMethod("clearApplicationCacheForOrigin",
501                  &TestRunnerBindings::NotImplemented)
502       .SetMethod("clearBackForwardList", &TestRunnerBindings::NotImplemented)
503       .SetMethod("keepWebHistory", &TestRunnerBindings::NotImplemented)
504       .SetMethod("setApplicationCacheOriginQuota",
505                  &TestRunnerBindings::NotImplemented)
506       .SetMethod("setCallCloseOnWebViews", &TestRunnerBindings::NotImplemented)
507       .SetMethod("setMainFrameIsFirstResponder",
508                  &TestRunnerBindings::NotImplemented)
509       .SetMethod("setUseDashboardCompatibilityMode",
510                  &TestRunnerBindings::NotImplemented)
511       .SetMethod("deleteAllLocalStorage", &TestRunnerBindings::NotImplemented)
512       .SetMethod("localStorageDiskUsageForOrigin",
513                  &TestRunnerBindings::NotImplemented)
514       .SetMethod("originsWithLocalStorage", &TestRunnerBindings::NotImplemented)
515       .SetMethod("deleteLocalStorageForOrigin",
516                  &TestRunnerBindings::NotImplemented)
517       .SetMethod("observeStorageTrackerNotifications",
518                  &TestRunnerBindings::NotImplemented)
519       .SetMethod("syncLocalStorage", &TestRunnerBindings::NotImplemented)
520       .SetMethod("addDisallowedURL", &TestRunnerBindings::NotImplemented)
521       .SetMethod("applicationCacheDiskUsageForOrigin",
522                  &TestRunnerBindings::NotImplemented)
523       .SetMethod("abortModal", &TestRunnerBindings::NotImplemented)
524
525       // Aliases.
526       // Used at fast/dom/assign-to-window-status.html
527       .SetMethod("dumpStatusCallbacks",
528                  &TestRunnerBindings::DumpWindowStatusChanges);
529 }
530
531 void TestRunnerBindings::NotifyDone() {
532   if (runner_)
533     runner_->NotifyDone();
534 }
535
536 void TestRunnerBindings::WaitUntilDone() {
537   if (runner_)
538     runner_->WaitUntilDone();
539 }
540
541 void TestRunnerBindings::QueueBackNavigation(int how_far_back) {
542   if (runner_)
543     runner_->QueueBackNavigation(how_far_back);
544 }
545
546 void TestRunnerBindings::QueueForwardNavigation(int how_far_forward) {
547   if (runner_)
548     runner_->QueueForwardNavigation(how_far_forward);
549 }
550
551 void TestRunnerBindings::QueueReload() {
552   if (runner_)
553     runner_->QueueReload();
554 }
555
556 void TestRunnerBindings::QueueLoadingScript(const std::string& script) {
557   if (runner_)
558     runner_->QueueLoadingScript(script);
559 }
560
561 void TestRunnerBindings::QueueNonLoadingScript(const std::string& script) {
562   if (runner_)
563     runner_->QueueNonLoadingScript(script);
564 }
565
566 void TestRunnerBindings::QueueLoad(gin::Arguments* args) {
567   if (runner_) {
568     std::string url;
569     std::string target;
570     args->GetNext(&url);
571     args->GetNext(&target);
572     runner_->QueueLoad(url, target);
573   }
574 }
575
576 void TestRunnerBindings::QueueLoadHTMLString(gin::Arguments* args) {
577   if (runner_)
578     runner_->QueueLoadHTMLString(args);
579 }
580
581 void TestRunnerBindings::SetCustomPolicyDelegate(gin::Arguments* args) {
582   if (runner_)
583     runner_->SetCustomPolicyDelegate(args);
584 }
585
586 void TestRunnerBindings::WaitForPolicyDelegate() {
587   if (runner_)
588     runner_->WaitForPolicyDelegate();
589 }
590
591 int TestRunnerBindings::WindowCount() {
592   if (runner_)
593     return runner_->WindowCount();
594   return 0;
595 }
596
597 void TestRunnerBindings::SetCloseRemainingWindowsWhenComplete(
598     gin::Arguments* args) {
599   if (!runner_)
600     return;
601
602   // In the original implementation, nothing happens if the argument is
603   // ommitted.
604   bool close_remaining_windows = false;
605   if (args->GetNext(&close_remaining_windows))
606     runner_->SetCloseRemainingWindowsWhenComplete(close_remaining_windows);
607 }
608
609 void TestRunnerBindings::ResetTestHelperControllers() {
610   if (runner_)
611     runner_->ResetTestHelperControllers();
612 }
613
614 void TestRunnerBindings::SetTabKeyCyclesThroughElements(
615     bool tab_key_cycles_through_elements) {
616   if (runner_)
617     runner_->SetTabKeyCyclesThroughElements(tab_key_cycles_through_elements);
618 }
619
620 void TestRunnerBindings::ExecCommand(gin::Arguments* args) {
621   if (runner_)
622     runner_->ExecCommand(args);
623 }
624
625 bool TestRunnerBindings::IsCommandEnabled(const std::string& command) {
626   if (runner_)
627     return runner_->IsCommandEnabled(command);
628   return false;
629 }
630
631 bool TestRunnerBindings::CallShouldCloseOnWebView() {
632   if (runner_)
633     return runner_->CallShouldCloseOnWebView();
634   return false;
635 }
636
637 void TestRunnerBindings::SetDomainRelaxationForbiddenForURLScheme(
638     bool forbidden, const std::string& scheme) {
639   if (runner_)
640     runner_->SetDomainRelaxationForbiddenForURLScheme(forbidden, scheme);
641 }
642
643 v8::Handle<v8::Value>
644 TestRunnerBindings::EvaluateScriptInIsolatedWorldAndReturnValue(
645     int world_id, const std::string& script) {
646   if (!runner_)
647     return v8::Handle<v8::Value>();
648   return runner_->EvaluateScriptInIsolatedWorldAndReturnValue(world_id,
649                                                               script);
650 }
651
652 void TestRunnerBindings::EvaluateScriptInIsolatedWorld(
653     int world_id, const std::string& script) {
654   if (runner_)
655     runner_->EvaluateScriptInIsolatedWorld(world_id, script);
656 }
657
658 void TestRunnerBindings::SetIsolatedWorldSecurityOrigin(
659     int world_id, v8::Handle<v8::Value> origin) {
660   if (runner_)
661     runner_->SetIsolatedWorldSecurityOrigin(world_id, origin);
662 }
663
664 void TestRunnerBindings::SetIsolatedWorldContentSecurityPolicy(
665     int world_id, const std::string& policy) {
666   if (runner_)
667     runner_->SetIsolatedWorldContentSecurityPolicy(world_id, policy);
668 }
669
670 void TestRunnerBindings::AddOriginAccessWhitelistEntry(
671     const std::string& source_origin,
672     const std::string& destination_protocol,
673     const std::string& destination_host,
674     bool allow_destination_subdomains) {
675   if (runner_) {
676     runner_->AddOriginAccessWhitelistEntry(source_origin,
677                                            destination_protocol,
678                                            destination_host,
679                                            allow_destination_subdomains);
680   }
681 }
682
683 void TestRunnerBindings::RemoveOriginAccessWhitelistEntry(
684     const std::string& source_origin,
685     const std::string& destination_protocol,
686     const std::string& destination_host,
687     bool allow_destination_subdomains) {
688   if (runner_) {
689     runner_->RemoveOriginAccessWhitelistEntry(source_origin,
690                                               destination_protocol,
691                                               destination_host,
692                                               allow_destination_subdomains);
693   }
694 }
695
696 bool TestRunnerBindings::HasCustomPageSizeStyle(int page_index) {
697   if (runner_)
698     return runner_->HasCustomPageSizeStyle(page_index);
699   return false;
700 }
701
702 void TestRunnerBindings::ForceRedSelectionColors() {
703   if (runner_)
704     runner_->ForceRedSelectionColors();
705 }
706
707 void TestRunnerBindings::InjectStyleSheet(const std::string& source_code,
708                                           bool all_frames) {
709   if (runner_)
710     runner_->InjectStyleSheet(source_code, all_frames);
711 }
712
713 bool TestRunnerBindings::FindString(
714     const std::string& search_text,
715     const std::vector<std::string>& options_array) {
716   if (runner_)
717     return runner_->FindString(search_text, options_array);
718   return false;
719 }
720
721 std::string TestRunnerBindings::SelectionAsMarkup() {
722   if (runner_)
723     return runner_->SelectionAsMarkup();
724   return std::string();
725 }
726
727 void TestRunnerBindings::SetTextSubpixelPositioning(bool value) {
728   if (runner_)
729     runner_->SetTextSubpixelPositioning(value);
730 }
731
732 void TestRunnerBindings::SetPageVisibility(const std::string& new_visibility) {
733   if (runner_)
734     runner_->SetPageVisibility(new_visibility);
735 }
736
737 void TestRunnerBindings::SetTextDirection(const std::string& direction_name) {
738   if (runner_)
739     runner_->SetTextDirection(direction_name);
740 }
741
742 void TestRunnerBindings::UseUnfortunateSynchronousResizeMode() {
743   if (runner_)
744     runner_->UseUnfortunateSynchronousResizeMode();
745 }
746
747 bool TestRunnerBindings::EnableAutoResizeMode(int min_width,
748                                               int min_height,
749                                               int max_width,
750                                               int max_height) {
751   if (runner_) {
752     return runner_->EnableAutoResizeMode(min_width, min_height,
753                                          max_width, max_height);
754   }
755   return false;
756 }
757
758 bool TestRunnerBindings::DisableAutoResizeMode(int new_width, int new_height) {
759   if (runner_)
760     return runner_->DisableAutoResizeMode(new_width, new_height);
761   return false;
762 }
763
764 void TestRunnerBindings::SetMockDeviceMotion(gin::Arguments* args) {
765   if (!runner_)
766     return;
767
768   bool has_acceleration_x;
769   double acceleration_x;
770   bool has_acceleration_y;
771   double acceleration_y;
772   bool has_acceleration_z;
773   double acceleration_z;
774   bool has_acceleration_including_gravity_x;
775   double acceleration_including_gravity_x;
776   bool has_acceleration_including_gravity_y;
777   double acceleration_including_gravity_y;
778   bool has_acceleration_including_gravity_z;
779   double acceleration_including_gravity_z;
780   bool has_rotation_rate_alpha;
781   double rotation_rate_alpha;
782   bool has_rotation_rate_beta;
783   double rotation_rate_beta;
784   bool has_rotation_rate_gamma;
785   double rotation_rate_gamma;
786   double interval;
787
788   args->GetNext(&has_acceleration_x);
789   args->GetNext(& acceleration_x);
790   args->GetNext(&has_acceleration_y);
791   args->GetNext(& acceleration_y);
792   args->GetNext(&has_acceleration_z);
793   args->GetNext(& acceleration_z);
794   args->GetNext(&has_acceleration_including_gravity_x);
795   args->GetNext(& acceleration_including_gravity_x);
796   args->GetNext(&has_acceleration_including_gravity_y);
797   args->GetNext(& acceleration_including_gravity_y);
798   args->GetNext(&has_acceleration_including_gravity_z);
799   args->GetNext(& acceleration_including_gravity_z);
800   args->GetNext(&has_rotation_rate_alpha);
801   args->GetNext(& rotation_rate_alpha);
802   args->GetNext(&has_rotation_rate_beta);
803   args->GetNext(& rotation_rate_beta);
804   args->GetNext(&has_rotation_rate_gamma);
805   args->GetNext(& rotation_rate_gamma);
806   args->GetNext(& interval);
807
808   runner_->SetMockDeviceMotion(has_acceleration_x, acceleration_x,
809                                has_acceleration_y, acceleration_y,
810                                has_acceleration_z, acceleration_z,
811                                has_acceleration_including_gravity_x,
812                                acceleration_including_gravity_x,
813                                has_acceleration_including_gravity_y,
814                                acceleration_including_gravity_y,
815                                has_acceleration_including_gravity_z,
816                                acceleration_including_gravity_z,
817                                has_rotation_rate_alpha,
818                                rotation_rate_alpha,
819                                has_rotation_rate_beta,
820                                rotation_rate_beta,
821                                has_rotation_rate_gamma,
822                                rotation_rate_gamma,
823                                interval);
824 }
825
826 void TestRunnerBindings::SetMockDeviceOrientation(gin::Arguments* args) {
827   if (!runner_)
828     return;
829
830   bool has_alpha;
831   double alpha;
832   bool has_beta;
833   double beta;
834   bool has_gamma;
835   double gamma;
836   bool has_absolute;
837   bool absolute;
838
839   args->GetNext(&has_alpha);
840   args->GetNext(&alpha);
841   args->GetNext(&has_beta);
842   args->GetNext(&beta);
843   args->GetNext(&has_gamma);
844   args->GetNext(&gamma);
845   args->GetNext(&has_absolute);
846   args->GetNext(&absolute);
847
848   runner_->SetMockDeviceOrientation(has_alpha, alpha,
849                                     has_beta, beta,
850                                     has_gamma, gamma,
851                                     has_absolute, absolute);
852 }
853
854 void TestRunnerBindings::SetMockScreenOrientation(const std::string& orientation) {
855   if (!runner_)
856     return;
857
858   runner_->SetMockScreenOrientation(orientation);
859 }
860
861 void TestRunnerBindings::DidAcquirePointerLock() {
862   if (runner_)
863     runner_->DidAcquirePointerLock();
864 }
865
866 void TestRunnerBindings::DidNotAcquirePointerLock() {
867   if (runner_)
868     runner_->DidNotAcquirePointerLock();
869 }
870
871 void TestRunnerBindings::DidLosePointerLock() {
872   if (runner_)
873     runner_->DidLosePointerLock();
874 }
875
876 void TestRunnerBindings::SetPointerLockWillFailSynchronously() {
877   if (runner_)
878     runner_->SetPointerLockWillFailSynchronously();
879 }
880
881 void TestRunnerBindings::SetPointerLockWillRespondAsynchronously() {
882   if (runner_)
883     runner_->SetPointerLockWillRespondAsynchronously();
884 }
885
886 void TestRunnerBindings::SetPopupBlockingEnabled(bool block_popups) {
887   if (runner_)
888     runner_->SetPopupBlockingEnabled(block_popups);
889 }
890
891 void TestRunnerBindings::SetJavaScriptCanAccessClipboard(bool can_access) {
892   if (runner_)
893     runner_->SetJavaScriptCanAccessClipboard(can_access);
894 }
895
896 void TestRunnerBindings::SetXSSAuditorEnabled(bool enabled) {
897   if (runner_)
898     runner_->SetXSSAuditorEnabled(enabled);
899 }
900
901 void TestRunnerBindings::SetAllowUniversalAccessFromFileURLs(bool allow) {
902   if (runner_)
903     runner_->SetAllowUniversalAccessFromFileURLs(allow);
904 }
905
906 void TestRunnerBindings::SetAllowFileAccessFromFileURLs(bool allow) {
907   if (runner_)
908     runner_->SetAllowFileAccessFromFileURLs(allow);
909 }
910
911 void TestRunnerBindings::OverridePreference(const std::string key,
912                                             v8::Handle<v8::Value> value) {
913   if (runner_)
914     runner_->OverridePreference(key, value);
915 }
916
917 void TestRunnerBindings::SetPluginsEnabled(bool enabled) {
918   if (runner_)
919     runner_->SetPluginsEnabled(enabled);
920 }
921
922 void TestRunnerBindings::DumpEditingCallbacks() {
923   if (runner_)
924     runner_->DumpEditingCallbacks();
925 }
926
927 void TestRunnerBindings::DumpAsText() {
928   if (runner_)
929     runner_->DumpAsText();
930 }
931
932 void TestRunnerBindings::DumpAsTextWithPixelResults() {
933   if (runner_)
934     runner_->DumpAsTextWithPixelResults();
935 }
936
937 void TestRunnerBindings::DumpChildFrameScrollPositions() {
938   if (runner_)
939     runner_->DumpChildFrameScrollPositions();
940 }
941
942 void TestRunnerBindings::DumpChildFramesAsText() {
943   if (runner_)
944     runner_->DumpChildFramesAsText();
945 }
946
947 void TestRunnerBindings::DumpIconChanges() {
948   if (runner_)
949     runner_->DumpIconChanges();
950 }
951
952 void TestRunnerBindings::SetAudioData(const gin::ArrayBufferView& view) {
953   if (runner_)
954     runner_->SetAudioData(view);
955 }
956
957 void TestRunnerBindings::DumpFrameLoadCallbacks() {
958   if (runner_)
959     runner_->DumpFrameLoadCallbacks();
960 }
961
962 void TestRunnerBindings::DumpPingLoaderCallbacks() {
963   if (runner_)
964     runner_->DumpPingLoaderCallbacks();
965 }
966
967 void TestRunnerBindings::DumpUserGestureInFrameLoadCallbacks() {
968   if (runner_)
969     runner_->DumpUserGestureInFrameLoadCallbacks();
970 }
971
972 void TestRunnerBindings::DumpTitleChanges() {
973   if (runner_)
974     runner_->DumpTitleChanges();
975 }
976
977 void TestRunnerBindings::DumpCreateView() {
978   if (runner_)
979     runner_->DumpCreateView();
980 }
981
982 void TestRunnerBindings::SetCanOpenWindows() {
983   if (runner_)
984     runner_->SetCanOpenWindows();
985 }
986
987 void TestRunnerBindings::DumpResourceLoadCallbacks() {
988   if (runner_)
989     runner_->DumpResourceLoadCallbacks();
990 }
991
992 void TestRunnerBindings::DumpResourceRequestCallbacks() {
993   if (runner_)
994     runner_->DumpResourceRequestCallbacks();
995 }
996
997 void TestRunnerBindings::DumpResourceResponseMIMETypes() {
998   if (runner_)
999     runner_->DumpResourceResponseMIMETypes();
1000 }
1001
1002 void TestRunnerBindings::SetImagesAllowed(bool allowed) {
1003   if (runner_)
1004     runner_->SetImagesAllowed(allowed);
1005 }
1006
1007 void TestRunnerBindings::SetScriptsAllowed(bool allowed) {
1008   if (runner_)
1009     runner_->SetScriptsAllowed(allowed);
1010 }
1011
1012 void TestRunnerBindings::SetStorageAllowed(bool allowed) {
1013   if (runner_)
1014     runner_->SetStorageAllowed(allowed);
1015 }
1016
1017 void TestRunnerBindings::SetPluginsAllowed(bool allowed) {
1018   if (runner_)
1019     runner_->SetPluginsAllowed(allowed);
1020 }
1021
1022 void TestRunnerBindings::SetAllowDisplayOfInsecureContent(bool allowed) {
1023   if (runner_)
1024     runner_->SetAllowDisplayOfInsecureContent(allowed);
1025 }
1026
1027 void TestRunnerBindings::SetAllowRunningOfInsecureContent(bool allowed) {
1028   if (runner_)
1029     runner_->SetAllowRunningOfInsecureContent(allowed);
1030 }
1031
1032 void TestRunnerBindings::DumpPermissionClientCallbacks() {
1033   if (runner_)
1034     runner_->DumpPermissionClientCallbacks();
1035 }
1036
1037 void TestRunnerBindings::DumpWindowStatusChanges() {
1038   if (runner_)
1039     runner_->DumpWindowStatusChanges();
1040 }
1041
1042 void TestRunnerBindings::DumpProgressFinishedCallback() {
1043   if (runner_)
1044     runner_->DumpProgressFinishedCallback();
1045 }
1046
1047 void TestRunnerBindings::DumpSpellCheckCallbacks() {
1048   if (runner_)
1049     runner_->DumpSpellCheckCallbacks();
1050 }
1051
1052 void TestRunnerBindings::DumpBackForwardList() {
1053   if (runner_)
1054     runner_->DumpBackForwardList();
1055 }
1056
1057 void TestRunnerBindings::DumpSelectionRect() {
1058   if (runner_)
1059     runner_->DumpSelectionRect();
1060 }
1061
1062 void TestRunnerBindings::SetPrinting() {
1063   if (runner_)
1064     runner_->SetPrinting();
1065 }
1066
1067 void TestRunnerBindings::SetShouldStayOnPageAfterHandlingBeforeUnload(
1068     bool value) {
1069   if (runner_)
1070     runner_->SetShouldStayOnPageAfterHandlingBeforeUnload(value);
1071 }
1072
1073 void TestRunnerBindings::SetWillSendRequestClearHeader(
1074     const std::string& header) {
1075   if (runner_)
1076     runner_->SetWillSendRequestClearHeader(header);
1077 }
1078
1079 void TestRunnerBindings::DumpResourceRequestPriorities() {
1080   if (runner_)
1081     runner_->DumpResourceRequestPriorities();
1082 }
1083
1084 void TestRunnerBindings::SetUseMockTheme(bool use) {
1085   if (runner_)
1086     runner_->SetUseMockTheme(use);
1087 }
1088
1089 void TestRunnerBindings::WaitUntilExternalURLLoad() {
1090   if (runner_)
1091     runner_->WaitUntilExternalURLLoad();
1092 }
1093
1094 void TestRunnerBindings::ShowWebInspector(gin::Arguments* args) {
1095   if (runner_) {
1096     std::string settings;
1097     args->GetNext(&settings);
1098     std::string frontend_url;
1099     args->GetNext(&frontend_url);
1100     runner_->ShowWebInspector(settings, frontend_url);
1101   }
1102 }
1103
1104 void TestRunnerBindings::CloseWebInspector() {
1105   if (runner_)
1106     runner_->CloseWebInspector();
1107 }
1108
1109 bool TestRunnerBindings::IsChooserShown() {
1110   if (runner_)
1111     return runner_->IsChooserShown();
1112   return false;
1113 }
1114
1115 void TestRunnerBindings::EvaluateInWebInspector(int call_id,
1116                                                 const std::string& script) {
1117   if (runner_)
1118     runner_->EvaluateInWebInspector(call_id, script);
1119 }
1120
1121 void TestRunnerBindings::ClearAllDatabases() {
1122   if (runner_)
1123     runner_->ClearAllDatabases();
1124 }
1125
1126 void TestRunnerBindings::SetDatabaseQuota(int quota) {
1127   if (runner_)
1128     runner_->SetDatabaseQuota(quota);
1129 }
1130
1131 void TestRunnerBindings::SetAlwaysAcceptCookies(bool accept) {
1132   if (runner_)
1133     runner_->SetAlwaysAcceptCookies(accept);
1134 }
1135
1136 void TestRunnerBindings::SetWindowIsKey(bool value) {
1137   if (runner_)
1138     runner_->SetWindowIsKey(value);
1139 }
1140
1141 std::string TestRunnerBindings::PathToLocalResource(const std::string& path) {
1142   if (runner_)
1143     return runner_->PathToLocalResource(path);
1144   return std::string();
1145 }
1146
1147 void TestRunnerBindings::SetBackingScaleFactor(
1148     double value, v8::Handle<v8::Function> callback) {
1149   if (runner_)
1150     runner_->SetBackingScaleFactor(value, callback);
1151 }
1152
1153 void TestRunnerBindings::SetColorProfile(
1154     const std::string& name, v8::Handle<v8::Function> callback) {
1155   if (runner_)
1156     runner_->SetColorProfile(name, callback);
1157 }
1158
1159 void TestRunnerBindings::SetPOSIXLocale(const std::string& locale) {
1160   if (runner_)
1161     runner_->SetPOSIXLocale(locale);
1162 }
1163
1164 void TestRunnerBindings::SetMIDIAccessorResult(bool result) {
1165   if (runner_)
1166     runner_->SetMIDIAccessorResult(result);
1167 }
1168
1169 void TestRunnerBindings::SetMIDISysexPermission(bool value) {
1170   if (runner_)
1171     runner_->SetMIDISysexPermission(value);
1172 }
1173
1174 void TestRunnerBindings::GrantWebNotificationPermission(gin::Arguments* args) {
1175   if (runner_) {
1176     std::string origin;
1177     bool permission_granted = true;
1178     args->GetNext(&origin);
1179     args->GetNext(&permission_granted);
1180     return runner_->GrantWebNotificationPermission(origin, permission_granted);
1181   }
1182 }
1183
1184 bool TestRunnerBindings::SimulateWebNotificationClick(
1185     const std::string& value) {
1186   if (runner_)
1187     return runner_->SimulateWebNotificationClick(value);
1188   return false;
1189 }
1190
1191 void TestRunnerBindings::AddMockSpeechRecognitionResult(
1192     const std::string& transcript, double confidence) {
1193   if (runner_)
1194     runner_->AddMockSpeechRecognitionResult(transcript, confidence);
1195 }
1196
1197 void TestRunnerBindings::SetMockSpeechRecognitionError(
1198     const std::string& error, const std::string& message) {
1199   if (runner_)
1200     runner_->SetMockSpeechRecognitionError(error, message);
1201 }
1202
1203 bool TestRunnerBindings::WasMockSpeechRecognitionAborted() {
1204   if (runner_)
1205     return runner_->WasMockSpeechRecognitionAborted();
1206   return false;
1207 }
1208
1209 void TestRunnerBindings::AddWebPageOverlay() {
1210   if (runner_)
1211     runner_->AddWebPageOverlay();
1212 }
1213
1214 void TestRunnerBindings::RemoveWebPageOverlay() {
1215   if (runner_)
1216     runner_->RemoveWebPageOverlay();
1217 }
1218
1219 void TestRunnerBindings::DisplayAsync() {
1220   if (runner_)
1221     runner_->DisplayAsync();
1222 }
1223
1224 void TestRunnerBindings::DisplayAsyncThen(v8::Handle<v8::Function> callback) {
1225   if (runner_)
1226     runner_->DisplayAsyncThen(callback);
1227 }
1228
1229 void TestRunnerBindings::SetCustomTextOutput(std::string output) {
1230   runner_->setCustomTextOutput(output);
1231 }
1232
1233 bool TestRunnerBindings::GlobalFlag() {
1234   if (runner_)
1235     return runner_->global_flag_;
1236   return false;
1237 }
1238
1239 void TestRunnerBindings::SetGlobalFlag(bool value) {
1240   if (runner_)
1241     runner_->global_flag_ = value;
1242 }
1243
1244 std::string TestRunnerBindings::PlatformName() {
1245   if (runner_)
1246     return runner_->platform_name_;
1247   return std::string();
1248 }
1249
1250 std::string TestRunnerBindings::TooltipText() {
1251   if (runner_)
1252     return runner_->tooltip_text_;
1253   return std::string();
1254 }
1255
1256 bool TestRunnerBindings::DisableNotifyDone() {
1257   if (runner_)
1258     return runner_->disable_notify_done_;
1259   return false;
1260 }
1261
1262 int TestRunnerBindings::WebHistoryItemCount() {
1263   if (runner_)
1264     return runner_->web_history_item_count_;
1265   return false;
1266 }
1267
1268 bool TestRunnerBindings::InterceptPostMessage() {
1269   if (runner_)
1270     return runner_->intercept_post_message_;
1271   return false;
1272 }
1273
1274 void TestRunnerBindings::SetInterceptPostMessage(bool value) {
1275   if (runner_)
1276     runner_->intercept_post_message_ = value;
1277 }
1278
1279 void TestRunnerBindings::NotImplemented(const gin::Arguments& args) {
1280 }
1281
1282 class TestPageOverlay : public WebPageOverlay {
1283  public:
1284   explicit TestPageOverlay(WebView* web_view)
1285       : web_view_(web_view) {
1286   }
1287   virtual ~TestPageOverlay() {}
1288
1289   virtual void paintPageOverlay(WebCanvas* canvas) OVERRIDE  {
1290     SkRect rect = SkRect::MakeWH(web_view_->size().width,
1291                                  web_view_->size().height);
1292     SkPaint paint;
1293     paint.setColor(SK_ColorCYAN);
1294     paint.setStyle(SkPaint::kFill_Style);
1295     canvas->drawRect(rect, paint);
1296   }
1297
1298  private:
1299   WebView* web_view_;
1300 };
1301
1302 TestRunner::WorkQueue::WorkQueue(TestRunner* controller)
1303     : frozen_(false)
1304     , controller_(controller) {}
1305
1306 TestRunner::WorkQueue::~WorkQueue() {
1307   Reset();
1308 }
1309
1310 void TestRunner::WorkQueue::ProcessWorkSoon() {
1311   if (controller_->topLoadingFrame())
1312     return;
1313
1314   if (!queue_.empty()) {
1315     // We delay processing queued work to avoid recursion problems.
1316     controller_->delegate_->postTask(new WorkQueueTask(this));
1317   } else if (!controller_->wait_until_done_) {
1318     controller_->delegate_->testFinished();
1319   }
1320 }
1321
1322 void TestRunner::WorkQueue::Reset() {
1323   frozen_ = false;
1324   while (!queue_.empty()) {
1325     delete queue_.front();
1326     queue_.pop_front();
1327   }
1328 }
1329
1330 void TestRunner::WorkQueue::AddWork(WorkItem* work) {
1331   if (frozen_) {
1332     delete work;
1333     return;
1334   }
1335   queue_.push_back(work);
1336 }
1337
1338 void TestRunner::WorkQueue::ProcessWork() {
1339   // Quit doing work once a load is in progress.
1340   while (!queue_.empty()) {
1341     bool startedLoad = queue_.front()->Run(controller_->delegate_,
1342                                            controller_->web_view_);
1343     delete queue_.front();
1344     queue_.pop_front();
1345     if (startedLoad)
1346       return;
1347   }
1348
1349   if (!controller_->wait_until_done_ && !controller_->topLoadingFrame())
1350     controller_->delegate_->testFinished();
1351 }
1352
1353 void TestRunner::WorkQueue::WorkQueueTask::runIfValid() {
1354   m_object->ProcessWork();
1355 }
1356
1357 TestRunner::TestRunner(TestInterfaces* interfaces)
1358     : test_is_running_(false),
1359       close_remaining_windows_(false),
1360       work_queue_(this),
1361       disable_notify_done_(false),
1362       web_history_item_count_(0),
1363       intercept_post_message_(false),
1364       test_interfaces_(interfaces),
1365       delegate_(NULL),
1366       web_view_(NULL),
1367       page_overlay_(NULL),
1368       web_permissions_(new WebPermissions()),
1369       notification_presenter_(new NotificationPresenter()),
1370       weak_factory_(this) {}
1371
1372 TestRunner::~TestRunner() {}
1373
1374 void TestRunner::Install(WebFrame* frame) {
1375   TestRunnerBindings::Install(weak_factory_.GetWeakPtr(), frame);
1376 }
1377
1378 void TestRunner::SetDelegate(WebTestDelegate* delegate) {
1379   delegate_ = delegate;
1380   web_permissions_->setDelegate(delegate);
1381   notification_presenter_->set_delegate(delegate);
1382 }
1383
1384 void TestRunner::SetWebView(WebView* webView, WebTestProxyBase* proxy) {
1385   web_view_ = webView;
1386   proxy_ = proxy;
1387 }
1388
1389 void TestRunner::Reset() {
1390   if (web_view_) {
1391     web_view_->setZoomLevel(0);
1392     web_view_->setTextZoomFactor(1);
1393     web_view_->setTabKeyCyclesThroughElements(true);
1394 #if !defined(__APPLE__) && !defined(WIN32) // Actually, TOOLKIT_GTK
1395     // (Constants copied because we can't depend on the header that defined
1396     // them from this file.)
1397     web_view_->setSelectionColors(
1398         0xff1e90ff, 0xff000000, 0xffc8c8c8, 0xff323232);
1399 #endif
1400     web_view_->removeInjectedStyleSheets();
1401     web_view_->setVisibilityState(WebPageVisibilityStateVisible, true);
1402     web_view_->mainFrame()->enableViewSourceMode(false);
1403
1404     if (page_overlay_) {
1405       web_view_->removePageOverlay(page_overlay_);
1406       delete page_overlay_;
1407       page_overlay_ = NULL;
1408     }
1409   }
1410
1411   top_loading_frame_ = NULL;
1412   wait_until_done_ = false;
1413   wait_until_external_url_load_ = false;
1414   policy_delegate_enabled_ = false;
1415   policy_delegate_is_permissive_ = false;
1416   policy_delegate_should_notify_done_ = false;
1417
1418   WebSecurityPolicy::resetOriginAccessWhitelists();
1419 #if defined(__linux__) || defined(ANDROID)
1420   WebFontRendering::setSubpixelPositioning(false);
1421 #endif
1422
1423   if (delegate_) {
1424     // Reset the default quota for each origin to 5MB
1425     delegate_->setDatabaseQuota(5 * 1024 * 1024);
1426     delegate_->setDeviceColorProfile("sRGB");
1427     delegate_->setDeviceScaleFactor(1);
1428     delegate_->setAcceptAllCookies(false);
1429     delegate_->setLocale("");
1430     delegate_->useUnfortunateSynchronousResizeMode(false);
1431     delegate_->disableAutoResizeMode(WebSize());
1432     delegate_->deleteAllCookies();
1433   }
1434
1435   dump_editting_callbacks_ = false;
1436   dump_as_text_ = false;
1437   dump_as_markup_ = false;
1438   generate_pixel_results_ = true;
1439   dump_child_frame_scroll_positions_ = false;
1440   dump_child_frames_as_text_ = false;
1441   dump_icon_changes_ = false;
1442   dump_as_audio_ = false;
1443   dump_frame_load_callbacks_ = false;
1444   dump_ping_loader_callbacks_ = false;
1445   dump_user_gesture_in_frame_load_callbacks_ = false;
1446   dump_title_changes_ = false;
1447   dump_create_view_ = false;
1448   can_open_windows_ = false;
1449   dump_resource_load_callbacks_ = false;
1450   dump_resource_request_callbacks_ = false;
1451   dump_resource_reqponse_mime_types_ = false;
1452   dump_window_status_changes_ = false;
1453   dump_progress_finished_callback_ = false;
1454   dump_spell_check_callbacks_ = false;
1455   dump_back_forward_list_ = false;
1456   dump_selection_rect_ = false;
1457   test_repaint_ = false;
1458   sweep_horizontally_ = false;
1459   is_printing_ = false;
1460   midi_accessor_result_ = true;
1461   should_stay_on_page_after_handling_before_unload_ = false;
1462   should_dump_resource_priorities_ = false;
1463   has_custom_text_output_ = false;
1464   custom_text_output_.clear();
1465
1466   http_headers_to_clear_.clear();
1467
1468   global_flag_ = false;
1469   platform_name_ = "chromium";
1470   tooltip_text_ = std::string();
1471   disable_notify_done_ = false;
1472   web_history_item_count_ = 0;
1473   intercept_post_message_ = false;
1474
1475   web_permissions_->reset();
1476
1477   notification_presenter_->Reset();
1478   use_mock_theme_ = true;
1479   pointer_locked_ = false;
1480   pointer_lock_planned_result_ = PointerLockWillSucceed;
1481
1482   task_list_.revokeAll();
1483   work_queue_.Reset();
1484
1485   if (close_remaining_windows_ && delegate_)
1486     delegate_->closeRemainingWindows();
1487   else
1488     close_remaining_windows_ = true;
1489 }
1490
1491 void TestRunner::SetTestIsRunning(bool running) {
1492   test_is_running_ = running;
1493 }
1494
1495 void TestRunner::InvokeCallback(scoped_ptr<InvokeCallbackTask> task) {
1496   delegate_->postTask(task.release());
1497 }
1498
1499 bool TestRunner::shouldDumpEditingCallbacks() const {
1500   return dump_editting_callbacks_;
1501 }
1502
1503 bool TestRunner::shouldDumpAsText() {
1504   CheckResponseMimeType();
1505   return dump_as_text_;
1506 }
1507
1508 void TestRunner::setShouldDumpAsText(bool value) {
1509   dump_as_text_ = value;
1510 }
1511
1512 bool TestRunner::shouldDumpAsMarkup() {
1513   return dump_as_markup_;
1514 }
1515
1516 void TestRunner::setShouldDumpAsMarkup(bool value) {
1517   dump_as_markup_ = value;
1518 }
1519
1520 bool TestRunner::shouldDumpAsCustomText() const {
1521   return has_custom_text_output_;
1522 }
1523
1524 std::string TestRunner::customDumpText() const {
1525   return custom_text_output_;
1526 }
1527
1528 void TestRunner::setCustomTextOutput(std::string text) {
1529   custom_text_output_ = text;
1530   has_custom_text_output_ = true;
1531 }
1532
1533 bool TestRunner::shouldGeneratePixelResults() {
1534   CheckResponseMimeType();
1535   return generate_pixel_results_;
1536 }
1537
1538 void TestRunner::setShouldGeneratePixelResults(bool value) {
1539   generate_pixel_results_ = value;
1540 }
1541
1542 bool TestRunner::shouldDumpChildFrameScrollPositions() const {
1543   return dump_child_frame_scroll_positions_;
1544 }
1545
1546 bool TestRunner::shouldDumpChildFramesAsText() const {
1547   return dump_child_frames_as_text_;
1548 }
1549
1550 bool TestRunner::shouldDumpAsAudio() const {
1551   return dump_as_audio_;
1552 }
1553
1554 void TestRunner::getAudioData(std::vector<unsigned char>* bufferView) const {
1555   *bufferView = audio_data_;
1556 }
1557
1558 bool TestRunner::shouldDumpFrameLoadCallbacks() const {
1559   return test_is_running_ && dump_frame_load_callbacks_;
1560 }
1561
1562 void TestRunner::setShouldDumpFrameLoadCallbacks(bool value) {
1563   dump_frame_load_callbacks_ = value;
1564 }
1565
1566 bool TestRunner::shouldDumpPingLoaderCallbacks() const {
1567   return test_is_running_ && dump_ping_loader_callbacks_;
1568 }
1569
1570 void TestRunner::setShouldDumpPingLoaderCallbacks(bool value) {
1571   dump_ping_loader_callbacks_ = value;
1572 }
1573
1574 void TestRunner::setShouldEnableViewSource(bool value) {
1575   web_view_->mainFrame()->enableViewSourceMode(value);
1576 }
1577
1578 bool TestRunner::shouldDumpUserGestureInFrameLoadCallbacks() const {
1579   return test_is_running_ && dump_user_gesture_in_frame_load_callbacks_;
1580 }
1581
1582 bool TestRunner::shouldDumpTitleChanges() const {
1583   return dump_title_changes_;
1584 }
1585
1586 bool TestRunner::shouldDumpIconChanges() const {
1587   return dump_icon_changes_;
1588 }
1589
1590 bool TestRunner::shouldDumpCreateView() const {
1591   return dump_create_view_;
1592 }
1593
1594 bool TestRunner::canOpenWindows() const {
1595   return can_open_windows_;
1596 }
1597
1598 bool TestRunner::shouldDumpResourceLoadCallbacks() const {
1599   return test_is_running_ && dump_resource_load_callbacks_;
1600 }
1601
1602 bool TestRunner::shouldDumpResourceRequestCallbacks() const {
1603   return test_is_running_ && dump_resource_request_callbacks_;
1604 }
1605
1606 bool TestRunner::shouldDumpResourceResponseMIMETypes() const {
1607   return test_is_running_ && dump_resource_reqponse_mime_types_;
1608 }
1609
1610 WebPermissionClient* TestRunner::webPermissions() const {
1611   return web_permissions_.get();
1612 }
1613
1614 bool TestRunner::shouldDumpStatusCallbacks() const {
1615   return dump_window_status_changes_;
1616 }
1617
1618 bool TestRunner::shouldDumpProgressFinishedCallback() const {
1619   return dump_progress_finished_callback_;
1620 }
1621
1622 bool TestRunner::shouldDumpSpellCheckCallbacks() const {
1623   return dump_spell_check_callbacks_;
1624 }
1625
1626 bool TestRunner::shouldDumpBackForwardList() const {
1627   return dump_back_forward_list_;
1628 }
1629
1630 bool TestRunner::shouldDumpSelectionRect() const {
1631   return dump_selection_rect_;
1632 }
1633
1634 bool TestRunner::isPrinting() const {
1635   return is_printing_;
1636 }
1637
1638 bool TestRunner::shouldStayOnPageAfterHandlingBeforeUnload() const {
1639   return should_stay_on_page_after_handling_before_unload_;
1640 }
1641
1642 bool TestRunner::shouldWaitUntilExternalURLLoad() const {
1643   return wait_until_external_url_load_;
1644 }
1645
1646 const std::set<std::string>* TestRunner::httpHeadersToClear() const {
1647   return &http_headers_to_clear_;
1648 }
1649
1650 void TestRunner::setTopLoadingFrame(WebFrame* frame, bool clear) {
1651   if (frame->top()->view() != web_view_)
1652     return;
1653   if (!test_is_running_)
1654     return;
1655   if (clear) {
1656     top_loading_frame_ = NULL;
1657     LocationChangeDone();
1658   } else if (!top_loading_frame_) {
1659     top_loading_frame_ = frame;
1660   }
1661 }
1662
1663 WebFrame* TestRunner::topLoadingFrame() const {
1664   return top_loading_frame_;
1665 }
1666
1667 void TestRunner::policyDelegateDone() {
1668   DCHECK(wait_until_done_);
1669   delegate_->testFinished();
1670   wait_until_done_ = false;
1671 }
1672
1673 bool TestRunner::policyDelegateEnabled() const {
1674   return policy_delegate_enabled_;
1675 }
1676
1677 bool TestRunner::policyDelegateIsPermissive() const {
1678   return policy_delegate_is_permissive_;
1679 }
1680
1681 bool TestRunner::policyDelegateShouldNotifyDone() const {
1682   return policy_delegate_should_notify_done_;
1683 }
1684
1685 bool TestRunner::shouldInterceptPostMessage() const {
1686   return intercept_post_message_;
1687 }
1688
1689 bool TestRunner::shouldDumpResourcePriorities() const {
1690   return should_dump_resource_priorities_;
1691 }
1692
1693 WebNotificationPresenter* TestRunner::notification_presenter() const {
1694   return notification_presenter_.get();
1695 }
1696
1697 bool TestRunner::RequestPointerLock() {
1698   switch (pointer_lock_planned_result_) {
1699     case PointerLockWillSucceed:
1700       delegate_->postDelayedTask(
1701           new HostMethodTask(this, &TestRunner::DidAcquirePointerLockInternal),
1702           0);
1703       return true;
1704     case PointerLockWillRespondAsync:
1705       DCHECK(!pointer_locked_);
1706       return true;
1707     case PointerLockWillFailSync:
1708       DCHECK(!pointer_locked_);
1709       return false;
1710     default:
1711       NOTREACHED();
1712       return false;
1713   }
1714 }
1715
1716 void TestRunner::RequestPointerUnlock() {
1717   delegate_->postDelayedTask(
1718       new HostMethodTask(this, &TestRunner::DidLosePointerLockInternal), 0);
1719 }
1720
1721 bool TestRunner::isPointerLocked() {
1722   return pointer_locked_;
1723 }
1724
1725 void TestRunner::setToolTipText(const WebString& text) {
1726   tooltip_text_ = text.utf8();
1727 }
1728
1729 bool TestRunner::midiAccessorResult() {
1730   return midi_accessor_result_;
1731 }
1732
1733 void TestRunner::clearDevToolsLocalStorage() {
1734   delegate_->clearDevToolsLocalStorage();
1735 }
1736
1737 void TestRunner::showDevTools(const std::string& settings,
1738                               const std::string& frontend_url) {
1739   delegate_->showDevTools(settings, frontend_url);
1740 }
1741
1742 class WorkItemBackForward : public TestRunner::WorkItem {
1743  public:
1744   WorkItemBackForward(int distance) : distance_(distance) {}
1745
1746   virtual bool Run(WebTestDelegate* delegate, WebView*) OVERRIDE {
1747     delegate->goToOffset(distance_);
1748     return true; // FIXME: Did it really start a navigation?
1749   }
1750
1751  private:
1752   int distance_;
1753 };
1754
1755 void TestRunner::NotifyDone() {
1756   if (disable_notify_done_)
1757     return;
1758
1759   // Test didn't timeout. Kill the timeout timer.
1760   taskList()->revokeAll();
1761
1762   CompleteNotifyDone();
1763 }
1764
1765 void TestRunner::WaitUntilDone() {
1766   wait_until_done_ = true;
1767 }
1768
1769 void TestRunner::QueueBackNavigation(int how_far_back) {
1770   work_queue_.AddWork(new WorkItemBackForward(-how_far_back));
1771 }
1772
1773 void TestRunner::QueueForwardNavigation(int how_far_forward) {
1774   work_queue_.AddWork(new WorkItemBackForward(how_far_forward));
1775 }
1776
1777 class WorkItemReload : public TestRunner::WorkItem {
1778  public:
1779   virtual bool Run(WebTestDelegate* delegate, WebView*) OVERRIDE {
1780     delegate->reload();
1781     return true;
1782   }
1783 };
1784
1785 void TestRunner::QueueReload() {
1786   work_queue_.AddWork(new WorkItemReload());
1787 }
1788
1789 class WorkItemLoadingScript : public TestRunner::WorkItem {
1790  public:
1791   WorkItemLoadingScript(const std::string& script)
1792       : script_(script) {}
1793
1794   virtual bool Run(WebTestDelegate*, WebView* web_view) OVERRIDE {
1795     web_view->mainFrame()->executeScript(
1796         WebScriptSource(WebString::fromUTF8(script_)));
1797     return true; // FIXME: Did it really start a navigation?
1798   }
1799
1800  private:
1801   std::string script_;
1802 };
1803
1804 void TestRunner::QueueLoadingScript(const std::string& script) {
1805   work_queue_.AddWork(new WorkItemLoadingScript(script));
1806 }
1807
1808 class WorkItemNonLoadingScript : public TestRunner::WorkItem {
1809  public:
1810   WorkItemNonLoadingScript(const std::string& script)
1811       : script_(script) {}
1812
1813   virtual bool Run(WebTestDelegate*, WebView* web_view) OVERRIDE {
1814     web_view->mainFrame()->executeScript(
1815         WebScriptSource(WebString::fromUTF8(script_)));
1816     return false;
1817   }
1818
1819  private:
1820   std::string script_;
1821 };
1822
1823 void TestRunner::QueueNonLoadingScript(const std::string& script) {
1824   work_queue_.AddWork(new WorkItemNonLoadingScript(script));
1825 }
1826
1827 class WorkItemLoad : public TestRunner::WorkItem {
1828  public:
1829   WorkItemLoad(const WebURL& url, const std::string& target)
1830       : url_(url), target_(target) {}
1831
1832   virtual bool Run(WebTestDelegate* delegate, WebView*) OVERRIDE {
1833     delegate->loadURLForFrame(url_, target_);
1834     return true; // FIXME: Did it really start a navigation?
1835   }
1836
1837  private:
1838   WebURL url_;
1839   std::string target_;
1840 };
1841
1842 void TestRunner::QueueLoad(const std::string& url, const std::string& target) {
1843   // FIXME: Implement WebURL::resolve() and avoid GURL.
1844   GURL current_url = web_view_->mainFrame()->document().url();
1845   GURL full_url = current_url.Resolve(url);
1846   work_queue_.AddWork(new WorkItemLoad(full_url, target));
1847 }
1848
1849 class WorkItemLoadHTMLString : public TestRunner::WorkItem  {
1850  public:
1851   WorkItemLoadHTMLString(const std::string& html, const WebURL& base_url)
1852       : html_(html), base_url_(base_url) {}
1853
1854   WorkItemLoadHTMLString(const std::string& html, const WebURL& base_url,
1855                          const WebURL& unreachable_url)
1856       : html_(html), base_url_(base_url), unreachable_url_(unreachable_url) {}
1857
1858   virtual bool Run(WebTestDelegate*, WebView* web_view) OVERRIDE {
1859     web_view->mainFrame()->loadHTMLString(
1860         WebData(html_.data(), html_.length()),
1861         base_url_, unreachable_url_);
1862     return true;
1863   }
1864
1865  private:
1866   std::string html_;
1867   WebURL base_url_;
1868   WebURL unreachable_url_;
1869 };
1870
1871 void TestRunner::QueueLoadHTMLString(gin::Arguments* args) {
1872   std::string html;
1873   args->GetNext(&html);
1874
1875   std::string base_url_str;
1876   args->GetNext(&base_url_str);
1877   WebURL base_url = WebURL(GURL(base_url_str));
1878
1879   if (args->PeekNext()->IsString()) {
1880     std::string unreachable_url_str;
1881     args->GetNext(&unreachable_url_str);
1882     WebURL unreachable_url = WebURL(GURL(unreachable_url_str));
1883     work_queue_.AddWork(new WorkItemLoadHTMLString(html, base_url,
1884                                                    unreachable_url));
1885   } else {
1886     work_queue_.AddWork(new WorkItemLoadHTMLString(html, base_url));
1887   }
1888 }
1889
1890 void TestRunner::SetCustomPolicyDelegate(gin::Arguments* args) {
1891   args->GetNext(&policy_delegate_enabled_);
1892   if (!args->PeekNext().IsEmpty() && args->PeekNext()->IsBoolean())
1893     args->GetNext(&policy_delegate_is_permissive_);
1894 }
1895
1896 void TestRunner::WaitForPolicyDelegate() {
1897   policy_delegate_enabled_ = true;
1898   policy_delegate_should_notify_done_ = true;
1899   wait_until_done_ = true;
1900 }
1901
1902 int TestRunner::WindowCount() {
1903   return test_interfaces_->windowList().size();
1904 }
1905
1906 void TestRunner::SetCloseRemainingWindowsWhenComplete(
1907     bool close_remaining_windows) {
1908   close_remaining_windows_ = close_remaining_windows;
1909 }
1910
1911 void TestRunner::ResetTestHelperControllers() {
1912   test_interfaces_->resetTestHelperControllers();
1913 }
1914
1915 void TestRunner::SetTabKeyCyclesThroughElements(
1916     bool tab_key_cycles_through_elements) {
1917   web_view_->setTabKeyCyclesThroughElements(tab_key_cycles_through_elements);
1918 }
1919
1920 void TestRunner::ExecCommand(gin::Arguments* args) {
1921   std::string command;
1922   args->GetNext(&command);
1923
1924   std::string value;
1925   if (args->Length() >= 3) {
1926     // Ignore the second parameter (which is userInterface)
1927     // since this command emulates a manual action.
1928     args->Skip();
1929     args->GetNext(&value);
1930   }
1931
1932   // Note: webkit's version does not return the boolean, so neither do we.
1933   web_view_->focusedFrame()->executeCommand(WebString::fromUTF8(command),
1934                                             WebString::fromUTF8(value));
1935 }
1936
1937 bool TestRunner::IsCommandEnabled(const std::string& command) {
1938   return web_view_->focusedFrame()->isCommandEnabled(
1939       WebString::fromUTF8(command));
1940 }
1941
1942 bool TestRunner::CallShouldCloseOnWebView() {
1943   return web_view_->mainFrame()->dispatchBeforeUnloadEvent();
1944 }
1945
1946 void TestRunner::SetDomainRelaxationForbiddenForURLScheme(
1947     bool forbidden, const std::string& scheme) {
1948   web_view_->setDomainRelaxationForbidden(forbidden,
1949                                           WebString::fromUTF8(scheme));
1950 }
1951
1952 v8::Handle<v8::Value> TestRunner::EvaluateScriptInIsolatedWorldAndReturnValue(
1953     int world_id,
1954     const std::string& script) {
1955   WebVector<v8::Local<v8::Value> > values;
1956   WebScriptSource source(WebString::fromUTF8(script));
1957   // This relies on the iframe focusing itself when it loads. This is a bit
1958   // sketchy, but it seems to be what other tests do.
1959   web_view_->focusedFrame()->executeScriptInIsolatedWorld(
1960       world_id, &source, 1, 1, &values);
1961   // Since only one script was added, only one result is expected
1962   if (values.size() == 1 && !values[0].IsEmpty())
1963     return values[0];
1964   return v8::Handle<v8::Value>();
1965 }
1966
1967 void TestRunner::EvaluateScriptInIsolatedWorld(int world_id,
1968                                                const std::string& script) {
1969   WebScriptSource source(WebString::fromUTF8(script));
1970   web_view_->focusedFrame()->executeScriptInIsolatedWorld(
1971       world_id, &source, 1, 1);
1972 }
1973
1974 void TestRunner::SetIsolatedWorldSecurityOrigin(int world_id,
1975                                                 v8::Handle<v8::Value> origin) {
1976   if (!(origin->IsString() || !origin->IsNull()))
1977     return;
1978
1979   WebSecurityOrigin web_origin;
1980   if (origin->IsString()) {
1981     web_origin = WebSecurityOrigin::createFromString(
1982         V8StringToWebString(origin->ToString()));
1983   }
1984   web_view_->focusedFrame()->setIsolatedWorldSecurityOrigin(world_id,
1985                                                             web_origin);
1986 }
1987
1988 void TestRunner::SetIsolatedWorldContentSecurityPolicy(
1989     int world_id,
1990     const std::string& policy) {
1991   web_view_->focusedFrame()->setIsolatedWorldContentSecurityPolicy(
1992       world_id, WebString::fromUTF8(policy));
1993 }
1994
1995 void TestRunner::AddOriginAccessWhitelistEntry(
1996     const std::string& source_origin,
1997     const std::string& destination_protocol,
1998     const std::string& destination_host,
1999     bool allow_destination_subdomains) {
2000   WebURL url((GURL(source_origin)));
2001   if (!url.isValid())
2002     return;
2003
2004   WebSecurityPolicy::addOriginAccessWhitelistEntry(
2005       url,
2006       WebString::fromUTF8(destination_protocol),
2007       WebString::fromUTF8(destination_host),
2008       allow_destination_subdomains);
2009 }
2010
2011 void TestRunner::RemoveOriginAccessWhitelistEntry(
2012     const std::string& source_origin,
2013     const std::string& destination_protocol,
2014     const std::string& destination_host,
2015     bool allow_destination_subdomains) {
2016   WebURL url((GURL(source_origin)));
2017   if (!url.isValid())
2018     return;
2019
2020   WebSecurityPolicy::removeOriginAccessWhitelistEntry(
2021       url,
2022       WebString::fromUTF8(destination_protocol),
2023       WebString::fromUTF8(destination_host),
2024       allow_destination_subdomains);
2025 }
2026
2027 bool TestRunner::HasCustomPageSizeStyle(int page_index) {
2028   WebFrame* frame = web_view_->mainFrame();
2029   if (!frame)
2030     return false;
2031   return frame->hasCustomPageSizeStyle(page_index);
2032 }
2033
2034 void TestRunner::ForceRedSelectionColors() {
2035   web_view_->setSelectionColors(0xffee0000, 0xff00ee00, 0xff000000, 0xffc0c0c0);
2036 }
2037
2038 void TestRunner::InjectStyleSheet(const std::string& source_code,
2039                                   bool all_frames) {
2040   WebView::injectStyleSheet(
2041       WebString::fromUTF8(source_code),
2042       WebVector<WebString>(),
2043       all_frames ? WebView::InjectStyleInAllFrames
2044                  : WebView::InjectStyleInTopFrameOnly);
2045 }
2046
2047 bool TestRunner::FindString(const std::string& search_text,
2048                             const std::vector<std::string>& options_array) {
2049   WebFindOptions find_options;
2050   bool wrap_around = false;
2051   find_options.matchCase = true;
2052   find_options.findNext = true;
2053
2054   for (size_t i = 0; i < options_array.size(); ++i) {
2055     const std::string& option = options_array[i];
2056     if (option == "CaseInsensitive")
2057       find_options.matchCase = false;
2058     else if (option == "Backwards")
2059       find_options.forward = false;
2060     else if (option == "StartInSelection")
2061       find_options.findNext = false;
2062     else if (option == "AtWordStarts")
2063       find_options.wordStart = true;
2064     else if (option == "TreatMedialCapitalAsWordStart")
2065       find_options.medialCapitalAsWordStart = true;
2066     else if (option == "WrapAround")
2067       wrap_around = true;
2068   }
2069
2070   WebFrame* frame = web_view_->mainFrame();
2071   const bool find_result = frame->find(0, WebString::fromUTF8(search_text),
2072                                        find_options, wrap_around, 0);
2073   frame->stopFinding(false);
2074   return find_result;
2075 }
2076
2077 std::string TestRunner::SelectionAsMarkup() {
2078   return web_view_->mainFrame()->selectionAsMarkup().utf8();
2079 }
2080
2081 void TestRunner::SetTextSubpixelPositioning(bool value) {
2082 #if defined(__linux__) || defined(ANDROID)
2083   // Since FontConfig doesn't provide a variable to control subpixel
2084   // positioning, we'll fall back to setting it globally for all fonts.
2085   WebFontRendering::setSubpixelPositioning(value);
2086 #endif
2087 }
2088
2089 void TestRunner::SetPageVisibility(const std::string& new_visibility) {
2090   if (new_visibility == "visible")
2091     web_view_->setVisibilityState(WebPageVisibilityStateVisible, false);
2092   else if (new_visibility == "hidden")
2093     web_view_->setVisibilityState(WebPageVisibilityStateHidden, false);
2094   else if (new_visibility == "prerender")
2095     web_view_->setVisibilityState(WebPageVisibilityStatePrerender, false);
2096 }
2097
2098 void TestRunner::SetTextDirection(const std::string& direction_name) {
2099   // Map a direction name to a WebTextDirection value.
2100   WebTextDirection direction;
2101   if (direction_name == "auto")
2102     direction = WebTextDirectionDefault;
2103   else if (direction_name == "rtl")
2104     direction = WebTextDirectionRightToLeft;
2105   else if (direction_name == "ltr")
2106     direction = WebTextDirectionLeftToRight;
2107   else
2108     return;
2109
2110   web_view_->setTextDirection(direction);
2111 }
2112
2113 void TestRunner::UseUnfortunateSynchronousResizeMode() {
2114   delegate_->useUnfortunateSynchronousResizeMode(true);
2115 }
2116
2117 bool TestRunner::EnableAutoResizeMode(int min_width,
2118                                       int min_height,
2119                                       int max_width,
2120                                       int max_height) {
2121   WebSize min_size(min_width, min_height);
2122   WebSize max_size(max_width, max_height);
2123   delegate_->enableAutoResizeMode(min_size, max_size);
2124   return true;
2125 }
2126
2127 bool TestRunner::DisableAutoResizeMode(int new_width, int new_height) {
2128   WebSize new_size(new_width, new_height);
2129   delegate_->disableAutoResizeMode(new_size);
2130   return true;
2131 }
2132
2133 void TestRunner::SetMockDeviceMotion(
2134     bool has_acceleration_x, double acceleration_x,
2135     bool has_acceleration_y, double acceleration_y,
2136     bool has_acceleration_z, double acceleration_z,
2137     bool has_acceleration_including_gravity_x,
2138     double acceleration_including_gravity_x,
2139     bool has_acceleration_including_gravity_y,
2140     double acceleration_including_gravity_y,
2141     bool has_acceleration_including_gravity_z,
2142     double acceleration_including_gravity_z,
2143     bool has_rotation_rate_alpha, double rotation_rate_alpha,
2144     bool has_rotation_rate_beta, double rotation_rate_beta,
2145     bool has_rotation_rate_gamma, double rotation_rate_gamma,
2146     double interval) {
2147   WebDeviceMotionData motion;
2148
2149   // acceleration
2150   motion.hasAccelerationX = has_acceleration_x;
2151   motion.accelerationX = acceleration_x;
2152   motion.hasAccelerationY = has_acceleration_y;
2153   motion.accelerationY = acceleration_y;
2154   motion.hasAccelerationZ = has_acceleration_z;
2155   motion.accelerationZ = acceleration_z;
2156
2157   // accelerationIncludingGravity
2158   motion.hasAccelerationIncludingGravityX =
2159       has_acceleration_including_gravity_x;
2160   motion.accelerationIncludingGravityX = acceleration_including_gravity_x;
2161   motion.hasAccelerationIncludingGravityY =
2162       has_acceleration_including_gravity_y;
2163   motion.accelerationIncludingGravityY = acceleration_including_gravity_y;
2164   motion.hasAccelerationIncludingGravityZ =
2165       has_acceleration_including_gravity_z;
2166   motion.accelerationIncludingGravityZ = acceleration_including_gravity_z;
2167
2168   // rotationRate
2169   motion.hasRotationRateAlpha = has_rotation_rate_alpha;
2170   motion.rotationRateAlpha = rotation_rate_alpha;
2171   motion.hasRotationRateBeta = has_rotation_rate_beta;
2172   motion.rotationRateBeta = rotation_rate_beta;
2173   motion.hasRotationRateGamma = has_rotation_rate_gamma;
2174   motion.rotationRateGamma = rotation_rate_gamma;
2175
2176   // interval
2177   motion.interval = interval;
2178
2179   delegate_->setDeviceMotionData(motion);
2180 }
2181
2182 void TestRunner::SetMockDeviceOrientation(bool has_alpha, double alpha,
2183                                           bool has_beta, double beta,
2184                                           bool has_gamma, double gamma,
2185                                           bool has_absolute, bool absolute) {
2186   WebDeviceOrientationData orientation;
2187
2188   // alpha
2189   orientation.hasAlpha = has_alpha;
2190   orientation.alpha = alpha;
2191
2192   // beta
2193   orientation.hasBeta = has_beta;
2194   orientation.beta = beta;
2195
2196   // gamma
2197   orientation.hasGamma = has_gamma;
2198   orientation.gamma = gamma;
2199
2200   // absolute
2201   orientation.hasAbsolute = has_absolute;
2202   orientation.absolute = absolute;
2203
2204   delegate_->setDeviceOrientationData(orientation);
2205 }
2206
2207 void TestRunner::SetMockScreenOrientation(const std::string& orientation_str) {
2208   blink::WebScreenOrientationType orientation;
2209
2210   if (orientation_str == "portrait-primary") {
2211     orientation = WebScreenOrientationPortraitPrimary;
2212   } else if (orientation_str == "portrait-secondary") {
2213     orientation = WebScreenOrientationPortraitSecondary;
2214   } else if (orientation_str == "landscape-primary") {
2215     orientation = WebScreenOrientationLandscapePrimary;
2216   } else if (orientation_str == "landscape-secondary") {
2217     orientation = WebScreenOrientationLandscapeSecondary;
2218   }
2219
2220   delegate_->setScreenOrientation(orientation);
2221 }
2222
2223 void TestRunner::DidAcquirePointerLock() {
2224   DidAcquirePointerLockInternal();
2225 }
2226
2227 void TestRunner::DidNotAcquirePointerLock() {
2228   DidNotAcquirePointerLockInternal();
2229 }
2230
2231 void TestRunner::DidLosePointerLock() {
2232   DidLosePointerLockInternal();
2233 }
2234
2235 void TestRunner::SetPointerLockWillFailSynchronously() {
2236   pointer_lock_planned_result_ = PointerLockWillFailSync;
2237 }
2238
2239 void TestRunner::SetPointerLockWillRespondAsynchronously() {
2240   pointer_lock_planned_result_ = PointerLockWillRespondAsync;
2241 }
2242
2243 void TestRunner::SetPopupBlockingEnabled(bool block_popups) {
2244   delegate_->preferences()->java_script_can_open_windows_automatically =
2245       !block_popups;
2246   delegate_->applyPreferences();
2247 }
2248
2249 void TestRunner::SetJavaScriptCanAccessClipboard(bool can_access) {
2250   delegate_->preferences()->java_script_can_access_clipboard = can_access;
2251   delegate_->applyPreferences();
2252 }
2253
2254 void TestRunner::SetXSSAuditorEnabled(bool enabled) {
2255   delegate_->preferences()->xss_auditor_enabled = enabled;
2256   delegate_->applyPreferences();
2257 }
2258
2259 void TestRunner::SetAllowUniversalAccessFromFileURLs(bool allow) {
2260   delegate_->preferences()->allow_universal_access_from_file_urls = allow;
2261   delegate_->applyPreferences();
2262 }
2263
2264 void TestRunner::SetAllowFileAccessFromFileURLs(bool allow) {
2265   delegate_->preferences()->allow_file_access_from_file_urls = allow;
2266   delegate_->applyPreferences();
2267 }
2268
2269 void TestRunner::OverridePreference(const std::string key,
2270                                     v8::Handle<v8::Value> value) {
2271   TestPreferences* prefs = delegate_->preferences();
2272   if (key == "WebKitDefaultFontSize") {
2273     prefs->default_font_size = value->Int32Value();
2274   } else if (key == "WebKitMinimumFontSize") {
2275     prefs->minimum_font_size = value->Int32Value();
2276   } else if (key == "WebKitDefaultTextEncodingName") {
2277     prefs->default_text_encoding_name = V8StringToWebString(value->ToString());
2278   } else if (key == "WebKitJavaScriptEnabled") {
2279     prefs->java_script_enabled = value->BooleanValue();
2280   } else if (key == "WebKitSupportsMultipleWindows") {
2281     prefs->supports_multiple_windows = value->BooleanValue();
2282   } else if (key == "WebKitDisplayImagesKey") {
2283     prefs->loads_images_automatically = value->BooleanValue();
2284   } else if (key == "WebKitPluginsEnabled") {
2285     prefs->plugins_enabled = value->BooleanValue();
2286   } else if (key == "WebKitJavaEnabled") {
2287     prefs->java_enabled = value->BooleanValue();
2288   } else if (key == "WebKitOfflineWebApplicationCacheEnabled") {
2289     prefs->offline_web_application_cache_enabled = value->BooleanValue();
2290   } else if (key == "WebKitTabToLinksPreferenceKey") {
2291     prefs->tabs_to_links = value->BooleanValue();
2292   } else if (key == "WebKitWebGLEnabled") {
2293     prefs->experimental_webgl_enabled = value->BooleanValue();
2294   } else if (key == "WebKitCSSRegionsEnabled") {
2295     prefs->experimental_css_regions_enabled = value->BooleanValue();
2296   } else if (key == "WebKitCSSGridLayoutEnabled") {
2297     prefs->experimental_css_grid_layout_enabled = value->BooleanValue();
2298   } else if (key == "WebKitHyperlinkAuditingEnabled") {
2299     prefs->hyperlink_auditing_enabled = value->BooleanValue();
2300   } else if (key == "WebKitEnableCaretBrowsing") {
2301     prefs->caret_browsing_enabled = value->BooleanValue();
2302   } else if (key == "WebKitAllowDisplayingInsecureContent") {
2303     prefs->allow_display_of_insecure_content = value->BooleanValue();
2304   } else if (key == "WebKitAllowRunningInsecureContent") {
2305     prefs->allow_running_of_insecure_content = value->BooleanValue();
2306   } else if (key == "WebKitShouldRespectImageOrientation") {
2307     prefs->should_respect_image_orientation = value->BooleanValue();
2308   } else if (key == "WebKitWebAudioEnabled") {
2309     DCHECK(value->BooleanValue());
2310   } else {
2311     std::string message("Invalid name for preference: ");
2312     message.append(key);
2313     delegate_->printMessage(std::string("CONSOLE MESSAGE: ") + message + "\n");
2314   }
2315   delegate_->applyPreferences();
2316 }
2317
2318 void TestRunner::SetPluginsEnabled(bool enabled) {
2319   delegate_->preferences()->plugins_enabled = enabled;
2320   delegate_->applyPreferences();
2321 }
2322
2323 void TestRunner::DumpEditingCallbacks() {
2324   dump_editting_callbacks_ = true;
2325 }
2326
2327 void TestRunner::DumpAsText() {
2328   dump_as_text_ = true;
2329   generate_pixel_results_ = false;
2330 }
2331
2332 void TestRunner::DumpAsTextWithPixelResults() {
2333   dump_as_text_ = true;
2334   generate_pixel_results_ = true;
2335 }
2336
2337 void TestRunner::DumpChildFrameScrollPositions() {
2338   dump_child_frame_scroll_positions_ = true;
2339 }
2340
2341 void TestRunner::DumpChildFramesAsText() {
2342   dump_child_frames_as_text_ = true;
2343 }
2344
2345 void TestRunner::DumpIconChanges() {
2346   dump_icon_changes_ = true;
2347 }
2348
2349 void TestRunner::SetAudioData(const gin::ArrayBufferView& view) {
2350   unsigned char* bytes = static_cast<unsigned char*>(view.bytes());
2351   audio_data_.resize(view.num_bytes());
2352   std::copy(bytes, bytes + view.num_bytes(), audio_data_.begin());
2353   dump_as_audio_ = true;
2354 }
2355
2356 void TestRunner::DumpFrameLoadCallbacks() {
2357   dump_frame_load_callbacks_ = true;
2358 }
2359
2360 void TestRunner::DumpPingLoaderCallbacks() {
2361   dump_ping_loader_callbacks_ = true;
2362 }
2363
2364 void TestRunner::DumpUserGestureInFrameLoadCallbacks() {
2365   dump_user_gesture_in_frame_load_callbacks_ = true;
2366 }
2367
2368 void TestRunner::DumpTitleChanges() {
2369   dump_title_changes_ = true;
2370 }
2371
2372 void TestRunner::DumpCreateView() {
2373   dump_create_view_ = true;
2374 }
2375
2376 void TestRunner::SetCanOpenWindows() {
2377   can_open_windows_ = true;
2378 }
2379
2380 void TestRunner::DumpResourceLoadCallbacks() {
2381   dump_resource_load_callbacks_ = true;
2382 }
2383
2384 void TestRunner::DumpResourceRequestCallbacks() {
2385   dump_resource_request_callbacks_ = true;
2386 }
2387
2388 void TestRunner::DumpResourceResponseMIMETypes() {
2389   dump_resource_reqponse_mime_types_ = true;
2390 }
2391
2392 void TestRunner::SetImagesAllowed(bool allowed) {
2393   web_permissions_->setImagesAllowed(allowed);
2394 }
2395
2396 void TestRunner::SetScriptsAllowed(bool allowed) {
2397   web_permissions_->setScriptsAllowed(allowed);
2398 }
2399
2400 void TestRunner::SetStorageAllowed(bool allowed) {
2401   web_permissions_->setStorageAllowed(allowed);
2402 }
2403
2404 void TestRunner::SetPluginsAllowed(bool allowed) {
2405   web_permissions_->setPluginsAllowed(allowed);
2406 }
2407
2408 void TestRunner::SetAllowDisplayOfInsecureContent(bool allowed) {
2409   web_permissions_->setDisplayingInsecureContentAllowed(allowed);
2410 }
2411
2412 void TestRunner::SetAllowRunningOfInsecureContent(bool allowed) {
2413   web_permissions_->setRunningInsecureContentAllowed(allowed);
2414 }
2415
2416 void TestRunner::DumpPermissionClientCallbacks() {
2417   web_permissions_->setDumpCallbacks(true);
2418 }
2419
2420 void TestRunner::DumpWindowStatusChanges() {
2421   dump_window_status_changes_ = true;
2422 }
2423
2424 void TestRunner::DumpProgressFinishedCallback() {
2425   dump_progress_finished_callback_ = true;
2426 }
2427
2428 void TestRunner::DumpSpellCheckCallbacks() {
2429   dump_spell_check_callbacks_ = true;
2430 }
2431
2432 void TestRunner::DumpBackForwardList() {
2433   dump_back_forward_list_ = true;
2434 }
2435
2436 void TestRunner::DumpSelectionRect() {
2437   dump_selection_rect_ = true;
2438 }
2439
2440 void TestRunner::SetPrinting() {
2441   is_printing_ = true;
2442 }
2443
2444 void TestRunner::SetShouldStayOnPageAfterHandlingBeforeUnload(bool value) {
2445   should_stay_on_page_after_handling_before_unload_ = value;
2446 }
2447
2448 void TestRunner::SetWillSendRequestClearHeader(const std::string& header) {
2449   if (!header.empty())
2450     http_headers_to_clear_.insert(header);
2451 }
2452
2453 void TestRunner::DumpResourceRequestPriorities() {
2454   should_dump_resource_priorities_ = true;
2455 }
2456
2457 void TestRunner::SetUseMockTheme(bool use) {
2458   use_mock_theme_ = use;
2459 }
2460
2461 void TestRunner::ShowWebInspector(const std::string& str,
2462                                   const std::string& frontend_url) {
2463   showDevTools(str, frontend_url);
2464 }
2465
2466 void TestRunner::WaitUntilExternalURLLoad() {
2467   wait_until_external_url_load_ = true;
2468 }
2469
2470 void TestRunner::CloseWebInspector() {
2471   delegate_->closeDevTools();
2472 }
2473
2474 bool TestRunner::IsChooserShown() {
2475   return proxy_->isChooserShown();
2476 }
2477
2478 void TestRunner::EvaluateInWebInspector(int call_id,
2479                                         const std::string& script) {
2480   delegate_->evaluateInWebInspector(call_id, script);
2481 }
2482
2483 void TestRunner::ClearAllDatabases() {
2484   delegate_->clearAllDatabases();
2485 }
2486
2487 void TestRunner::SetDatabaseQuota(int quota) {
2488   delegate_->setDatabaseQuota(quota);
2489 }
2490
2491 void TestRunner::SetAlwaysAcceptCookies(bool accept) {
2492   delegate_->setAcceptAllCookies(accept);
2493 }
2494
2495 void TestRunner::SetWindowIsKey(bool value) {
2496   delegate_->setFocus(proxy_, value);
2497 }
2498
2499 std::string TestRunner::PathToLocalResource(const std::string& path) {
2500   return delegate_->pathToLocalResource(path);
2501 }
2502
2503 void TestRunner::SetBackingScaleFactor(double value,
2504                                        v8::Handle<v8::Function> callback) {
2505   delegate_->setDeviceScaleFactor(value);
2506   proxy_->discardBackingStore();
2507   delegate_->postTask(new InvokeCallbackTask(this, callback));
2508 }
2509
2510 void TestRunner::SetColorProfile(const std::string& name,
2511                                  v8::Handle<v8::Function> callback) {
2512   delegate_->setDeviceColorProfile(name);
2513   delegate_->postTask(new InvokeCallbackTask(this, callback));
2514 }
2515
2516 void TestRunner::SetPOSIXLocale(const std::string& locale) {
2517   delegate_->setLocale(locale);
2518 }
2519
2520 void TestRunner::SetMIDIAccessorResult(bool result) {
2521   midi_accessor_result_ = result;
2522 }
2523
2524 void TestRunner::SetMIDISysexPermission(bool value) {
2525   const std::vector<WebTestProxyBase*>& windowList =
2526       test_interfaces_->windowList();
2527   for (unsigned i = 0; i < windowList.size(); ++i)
2528     windowList.at(i)->midiClientMock()->setSysexPermission(value);
2529 }
2530
2531 void TestRunner::GrantWebNotificationPermission(const std::string& origin,
2532                                                 bool permission_granted) {
2533   notification_presenter_->GrantPermission(origin, permission_granted);
2534 }
2535
2536 bool TestRunner::SimulateWebNotificationClick(const std::string& value) {
2537   return notification_presenter_->SimulateClick(value);
2538 }
2539
2540 void TestRunner::AddMockSpeechRecognitionResult(const std::string& transcript,
2541                                                 double confidence) {
2542   proxy_->speechRecognizerMock()->addMockResult(
2543       WebString::fromUTF8(transcript), confidence);
2544 }
2545
2546 void TestRunner::SetMockSpeechRecognitionError(const std::string& error,
2547                                                const std::string& message) {
2548   proxy_->speechRecognizerMock()->setError(WebString::fromUTF8(error),
2549                                            WebString::fromUTF8(message));
2550 }
2551
2552 bool TestRunner::WasMockSpeechRecognitionAborted() {
2553   return proxy_->speechRecognizerMock()->wasAborted();
2554 }
2555
2556 void TestRunner::AddWebPageOverlay() {
2557   if (web_view_ && !page_overlay_) {
2558     page_overlay_ = new TestPageOverlay(web_view_);
2559     web_view_->addPageOverlay(page_overlay_, 0);
2560   }
2561 }
2562
2563 void TestRunner::RemoveWebPageOverlay() {
2564   if (web_view_ && page_overlay_) {
2565     web_view_->removePageOverlay(page_overlay_);
2566     delete page_overlay_;
2567     page_overlay_ = NULL;
2568   }
2569 }
2570
2571 void TestRunner::DisplayAsync() {
2572   proxy_->displayAsyncThen(base::Closure());
2573 }
2574
2575 void TestRunner::DisplayAsyncThen(v8::Handle<v8::Function> callback) {
2576   scoped_ptr<InvokeCallbackTask> task(
2577       new InvokeCallbackTask(this, callback));
2578   proxy_->displayAsyncThen(base::Bind(&TestRunner::InvokeCallback,
2579                                       base::Unretained(this),
2580                                       base::Passed(&task)));
2581 }
2582
2583 void TestRunner::LocationChangeDone() {
2584   web_history_item_count_ = delegate_->navigationEntryCount();
2585
2586   // No more new work after the first complete load.
2587   work_queue_.set_frozen(true);
2588
2589   if (!wait_until_done_)
2590     work_queue_.ProcessWorkSoon();
2591 }
2592
2593 void TestRunner::CheckResponseMimeType() {
2594   // Text output: the test page can request different types of output which we
2595   // handle here.
2596   if (!dump_as_text_) {
2597     std::string mimeType =
2598         web_view_->mainFrame()->dataSource()->response().mimeType().utf8();
2599     if (mimeType == "text/plain") {
2600       dump_as_text_ = true;
2601       generate_pixel_results_ = false;
2602     }
2603   }
2604 }
2605
2606 void TestRunner::CompleteNotifyDone() {
2607   if (wait_until_done_ && !topLoadingFrame() && work_queue_.is_empty())
2608     delegate_->testFinished();
2609   wait_until_done_ = false;
2610 }
2611
2612 void TestRunner::DidAcquirePointerLockInternal() {
2613   pointer_locked_ = true;
2614   web_view_->didAcquirePointerLock();
2615
2616   // Reset planned result to default.
2617   pointer_lock_planned_result_ = PointerLockWillSucceed;
2618 }
2619
2620 void TestRunner::DidNotAcquirePointerLockInternal() {
2621   DCHECK(!pointer_locked_);
2622   pointer_locked_ = false;
2623   web_view_->didNotAcquirePointerLock();
2624
2625   // Reset planned result to default.
2626   pointer_lock_planned_result_ = PointerLockWillSucceed;
2627 }
2628
2629 void TestRunner::DidLosePointerLockInternal() {
2630   bool was_locked = pointer_locked_;
2631   pointer_locked_ = false;
2632   if (was_locked)
2633     web_view_->didLosePointerLock();
2634 }
2635
2636 }  // namespace content