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