render_view_test.cc revision b2df76ea8fec9e32f6f3718986dba0d95315b29c
1// Copyright (c) 2012 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/public/test/render_view_test.h" 6 7#include "base/run_loop.h" 8#include "content/common/input_messages.h" 9#include "content/common/view_messages.h" 10#include "content/public/browser/native_web_keyboard_event.h" 11#include "content/public/common/renderer_preferences.h" 12#include "content/renderer/render_thread_impl.h" 13#include "content/renderer/render_view_impl.h" 14#include "content/renderer/renderer_main_platform_delegate.h" 15#include "content/renderer/renderer_webkitplatformsupport_impl.h" 16#include "content/test/mock_render_process.h" 17#include "third_party/WebKit/Source/Platform/chromium/public/WebURLRequest.h" 18#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h" 19#include "third_party/WebKit/Source/WebKit/chromium/public/WebHistoryItem.h" 20#include "third_party/WebKit/Source/WebKit/chromium/public/WebInputEvent.h" 21#include "third_party/WebKit/Source/WebKit/chromium/public/WebKit.h" 22#include "third_party/WebKit/Source/WebKit/chromium/public/WebScreenInfo.h" 23#include "third_party/WebKit/Source/WebKit/chromium/public/WebScriptController.h" 24#include "third_party/WebKit/Source/WebKit/chromium/public/WebScriptSource.h" 25#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" 26#include "ui/base/resource/resource_bundle.h" 27#include "webkit/dom_storage/dom_storage_types.h" 28#include "webkit/glue/glue_serialize.h" 29#include "webkit/glue/webkit_glue.h" 30 31using WebKit::WebFrame; 32using WebKit::WebInputEvent; 33using WebKit::WebMouseEvent; 34using WebKit::WebScriptController; 35using WebKit::WebScriptSource; 36using WebKit::WebString; 37using WebKit::WebURLRequest; 38 39namespace { 40const int32 kOpenerId = -2; 41const int32 kRouteId = 5; 42const int32 kNewWindowRouteId = 6; 43const int32 kSurfaceId = 42; 44 45} // namespace 46 47namespace content { 48 49class RendererWebKitPlatformSupportImplNoSandboxImpl 50 : public RendererWebKitPlatformSupportImpl { 51 public: 52 virtual WebKit::WebSandboxSupport* sandboxSupport() { 53 return NULL; 54 } 55}; 56 57RenderViewTest::RendererWebKitPlatformSupportImplNoSandbox:: 58 RendererWebKitPlatformSupportImplNoSandbox() { 59 webkit_platform_support_.reset( 60 new RendererWebKitPlatformSupportImplNoSandboxImpl()); 61} 62 63RenderViewTest::RendererWebKitPlatformSupportImplNoSandbox:: 64 ~RendererWebKitPlatformSupportImplNoSandbox() { 65} 66 67WebKit::Platform* 68 RenderViewTest::RendererWebKitPlatformSupportImplNoSandbox::Get() { 69 return webkit_platform_support_.get(); 70} 71 72RenderViewTest::RenderViewTest() 73 : view_(NULL) { 74} 75 76RenderViewTest::~RenderViewTest() { 77} 78 79void RenderViewTest::ProcessPendingMessages() { 80 msg_loop_.PostTask(FROM_HERE, base::MessageLoop::QuitClosure()); 81 msg_loop_.Run(); 82} 83 84WebFrame* RenderViewTest::GetMainFrame() { 85 return view_->GetWebView()->mainFrame(); 86} 87 88void RenderViewTest::ExecuteJavaScript(const char* js) { 89 GetMainFrame()->executeScript(WebScriptSource(WebString::fromUTF8(js))); 90} 91 92bool RenderViewTest::ExecuteJavaScriptAndReturnIntValue( 93 const string16& script, 94 int* int_result) { 95 v8::HandleScope handle_scope; 96 v8::Handle<v8::Value> result = 97 GetMainFrame()->executeScriptAndReturnValue(WebScriptSource(script)); 98 if (result.IsEmpty() || !result->IsInt32()) 99 return false; 100 101 if (int_result) 102 *int_result = result->Int32Value(); 103 104 return true; 105} 106 107void RenderViewTest::LoadHTML(const char* html) { 108 std::string url_str = "data:text/html;charset=utf-8,"; 109 url_str.append(html); 110 GURL url(url_str); 111 112 GetMainFrame()->loadRequest(WebURLRequest(url)); 113 114 // The load actually happens asynchronously, so we pump messages to process 115 // the pending continuation. 116 ProcessPendingMessages(); 117} 118 119void RenderViewTest::GoBack(const WebKit::WebHistoryItem& item) { 120 GoToOffset(-1, item); 121} 122 123void RenderViewTest::GoForward(const WebKit::WebHistoryItem& item) { 124 GoToOffset(1, item); 125} 126 127void RenderViewTest::SetUp() { 128 // Subclasses can set the ContentClient's renderer before calling 129 // RenderViewTest::SetUp(). 130 ContentRendererClient* old_client = 131 SetRendererClientForTesting(&content_renderer_client_); 132 if (old_client) 133 SetRendererClientForTesting(old_client); 134 135 // Subclasses can set render_thread_ with their own implementation before 136 // calling RenderViewTest::SetUp(). 137 if (!render_thread_) 138 render_thread_.reset(new MockRenderThread()); 139 render_thread_->set_routing_id(kRouteId); 140 render_thread_->set_surface_id(kSurfaceId); 141 render_thread_->set_new_window_routing_id(kNewWindowRouteId); 142 143 command_line_.reset(new CommandLine(CommandLine::NO_PROGRAM)); 144 params_.reset(new MainFunctionParams(*command_line_)); 145 platform_.reset(new RendererMainPlatformDelegate(*params_)); 146 platform_->PlatformInitialize(); 147 148 // Setting flags and really doing anything with WebKit is fairly fragile and 149 // hacky, but this is the world we live in... 150 webkit_glue::SetJavaScriptFlags(" --expose-gc"); 151 WebKit::initialize(webkit_platform_support_.Get()); 152 153 // Ensure that we register any necessary schemes when initializing WebKit, 154 // since we are using a MockRenderThread. 155 RenderThreadImpl::RegisterSchemes(); 156 157 // This check is needed because when run under content_browsertests, 158 // ResourceBundle isn't initialized (since we have to use a diferent test 159 // suite implementation than for content_unittests). For browser_tests, this 160 // is already initialized. 161 if (!ResourceBundle::HasSharedInstance()) 162 ResourceBundle::InitSharedInstanceWithLocale("en-US", NULL); 163 164 mock_process_.reset(new MockRenderProcess); 165 166 // This needs to pass the mock render thread to the view. 167 RenderViewImpl* view = RenderViewImpl::Create( 168 kOpenerId, 169 RendererPreferences(), 170 WebPreferences(), 171 new SharedRenderViewCounter(0), 172 kRouteId, 173 kSurfaceId, 174 dom_storage::kInvalidSessionStorageNamespaceId, 175 string16(), 176 false, 177 false, 178 1, 179 WebKit::WebScreenInfo(), 180 AccessibilityModeOff, 181 true); 182 view->AddRef(); 183 view_ = view; 184} 185 186void RenderViewTest::TearDown() { 187 // Try very hard to collect garbage before shutting down. 188 GetMainFrame()->collectGarbage(); 189 GetMainFrame()->collectGarbage(); 190 191 // Run the loop so the release task from the renderwidget executes. 192 ProcessPendingMessages(); 193 194 render_thread_->SendCloseMessage(); 195 view_ = NULL; 196 mock_process_.reset(); 197 198 // After telling the view to close and resetting mock_process_ we may get 199 // some new tasks which need to be processed before shutting down WebKit 200 // (http://crbug.com/21508). 201 base::RunLoop().RunUntilIdle(); 202 203 WebKit::shutdown(); 204 205 platform_->PlatformUninitialize(); 206 platform_.reset(); 207 params_.reset(); 208 command_line_.reset(); 209} 210 211void RenderViewTest::SendNativeKeyEvent( 212 const NativeWebKeyboardEvent& key_event) { 213 SendWebKeyboardEvent(key_event); 214} 215 216void RenderViewTest::SendWebKeyboardEvent( 217 const WebKit::WebKeyboardEvent& key_event) { 218 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_); 219 impl->OnMessageReceived( 220 InputMsg_HandleInputEvent(0, &key_event, cc::LatencyInfo(), false)); 221} 222 223void RenderViewTest::SendWebMouseEvent( 224 const WebKit::WebMouseEvent& mouse_event) { 225 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_); 226 impl->OnMessageReceived( 227 InputMsg_HandleInputEvent(0, &mouse_event, cc::LatencyInfo(), false)); 228} 229 230const char* const kGetCoordinatesScript = 231 "(function() {" 232 " function GetCoordinates(elem) {" 233 " if (!elem)" 234 " return [ 0, 0];" 235 " var coordinates = [ elem.offsetLeft, elem.offsetTop];" 236 " var parent_coordinates = GetCoordinates(elem.offsetParent);" 237 " coordinates[0] += parent_coordinates[0];" 238 " coordinates[1] += parent_coordinates[1];" 239 " return coordinates;" 240 " };" 241 " var elem = document.getElementById('$1');" 242 " if (!elem)" 243 " return null;" 244 " var bounds = GetCoordinates(elem);" 245 " bounds[2] = elem.offsetWidth;" 246 " bounds[3] = elem.offsetHeight;" 247 " return bounds;" 248 "})();"; 249gfx::Rect RenderViewTest::GetElementBounds(const std::string& element_id) { 250 std::vector<std::string> params; 251 params.push_back(element_id); 252 std::string script = 253 ReplaceStringPlaceholders(kGetCoordinatesScript, params, NULL); 254 255 v8::HandleScope handle_scope; 256 v8::Handle<v8::Value> value = GetMainFrame()->executeScriptAndReturnValue( 257 WebScriptSource(WebString::fromUTF8(script))); 258 if (value.IsEmpty() || !value->IsArray()) 259 return gfx::Rect(); 260 261 v8::Handle<v8::Array> array = value.As<v8::Array>(); 262 if (array->Length() != 4) 263 return gfx::Rect(); 264 std::vector<int> coords; 265 for (int i = 0; i < 4; ++i) { 266 v8::Handle<v8::Number> index = v8::Number::New(i); 267 v8::Local<v8::Value> value = array->Get(index); 268 if (value.IsEmpty() || !value->IsInt32()) 269 return gfx::Rect(); 270 coords.push_back(value->Int32Value()); 271 } 272 return gfx::Rect(coords[0], coords[1], coords[2], coords[3]); 273} 274 275bool RenderViewTest::SimulateElementClick(const std::string& element_id) { 276 gfx::Rect bounds = GetElementBounds(element_id); 277 if (bounds.IsEmpty()) 278 return false; 279 WebMouseEvent mouse_event; 280 mouse_event.type = WebInputEvent::MouseDown; 281 mouse_event.button = WebMouseEvent::ButtonLeft; 282 mouse_event.x = bounds.CenterPoint().x(); 283 mouse_event.y = bounds.CenterPoint().y(); 284 mouse_event.clickCount = 1; 285 scoped_ptr<IPC::Message> input_message( 286 new InputMsg_HandleInputEvent(0, &mouse_event, cc::LatencyInfo(), false)); 287 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_); 288 impl->OnMessageReceived(*input_message); 289 return true; 290} 291 292void RenderViewTest::SetFocused(const WebKit::WebNode& node) { 293 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_); 294 impl->focusedNodeChanged(node); 295} 296 297void RenderViewTest::ClearHistory() { 298 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_); 299 impl->page_id_ = -1; 300 impl->history_list_offset_ = -1; 301 impl->history_list_length_ = 0; 302 impl->history_page_ids_.clear(); 303} 304 305void RenderViewTest::Reload(const GURL& url) { 306 ViewMsg_Navigate_Params params; 307 params.url = url; 308 params.navigation_type = ViewMsg_Navigate_Type::RELOAD; 309 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_); 310 impl->OnNavigate(params); 311} 312 313uint32 RenderViewTest::GetNavigationIPCType() { 314 return ViewHostMsg_FrameNavigate::ID; 315} 316 317void RenderViewTest::Resize(gfx::Size new_size, 318 gfx::Rect resizer_rect, 319 bool is_fullscreen) { 320 scoped_ptr<IPC::Message> resize_message(new ViewMsg_Resize( 321 0, new_size, new_size, 0.f, resizer_rect, is_fullscreen)); 322 OnMessageReceived(*resize_message); 323} 324 325bool RenderViewTest::OnMessageReceived(const IPC::Message& msg) { 326 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_); 327 return impl->OnMessageReceived(msg); 328} 329 330void RenderViewTest::DidNavigateWithinPage(WebKit::WebFrame* frame, 331 bool is_new_navigation) { 332 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_); 333 impl->didNavigateWithinPage(frame, is_new_navigation); 334} 335 336void RenderViewTest::SendContentStateImmediately() { 337 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_); 338 impl->set_send_content_state_immediately(true); 339} 340 341WebKit::WebWidget* RenderViewTest::GetWebWidget() { 342 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_); 343 return impl->webwidget(); 344} 345 346void RenderViewTest::GoToOffset(int offset, 347 const WebKit::WebHistoryItem& history_item) { 348 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_); 349 350 int history_list_length = impl->historyBackListCount() + 351 impl->historyForwardListCount() + 1; 352 int pending_offset = offset + impl->history_list_offset(); 353 354 ViewMsg_Navigate_Params navigate_params; 355 navigate_params.navigation_type = ViewMsg_Navigate_Type::NORMAL; 356 navigate_params.transition = PAGE_TRANSITION_FORWARD_BACK; 357 navigate_params.current_history_list_length = history_list_length; 358 navigate_params.current_history_list_offset = impl->history_list_offset(); 359 navigate_params.pending_history_list_offset = pending_offset; 360 navigate_params.page_id = impl->GetPageId() + offset; 361 navigate_params.state = webkit_glue::HistoryItemToString(history_item); 362 navigate_params.request_time = base::Time::Now(); 363 364 ViewMsg_Navigate navigate_message(impl->GetRoutingID(), navigate_params); 365 OnMessageReceived(navigate_message); 366 367 // The load actually happens asynchronously, so we pump messages to process 368 // the pending continuation. 369 ProcessPendingMessages(); 370} 371 372} // namespace content 373