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/content_browser_client.h"
13 #include "content/public/browser/native_web_keyboard_event.h"
14 #include "content/public/common/content_client.h"
15 #include "content/public/common/renderer_preferences.h"
16 #include "content/public/renderer/content_renderer_client.h"
17 #include "content/public/test/frame_load_waiter.h"
18 #include "content/renderer/history_controller.h"
19 #include "content/renderer/history_serialization.h"
20 #include "content/renderer/render_thread_impl.h"
21 #include "content/renderer/render_view_impl.h"
22 #include "content/renderer/renderer_blink_platform_impl.h"
23 #include "content/renderer/renderer_main_platform_delegate.h"
24 #include "content/renderer/scheduler/renderer_scheduler.h"
25 #include "content/test/mock_render_process.h"
26 #include "content/test/test_content_client.h"
27 #include "third_party/WebKit/public/platform/WebScreenInfo.h"
28 #include "third_party/WebKit/public/platform/WebURLRequest.h"
29 #include "third_party/WebKit/public/web/WebHistoryItem.h"
30 #include "third_party/WebKit/public/web/WebInputEvent.h"
31 #include "third_party/WebKit/public/web/WebKit.h"
32 #include "third_party/WebKit/public/web/WebLocalFrame.h"
33 #include "third_party/WebKit/public/web/WebScriptSource.h"
34 #include "third_party/WebKit/public/web/WebView.h"
35 #include "ui/base/resource/resource_bundle.h"
36 #include "v8/include/v8.h"
38 #if defined(OS_MACOSX)
39 #include "base/mac/scoped_nsautorelease_pool.h"
42 using blink::WebInputEvent
;
43 using blink::WebLocalFrame
;
44 using blink::WebMouseEvent
;
45 using blink::WebScriptSource
;
46 using blink::WebString
;
47 using blink::WebURLRequest
;
50 const int32 kOpenerId
= -2;
51 const int32 kRouteId
= 5;
52 const int32 kMainFrameRouteId
= 6;
53 const int32 kNewWindowRouteId
= 7;
54 const int32 kNewFrameRouteId
= 10;
55 const int32 kSurfaceId
= 42;
61 class RendererBlinkPlatformImplNoSandboxImpl
62 : public RendererBlinkPlatformImpl
{
64 RendererBlinkPlatformImplNoSandboxImpl(RendererScheduler
* scheduler
)
65 : RendererBlinkPlatformImpl(scheduler
) {}
67 virtual blink::WebSandboxSupport
* sandboxSupport() {
72 RenderViewTest::RendererBlinkPlatformImplNoSandbox::
73 RendererBlinkPlatformImplNoSandbox() {
74 renderer_scheduler_
= RendererScheduler::Create();
75 blink_platform_impl_
.reset(
76 new RendererBlinkPlatformImplNoSandboxImpl(renderer_scheduler_
.get()));
79 RenderViewTest::RendererBlinkPlatformImplNoSandbox::
80 ~RendererBlinkPlatformImplNoSandbox() {
83 blink::Platform
* RenderViewTest::RendererBlinkPlatformImplNoSandbox::Get() {
84 return blink_platform_impl_
.get();
87 RenderViewTest::RenderViewTest()
91 RenderViewTest::~RenderViewTest() {
94 void RenderViewTest::ProcessPendingMessages() {
95 msg_loop_
.PostTask(FROM_HERE
, base::MessageLoop::QuitClosure());
99 WebLocalFrame
* RenderViewTest::GetMainFrame() {
100 return view_
->GetWebView()->mainFrame()->toWebLocalFrame();
103 void RenderViewTest::ExecuteJavaScript(const char* js
) {
104 GetMainFrame()->executeScript(WebScriptSource(WebString::fromUTF8(js
)));
107 bool RenderViewTest::ExecuteJavaScriptAndReturnIntValue(
108 const base::string16
& script
,
110 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
111 v8::Handle
<v8::Value
> result
=
112 GetMainFrame()->executeScriptAndReturnValue(WebScriptSource(script
));
113 if (result
.IsEmpty() || !result
->IsInt32())
117 *int_result
= result
->Int32Value();
122 void RenderViewTest::LoadHTML(const char* html
) {
123 std::string url_str
= "data:text/html;charset=utf-8,";
124 url_str
.append(html
);
126 GetMainFrame()->loadRequest(WebURLRequest(url
));
127 // The load actually happens asynchronously, so we pump messages to process
128 // the pending continuation.
129 FrameLoadWaiter(view_
->GetMainRenderFrame()).Wait();
132 PageState
RenderViewTest::GetCurrentPageState() {
133 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
134 return HistoryEntryToPageState(impl
->history_controller()->GetCurrentEntry());
137 void RenderViewTest::GoBack(const PageState
& state
) {
138 GoToOffset(-1, state
);
141 void RenderViewTest::GoForward(const PageState
& state
) {
142 GoToOffset(1, state
);
145 void RenderViewTest::SetUp() {
146 content_client_
.reset(CreateContentClient());
147 content_browser_client_
.reset(CreateContentBrowserClient());
148 content_renderer_client_
.reset(CreateContentRendererClient());
149 SetContentClient(content_client_
.get());
150 SetBrowserClientForTesting(content_browser_client_
.get());
151 SetRendererClientForTesting(content_renderer_client_
.get());
153 // Subclasses can set render_thread_ with their own implementation before
154 // calling RenderViewTest::SetUp().
156 render_thread_
.reset(new MockRenderThread());
157 render_thread_
->set_routing_id(kRouteId
);
158 render_thread_
->set_surface_id(kSurfaceId
);
159 render_thread_
->set_new_window_routing_id(kNewWindowRouteId
);
160 render_thread_
->set_new_frame_routing_id(kNewFrameRouteId
);
162 #if defined(OS_MACOSX)
163 autorelease_pool_
.reset(new base::mac::ScopedNSAutoreleasePool());
165 command_line_
.reset(new CommandLine(CommandLine::NO_PROGRAM
));
166 params_
.reset(new MainFunctionParams(*command_line_
));
167 platform_
.reset(new RendererMainPlatformDelegate(*params_
));
168 platform_
->PlatformInitialize();
170 // Setting flags and really doing anything with WebKit is fairly fragile and
171 // hacky, but this is the world we live in...
172 std::string
flags("--expose-gc");
173 v8::V8::SetFlagsFromString(flags
.c_str(), static_cast<int>(flags
.size()));
174 blink::initialize(blink_platform_impl_
.Get());
176 // Ensure that we register any necessary schemes when initializing WebKit,
177 // since we are using a MockRenderThread.
178 RenderThreadImpl::RegisterSchemes();
180 // This check is needed because when run under content_browsertests,
181 // ResourceBundle isn't initialized (since we have to use a diferent test
182 // suite implementation than for content_unittests). For browser_tests, this
183 // is already initialized.
184 if (!ui::ResourceBundle::HasSharedInstance())
185 ui::ResourceBundle::InitSharedInstanceWithLocale(
186 "en-US", NULL
, ui::ResourceBundle::LOAD_COMMON_RESOURCES
);
188 mock_process_
.reset(new MockRenderProcess
);
190 ViewMsg_New_Params view_params
;
191 view_params
.opener_route_id
= kOpenerId
;
192 view_params
.window_was_created_with_opener
= false;
193 view_params
.renderer_preferences
= RendererPreferences();
194 view_params
.web_preferences
= WebPreferences();
195 view_params
.view_id
= kRouteId
;
196 view_params
.main_frame_routing_id
= kMainFrameRouteId
;
197 view_params
.surface_id
= kSurfaceId
;
198 view_params
.session_storage_namespace_id
= kInvalidSessionStorageNamespaceId
;
199 view_params
.frame_name
= base::string16();
200 view_params
.swapped_out
= false;
201 view_params
.replicated_frame_state
= FrameReplicationState();
202 view_params
.proxy_routing_id
= MSG_ROUTING_NONE
;
203 view_params
.hidden
= false;
204 view_params
.never_visible
= false;
205 view_params
.next_page_id
= 1;
206 view_params
.initial_size
= *InitialSizeParams();
207 view_params
.enable_auto_resize
= false;
208 view_params
.min_size
= gfx::Size();
209 view_params
.max_size
= gfx::Size();
211 // This needs to pass the mock render thread to the view.
212 RenderViewImpl
* view
= RenderViewImpl::Create(view_params
, false);
217 void RenderViewTest::TearDown() {
218 // Try very hard to collect garbage before shutting down.
219 // "5" was chosen following http://crbug.com/46571#c9
220 const int kGCIterations
= 5;
221 for (int i
= 0; i
< kGCIterations
; i
++)
222 GetMainFrame()->collectGarbage();
224 // Run the loop so the release task from the renderwidget executes.
225 ProcessPendingMessages();
227 for (int i
= 0; i
< kGCIterations
; i
++)
228 GetMainFrame()->collectGarbage();
230 render_thread_
->SendCloseMessage();
232 mock_process_
.reset();
234 // After telling the view to close and resetting mock_process_ we may get
235 // some new tasks which need to be processed before shutting down WebKit
236 // (http://crbug.com/21508).
237 base::RunLoop().RunUntilIdle();
239 #if defined(OS_MACOSX)
240 // Needs to run before blink::shutdown().
241 autorelease_pool_
.reset(NULL
);
246 platform_
->PlatformUninitialize();
249 command_line_
.reset();
252 void RenderViewTest::SendNativeKeyEvent(
253 const NativeWebKeyboardEvent
& key_event
) {
254 SendWebKeyboardEvent(key_event
);
257 void RenderViewTest::SendWebKeyboardEvent(
258 const blink::WebKeyboardEvent
& key_event
) {
259 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
260 impl
->OnMessageReceived(
261 InputMsg_HandleInputEvent(0, &key_event
, ui::LatencyInfo(), false));
264 void RenderViewTest::SendWebMouseEvent(
265 const blink::WebMouseEvent
& mouse_event
) {
266 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
267 impl
->OnMessageReceived(
268 InputMsg_HandleInputEvent(0, &mouse_event
, ui::LatencyInfo(), false));
271 const char* const kGetCoordinatesScript
=
273 " function GetCoordinates(elem) {"
276 " var coordinates = [ elem.offsetLeft, elem.offsetTop];"
277 " var parent_coordinates = GetCoordinates(elem.offsetParent);"
278 " coordinates[0] += parent_coordinates[0];"
279 " coordinates[1] += parent_coordinates[1];"
280 " return [ Math.round(coordinates[0]),"
281 " Math.round(coordinates[1])];"
283 " var elem = document.getElementById('$1');"
286 " var bounds = GetCoordinates(elem);"
287 " bounds[2] = Math.round(elem.offsetWidth);"
288 " bounds[3] = Math.round(elem.offsetHeight);"
291 gfx::Rect
RenderViewTest::GetElementBounds(const std::string
& element_id
) {
292 std::vector
<std::string
> params
;
293 params
.push_back(element_id
);
295 ReplaceStringPlaceholders(kGetCoordinatesScript
, params
, NULL
);
297 v8::Isolate
* isolate
= v8::Isolate::GetCurrent();
298 v8::HandleScope
handle_scope(isolate
);
299 v8::Handle
<v8::Value
> value
= GetMainFrame()->executeScriptAndReturnValue(
300 WebScriptSource(WebString::fromUTF8(script
)));
301 if (value
.IsEmpty() || !value
->IsArray())
304 v8::Handle
<v8::Array
> array
= value
.As
<v8::Array
>();
305 if (array
->Length() != 4)
307 std::vector
<int> coords
;
308 for (int i
= 0; i
< 4; ++i
) {
309 v8::Handle
<v8::Number
> index
= v8::Number::New(isolate
, i
);
310 v8::Local
<v8::Value
> value
= array
->Get(index
);
311 if (value
.IsEmpty() || !value
->IsInt32())
313 coords
.push_back(value
->Int32Value());
315 return gfx::Rect(coords
[0], coords
[1], coords
[2], coords
[3]);
318 bool RenderViewTest::SimulateElementClick(const std::string
& element_id
) {
319 gfx::Rect bounds
= GetElementBounds(element_id
);
320 if (bounds
.IsEmpty())
322 WebMouseEvent mouse_event
;
323 mouse_event
.type
= WebInputEvent::MouseDown
;
324 mouse_event
.button
= WebMouseEvent::ButtonLeft
;
325 mouse_event
.x
= bounds
.CenterPoint().x();
326 mouse_event
.y
= bounds
.CenterPoint().y();
327 mouse_event
.clickCount
= 1;
328 scoped_ptr
<IPC::Message
> input_message(
329 new InputMsg_HandleInputEvent(0, &mouse_event
, ui::LatencyInfo(), false));
330 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
331 impl
->OnMessageReceived(*input_message
);
335 void RenderViewTest::SetFocused(const blink::WebNode
& node
) {
336 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
337 impl
->focusedNodeChanged(node
);
340 void RenderViewTest::Reload(const GURL
& url
) {
341 FrameMsg_Navigate_Params params
;
342 params
.common_params
.url
= url
;
343 params
.common_params
.navigation_type
= FrameMsg_Navigate_Type::RELOAD
;
344 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
345 impl
->GetMainRenderFrame()->OnNavigate(params
);
346 FrameLoadWaiter(impl
->GetMainRenderFrame()).Wait();
349 uint32
RenderViewTest::GetNavigationIPCType() {
350 return FrameHostMsg_DidCommitProvisionalLoad::ID
;
353 void RenderViewTest::Resize(gfx::Size new_size
,
354 gfx::Rect resizer_rect
,
355 bool is_fullscreen
) {
356 ViewMsg_Resize_Params params
;
357 params
.screen_info
= blink::WebScreenInfo();
358 params
.new_size
= new_size
;
359 params
.physical_backing_size
= new_size
;
360 params
.top_controls_height
= 0.f
;
361 params
.top_controls_shrink_blink_size
= false;
362 params
.resizer_rect
= resizer_rect
;
363 params
.is_fullscreen
= is_fullscreen
;
364 scoped_ptr
<IPC::Message
> resize_message(new ViewMsg_Resize(0, params
));
365 OnMessageReceived(*resize_message
);
368 bool RenderViewTest::OnMessageReceived(const IPC::Message
& msg
) {
369 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
370 return impl
->OnMessageReceived(msg
);
373 void RenderViewTest::DidNavigateWithinPage(blink::WebLocalFrame
* frame
,
374 bool is_new_navigation
) {
375 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
376 blink::WebHistoryItem item
;
378 impl
->GetMainRenderFrame()->didNavigateWithinPage(
381 is_new_navigation
? blink::WebStandardCommit
382 : blink::WebHistoryInertCommit
);
385 void RenderViewTest::SendContentStateImmediately() {
386 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
387 impl
->set_send_content_state_immediately(true);
390 blink::WebWidget
* RenderViewTest::GetWebWidget() {
391 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
392 return impl
->webwidget();
396 ContentClient
* RenderViewTest::CreateContentClient() {
397 return new TestContentClient
;
400 ContentBrowserClient
* RenderViewTest::CreateContentBrowserClient() {
401 return new ContentBrowserClient
;
404 ContentRendererClient
* RenderViewTest::CreateContentRendererClient() {
405 return new ContentRendererClient
;
408 scoped_ptr
<ViewMsg_Resize_Params
> RenderViewTest::InitialSizeParams() {
409 return make_scoped_ptr(new ViewMsg_Resize_Params());
412 void RenderViewTest::GoToOffset(int offset
, const PageState
& state
) {
413 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
415 int history_list_length
= impl
->historyBackListCount() +
416 impl
->historyForwardListCount() + 1;
417 int pending_offset
= offset
+ impl
->history_list_offset_
;
419 FrameMsg_Navigate_Params navigate_params
;
420 navigate_params
.common_params
.navigation_type
=
421 FrameMsg_Navigate_Type::NORMAL
;
422 navigate_params
.common_params
.transition
= ui::PAGE_TRANSITION_FORWARD_BACK
;
423 navigate_params
.current_history_list_length
= history_list_length
;
424 navigate_params
.current_history_list_offset
= impl
->history_list_offset_
;
425 navigate_params
.pending_history_list_offset
= pending_offset
;
426 navigate_params
.page_id
= impl
->page_id_
+ offset
;
427 navigate_params
.commit_params
.page_state
= state
;
428 navigate_params
.request_time
= base::Time::Now();
430 FrameMsg_Navigate
navigate_message(impl
->GetMainRenderFrame()->GetRoutingID(),
432 impl
->GetMainRenderFrame()->OnMessageReceived(navigate_message
);
434 // The load actually happens asynchronously, so we pump messages to process
435 // the pending continuation.
436 FrameLoadWaiter(view_
->GetMainRenderFrame()).Wait();
439 } // namespace content