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.
5 #include "content/public/test/render_view_test.h"
7 #include "base/run_loop.h"
8 #include "content/common/dom_storage/dom_storage_types.h"
9 #include "content/common/frame_messages.h"
10 #include "content/common/input_messages.h"
11 #include "content/common/view_messages.h"
12 #include "content/public/browser/native_web_keyboard_event.h"
13 #include "content/public/common/renderer_preferences.h"
14 #include "content/public/renderer/history_item_serialization.h"
15 #include "content/renderer/render_thread_impl.h"
16 #include "content/renderer/render_view_impl.h"
17 #include "content/renderer/renderer_main_platform_delegate.h"
18 #include "content/renderer/renderer_webkitplatformsupport_impl.h"
19 #include "content/test/mock_render_process.h"
20 #include "third_party/WebKit/public/platform/WebScreenInfo.h"
21 #include "third_party/WebKit/public/platform/WebURLRequest.h"
22 #include "third_party/WebKit/public/web/WebFrame.h"
23 #include "third_party/WebKit/public/web/WebHistoryItem.h"
24 #include "third_party/WebKit/public/web/WebInputEvent.h"
25 #include "third_party/WebKit/public/web/WebKit.h"
26 #include "third_party/WebKit/public/web/WebScriptSource.h"
27 #include "third_party/WebKit/public/web/WebView.h"
28 #include "ui/base/resource/resource_bundle.h"
29 #include "v8/include/v8.h"
31 #if defined(OS_MACOSX)
32 #include "base/mac/scoped_nsautorelease_pool.h"
35 using blink::WebFrame;
36 using blink::WebInputEvent;
37 using blink::WebMouseEvent;
38 using blink::WebScriptSource;
39 using blink::WebString;
40 using blink::WebURLRequest;
43 const int32 kOpenerId = -2;
44 const int32 kRouteId = 5;
45 const int32 kMainFrameRouteId = 6;
46 const int32 kNewWindowRouteId = 7;
47 const int32 kNewFrameRouteId = 10;
48 const int32 kSurfaceId = 42;
54 class RendererWebKitPlatformSupportImplNoSandboxImpl
55 : public RendererWebKitPlatformSupportImpl {
57 virtual blink::WebSandboxSupport* sandboxSupport() {
62 RenderViewTest::RendererWebKitPlatformSupportImplNoSandbox::
63 RendererWebKitPlatformSupportImplNoSandbox() {
64 webkit_platform_support_.reset(
65 new RendererWebKitPlatformSupportImplNoSandboxImpl());
68 RenderViewTest::RendererWebKitPlatformSupportImplNoSandbox::
69 ~RendererWebKitPlatformSupportImplNoSandbox() {
73 RenderViewTest::RendererWebKitPlatformSupportImplNoSandbox::Get() {
74 return webkit_platform_support_.get();
77 RenderViewTest::RenderViewTest()
81 RenderViewTest::~RenderViewTest() {
84 void RenderViewTest::ProcessPendingMessages() {
85 msg_loop_.PostTask(FROM_HERE, base::MessageLoop::QuitClosure());
89 WebFrame* RenderViewTest::GetMainFrame() {
90 return view_->GetWebView()->mainFrame();
93 void RenderViewTest::ExecuteJavaScript(const char* js) {
94 GetMainFrame()->executeScript(WebScriptSource(WebString::fromUTF8(js)));
97 bool RenderViewTest::ExecuteJavaScriptAndReturnIntValue(
98 const base::string16& script,
100 v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
101 v8::Handle<v8::Value> result =
102 GetMainFrame()->executeScriptAndReturnValue(WebScriptSource(script));
103 if (result.IsEmpty() || !result->IsInt32())
107 *int_result = result->Int32Value();
112 void RenderViewTest::LoadHTML(const char* html) {
113 std::string url_str = "data:text/html;charset=utf-8,";
114 url_str.append(html);
117 GetMainFrame()->loadRequest(WebURLRequest(url));
119 // The load actually happens asynchronously, so we pump messages to process
120 // the pending continuation.
121 ProcessPendingMessages();
124 void RenderViewTest::GoBack(const blink::WebHistoryItem& item) {
125 GoToOffset(-1, item);
128 void RenderViewTest::GoForward(const blink::WebHistoryItem& item) {
132 void RenderViewTest::SetUp() {
133 // Subclasses can set the ContentClient's renderer before calling
134 // RenderViewTest::SetUp().
135 ContentRendererClient* old_client =
136 SetRendererClientForTesting(&content_renderer_client_);
138 SetRendererClientForTesting(old_client);
140 // Subclasses can set render_thread_ with their own implementation before
141 // calling RenderViewTest::SetUp().
143 render_thread_.reset(new MockRenderThread());
144 render_thread_->set_routing_id(kRouteId);
145 render_thread_->set_surface_id(kSurfaceId);
146 render_thread_->set_new_window_routing_id(kNewWindowRouteId);
147 render_thread_->set_new_frame_routing_id(kNewFrameRouteId);
149 #if defined(OS_MACOSX)
150 autorelease_pool_.reset(new base::mac::ScopedNSAutoreleasePool());
152 command_line_.reset(new CommandLine(CommandLine::NO_PROGRAM));
153 params_.reset(new MainFunctionParams(*command_line_));
154 platform_.reset(new RendererMainPlatformDelegate(*params_));
155 platform_->PlatformInitialize();
157 // Setting flags and really doing anything with WebKit is fairly fragile and
158 // hacky, but this is the world we live in...
159 std::string flags("--expose-gc");
160 v8::V8::SetFlagsFromString(flags.c_str(), static_cast<int>(flags.size()));
161 blink::initialize(webkit_platform_support_.Get());
163 // Ensure that we register any necessary schemes when initializing WebKit,
164 // since we are using a MockRenderThread.
165 RenderThreadImpl::RegisterSchemes();
167 // This check is needed because when run under content_browsertests,
168 // ResourceBundle isn't initialized (since we have to use a diferent test
169 // suite implementation than for content_unittests). For browser_tests, this
170 // is already initialized.
171 if (!ResourceBundle::HasSharedInstance())
172 ResourceBundle::InitSharedInstanceWithLocale("en-US", NULL);
174 mock_process_.reset(new MockRenderProcess);
176 // This needs to pass the mock render thread to the view.
177 RenderViewImpl* view = RenderViewImpl::Create(
179 RendererPreferences(),
184 kInvalidSessionStorageNamespaceId,
186 false, // is_renderer_created
187 false, // swapped_out
190 blink::WebScreenInfo(),
191 AccessibilityModeOff,
197 void RenderViewTest::TearDown() {
198 // Try very hard to collect garbage before shutting down.
199 // "5" was chosen following http://crbug.com/46571#c9
200 const int kGCIterations = 5;
201 for (int i = 0; i < kGCIterations; i++)
202 GetMainFrame()->collectGarbage();
204 // Run the loop so the release task from the renderwidget executes.
205 ProcessPendingMessages();
207 for (int i = 0; i < kGCIterations; i++)
208 GetMainFrame()->collectGarbage();
210 render_thread_->SendCloseMessage();
212 mock_process_.reset();
214 // After telling the view to close and resetting mock_process_ we may get
215 // some new tasks which need to be processed before shutting down WebKit
216 // (http://crbug.com/21508).
217 base::RunLoop().RunUntilIdle();
219 #if defined(OS_MACOSX)
220 // Needs to run before blink::shutdown().
221 autorelease_pool_.reset(NULL);
226 platform_->PlatformUninitialize();
229 command_line_.reset();
232 void RenderViewTest::SendNativeKeyEvent(
233 const NativeWebKeyboardEvent& key_event) {
234 SendWebKeyboardEvent(key_event);
237 void RenderViewTest::SendWebKeyboardEvent(
238 const blink::WebKeyboardEvent& key_event) {
239 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
240 impl->OnMessageReceived(
241 InputMsg_HandleInputEvent(0, &key_event, ui::LatencyInfo(), false));
244 void RenderViewTest::SendWebMouseEvent(
245 const blink::WebMouseEvent& mouse_event) {
246 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
247 impl->OnMessageReceived(
248 InputMsg_HandleInputEvent(0, &mouse_event, ui::LatencyInfo(), false));
251 const char* const kGetCoordinatesScript =
253 " function GetCoordinates(elem) {"
256 " var coordinates = [ elem.offsetLeft, elem.offsetTop];"
257 " var parent_coordinates = GetCoordinates(elem.offsetParent);"
258 " coordinates[0] += parent_coordinates[0];"
259 " coordinates[1] += parent_coordinates[1];"
260 " return coordinates;"
262 " var elem = document.getElementById('$1');"
265 " var bounds = GetCoordinates(elem);"
266 " bounds[2] = elem.offsetWidth;"
267 " bounds[3] = elem.offsetHeight;"
270 gfx::Rect RenderViewTest::GetElementBounds(const std::string& element_id) {
271 std::vector<std::string> params;
272 params.push_back(element_id);
274 ReplaceStringPlaceholders(kGetCoordinatesScript, params, NULL);
276 v8::Isolate* isolate = v8::Isolate::GetCurrent();
277 v8::HandleScope handle_scope(isolate);
278 v8::Handle<v8::Value> value = GetMainFrame()->executeScriptAndReturnValue(
279 WebScriptSource(WebString::fromUTF8(script)));
280 if (value.IsEmpty() || !value->IsArray())
283 v8::Handle<v8::Array> array = value.As<v8::Array>();
284 if (array->Length() != 4)
286 std::vector<int> coords;
287 for (int i = 0; i < 4; ++i) {
288 v8::Handle<v8::Number> index = v8::Number::New(isolate, i);
289 v8::Local<v8::Value> value = array->Get(index);
290 if (value.IsEmpty() || !value->IsInt32())
292 coords.push_back(value->Int32Value());
294 return gfx::Rect(coords[0], coords[1], coords[2], coords[3]);
297 bool RenderViewTest::SimulateElementClick(const std::string& element_id) {
298 gfx::Rect bounds = GetElementBounds(element_id);
299 if (bounds.IsEmpty())
301 WebMouseEvent mouse_event;
302 mouse_event.type = WebInputEvent::MouseDown;
303 mouse_event.button = WebMouseEvent::ButtonLeft;
304 mouse_event.x = bounds.CenterPoint().x();
305 mouse_event.y = bounds.CenterPoint().y();
306 mouse_event.clickCount = 1;
307 scoped_ptr<IPC::Message> input_message(
308 new InputMsg_HandleInputEvent(0, &mouse_event, ui::LatencyInfo(), false));
309 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
310 impl->OnMessageReceived(*input_message);
314 void RenderViewTest::SetFocused(const blink::WebNode& node) {
315 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
316 impl->focusedNodeChanged(node);
319 void RenderViewTest::ClearHistory() {
320 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
322 impl->history_list_offset_ = -1;
323 impl->history_list_length_ = 0;
324 impl->history_page_ids_.clear();
327 void RenderViewTest::Reload(const GURL& url) {
328 FrameMsg_Navigate_Params params;
330 params.navigation_type = FrameMsg_Navigate_Type::RELOAD;
331 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
332 impl->main_render_frame()->OnNavigate(params);
335 uint32 RenderViewTest::GetNavigationIPCType() {
336 return FrameHostMsg_DidCommitProvisionalLoad::ID;
339 void RenderViewTest::Resize(gfx::Size new_size,
340 gfx::Rect resizer_rect,
341 bool is_fullscreen) {
342 ViewMsg_Resize_Params params;
343 params.screen_info = blink::WebScreenInfo();
344 params.new_size = new_size;
345 params.physical_backing_size = new_size;
346 params.overdraw_bottom_height = 0.f;
347 params.resizer_rect = resizer_rect;
348 params.is_fullscreen = is_fullscreen;
349 scoped_ptr<IPC::Message> resize_message(new ViewMsg_Resize(0, params));
350 OnMessageReceived(*resize_message);
353 bool RenderViewTest::OnMessageReceived(const IPC::Message& msg) {
354 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
355 return impl->OnMessageReceived(msg);
358 void RenderViewTest::DidNavigateWithinPage(blink::WebFrame* frame,
359 bool is_new_navigation) {
360 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
361 impl->didNavigateWithinPage(frame, is_new_navigation);
364 void RenderViewTest::SendContentStateImmediately() {
365 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
366 impl->set_send_content_state_immediately(true);
369 blink::WebWidget* RenderViewTest::GetWebWidget() {
370 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
371 return impl->webwidget();
374 void RenderViewTest::GoToOffset(int offset,
375 const blink::WebHistoryItem& history_item) {
376 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
378 int history_list_length = impl->historyBackListCount() +
379 impl->historyForwardListCount() + 1;
380 int pending_offset = offset + impl->history_list_offset();
382 FrameMsg_Navigate_Params navigate_params;
383 navigate_params.navigation_type = FrameMsg_Navigate_Type::NORMAL;
384 navigate_params.transition = PAGE_TRANSITION_FORWARD_BACK;
385 navigate_params.current_history_list_length = history_list_length;
386 navigate_params.current_history_list_offset = impl->history_list_offset();
387 navigate_params.pending_history_list_offset = pending_offset;
388 navigate_params.page_id = impl->GetPageId() + offset;
389 navigate_params.page_state = HistoryItemToPageState(history_item);
390 navigate_params.request_time = base::Time::Now();
392 FrameMsg_Navigate navigate_message(impl->main_render_frame()->GetRoutingID(),
394 impl->main_render_frame()->OnMessageReceived(navigate_message);
396 // The load actually happens asynchronously, so we pump messages to process
397 // the pending continuation.
398 ProcessPendingMessages();
401 } // namespace content