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/fake_compositor_dependencies.h"
26 #include "content/test/mock_render_process.h"
27 #include "content/test/test_content_client.h"
28 #include "third_party/WebKit/public/platform/WebScreenInfo.h"
29 #include "third_party/WebKit/public/platform/WebURLRequest.h"
30 #include "third_party/WebKit/public/web/WebHistoryItem.h"
31 #include "third_party/WebKit/public/web/WebInputEvent.h"
32 #include "third_party/WebKit/public/web/WebKit.h"
33 #include "third_party/WebKit/public/web/WebLocalFrame.h"
34 #include "third_party/WebKit/public/web/WebScriptSource.h"
35 #include "third_party/WebKit/public/web/WebView.h"
36 #include "ui/base/resource/resource_bundle.h"
37 #include "v8/include/v8.h"
39 #if defined(OS_MACOSX)
40 #include "base/mac/scoped_nsautorelease_pool.h"
43 using blink::WebGestureEvent
;
44 using blink::WebInputEvent
;
45 using blink::WebLocalFrame
;
46 using blink::WebMouseEvent
;
47 using blink::WebScriptSource
;
48 using blink::WebString
;
49 using blink::WebURLRequest
;
52 const int32 kOpenerId
= -2;
53 const int32 kRouteId
= 5;
54 const int32 kMainFrameRouteId
= 6;
55 const int32 kNewWindowRouteId
= 7;
56 const int32 kNewFrameRouteId
= 10;
57 const int32 kSurfaceId
= 42;
63 class RendererBlinkPlatformImplNoSandboxImpl
64 : public RendererBlinkPlatformImpl
{
66 RendererBlinkPlatformImplNoSandboxImpl(RendererScheduler
* scheduler
)
67 : RendererBlinkPlatformImpl(scheduler
) {}
69 virtual blink::WebSandboxSupport
* sandboxSupport() {
74 RenderViewTest::RendererBlinkPlatformImplNoSandbox::
75 RendererBlinkPlatformImplNoSandbox() {
76 renderer_scheduler_
= RendererScheduler::Create();
77 blink_platform_impl_
.reset(
78 new RendererBlinkPlatformImplNoSandboxImpl(renderer_scheduler_
.get()));
81 RenderViewTest::RendererBlinkPlatformImplNoSandbox::
82 ~RendererBlinkPlatformImplNoSandbox() {
85 blink::Platform
* RenderViewTest::RendererBlinkPlatformImplNoSandbox::Get() {
86 return blink_platform_impl_
.get();
89 RenderViewTest::RenderViewTest()
93 RenderViewTest::~RenderViewTest() {
96 void RenderViewTest::ProcessPendingMessages() {
97 msg_loop_
.PostTask(FROM_HERE
, base::MessageLoop::QuitClosure());
101 WebLocalFrame
* RenderViewTest::GetMainFrame() {
102 return view_
->GetWebView()->mainFrame()->toWebLocalFrame();
105 void RenderViewTest::ExecuteJavaScript(const char* js
) {
106 GetMainFrame()->executeScript(WebScriptSource(WebString::fromUTF8(js
)));
109 bool RenderViewTest::ExecuteJavaScriptAndReturnIntValue(
110 const base::string16
& script
,
112 v8::HandleScope
handle_scope(v8::Isolate::GetCurrent());
113 v8::Handle
<v8::Value
> result
=
114 GetMainFrame()->executeScriptAndReturnValue(WebScriptSource(script
));
115 if (result
.IsEmpty() || !result
->IsInt32())
119 *int_result
= result
->Int32Value();
124 void RenderViewTest::LoadHTML(const char* html
) {
125 std::string url_str
= "data:text/html;charset=utf-8,";
126 url_str
.append(html
);
128 GetMainFrame()->loadRequest(WebURLRequest(url
));
129 // The load actually happens asynchronously, so we pump messages to process
130 // the pending continuation.
131 FrameLoadWaiter(view_
->GetMainRenderFrame()).Wait();
134 PageState
RenderViewTest::GetCurrentPageState() {
135 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
136 return HistoryEntryToPageState(impl
->history_controller()->GetCurrentEntry());
139 void RenderViewTest::GoBack(const PageState
& state
) {
140 GoToOffset(-1, state
);
143 void RenderViewTest::GoForward(const PageState
& state
) {
144 GoToOffset(1, state
);
147 void RenderViewTest::SetUp() {
148 content_client_
.reset(CreateContentClient());
149 content_browser_client_
.reset(CreateContentBrowserClient());
150 content_renderer_client_
.reset(CreateContentRendererClient());
151 SetContentClient(content_client_
.get());
152 SetBrowserClientForTesting(content_browser_client_
.get());
153 SetRendererClientForTesting(content_renderer_client_
.get());
155 // Subclasses can set render_thread_ with their own implementation before
156 // calling RenderViewTest::SetUp().
158 render_thread_
.reset(new MockRenderThread());
159 render_thread_
->set_routing_id(kRouteId
);
160 render_thread_
->set_surface_id(kSurfaceId
);
161 render_thread_
->set_new_window_routing_id(kNewWindowRouteId
);
162 render_thread_
->set_new_frame_routing_id(kNewFrameRouteId
);
164 #if defined(OS_MACOSX)
165 autorelease_pool_
.reset(new base::mac::ScopedNSAutoreleasePool());
167 command_line_
.reset(new base::CommandLine(base::CommandLine::NO_PROGRAM
));
168 params_
.reset(new MainFunctionParams(*command_line_
));
169 platform_
.reset(new RendererMainPlatformDelegate(*params_
));
170 platform_
->PlatformInitialize();
172 // Setting flags and really doing anything with WebKit is fairly fragile and
173 // hacky, but this is the world we live in...
174 std::string
flags("--expose-gc");
175 v8::V8::SetFlagsFromString(flags
.c_str(), static_cast<int>(flags
.size()));
176 blink::initialize(blink_platform_impl_
.Get());
178 // Ensure that we register any necessary schemes when initializing WebKit,
179 // since we are using a MockRenderThread.
180 RenderThreadImpl::RegisterSchemes();
182 // This check is needed because when run under content_browsertests,
183 // ResourceBundle isn't initialized (since we have to use a diferent test
184 // suite implementation than for content_unittests). For browser_tests, this
185 // is already initialized.
186 if (!ui::ResourceBundle::HasSharedInstance())
187 ui::ResourceBundle::InitSharedInstanceWithLocale(
188 "en-US", NULL
, ui::ResourceBundle::DO_NOT_LOAD_COMMON_RESOURCES
);
190 compositor_deps_
.reset(new FakeCompositorDependencies
);
191 mock_process_
.reset(new MockRenderProcess
);
193 ViewMsg_New_Params view_params
;
194 view_params
.opener_route_id
= kOpenerId
;
195 view_params
.window_was_created_with_opener
= false;
196 view_params
.renderer_preferences
= RendererPreferences();
197 view_params
.web_preferences
= WebPreferences();
198 view_params
.view_id
= kRouteId
;
199 view_params
.main_frame_routing_id
= kMainFrameRouteId
;
200 view_params
.surface_id
= kSurfaceId
;
201 view_params
.session_storage_namespace_id
= kInvalidSessionStorageNamespaceId
;
202 view_params
.frame_name
= base::string16();
203 view_params
.swapped_out
= false;
204 view_params
.replicated_frame_state
= FrameReplicationState();
205 view_params
.proxy_routing_id
= MSG_ROUTING_NONE
;
206 view_params
.hidden
= false;
207 view_params
.never_visible
= false;
208 view_params
.next_page_id
= 1;
209 view_params
.initial_size
= *InitialSizeParams();
210 view_params
.enable_auto_resize
= false;
211 view_params
.min_size
= gfx::Size();
212 view_params
.max_size
= gfx::Size();
214 // This needs to pass the mock render thread to the view.
215 RenderViewImpl
* view
=
216 RenderViewImpl::Create(view_params
, compositor_deps_
.get(), false);
221 void RenderViewTest::TearDown() {
222 // Try very hard to collect garbage before shutting down.
223 // "5" was chosen following http://crbug.com/46571#c9
224 const int kGCIterations
= 5;
225 for (int i
= 0; i
< kGCIterations
; i
++)
226 GetMainFrame()->collectGarbage();
228 // Run the loop so the release task from the renderwidget executes.
229 ProcessPendingMessages();
231 for (int i
= 0; i
< kGCIterations
; i
++)
232 GetMainFrame()->collectGarbage();
234 render_thread_
->SendCloseMessage();
236 mock_process_
.reset();
238 // After telling the view to close and resetting mock_process_ we may get
239 // some new tasks which need to be processed before shutting down WebKit
240 // (http://crbug.com/21508).
241 base::RunLoop().RunUntilIdle();
243 #if defined(OS_MACOSX)
244 // Needs to run before blink::shutdown().
245 autorelease_pool_
.reset(NULL
);
250 platform_
->PlatformUninitialize();
253 command_line_
.reset();
256 void RenderViewTest::SendNativeKeyEvent(
257 const NativeWebKeyboardEvent
& key_event
) {
258 SendWebKeyboardEvent(key_event
);
261 void RenderViewTest::SendWebKeyboardEvent(
262 const blink::WebKeyboardEvent
& key_event
) {
263 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
264 impl
->OnMessageReceived(
265 InputMsg_HandleInputEvent(0, &key_event
, ui::LatencyInfo(), false));
268 void RenderViewTest::SendWebMouseEvent(
269 const blink::WebMouseEvent
& mouse_event
) {
270 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
271 impl
->OnMessageReceived(
272 InputMsg_HandleInputEvent(0, &mouse_event
, ui::LatencyInfo(), false));
275 const char* const kGetCoordinatesScript
=
277 " function GetCoordinates(elem) {"
280 " var coordinates = [ elem.offsetLeft, elem.offsetTop];"
281 " var parent_coordinates = GetCoordinates(elem.offsetParent);"
282 " coordinates[0] += parent_coordinates[0];"
283 " coordinates[1] += parent_coordinates[1];"
284 " return [ Math.round(coordinates[0]),"
285 " Math.round(coordinates[1])];"
287 " var elem = document.getElementById('$1');"
290 " var bounds = GetCoordinates(elem);"
291 " bounds[2] = Math.round(elem.offsetWidth);"
292 " bounds[3] = Math.round(elem.offsetHeight);"
295 gfx::Rect
RenderViewTest::GetElementBounds(const std::string
& element_id
) {
296 std::vector
<std::string
> params
;
297 params
.push_back(element_id
);
299 ReplaceStringPlaceholders(kGetCoordinatesScript
, params
, NULL
);
301 v8::Isolate
* isolate
= v8::Isolate::GetCurrent();
302 v8::HandleScope
handle_scope(isolate
);
303 v8::Handle
<v8::Value
> value
= GetMainFrame()->executeScriptAndReturnValue(
304 WebScriptSource(WebString::fromUTF8(script
)));
305 if (value
.IsEmpty() || !value
->IsArray())
308 v8::Handle
<v8::Array
> array
= value
.As
<v8::Array
>();
309 if (array
->Length() != 4)
311 std::vector
<int> coords
;
312 for (int i
= 0; i
< 4; ++i
) {
313 v8::Handle
<v8::Number
> index
= v8::Number::New(isolate
, i
);
314 v8::Local
<v8::Value
> value
= array
->Get(index
);
315 if (value
.IsEmpty() || !value
->IsInt32())
317 coords
.push_back(value
->Int32Value());
319 return gfx::Rect(coords
[0], coords
[1], coords
[2], coords
[3]);
322 bool RenderViewTest::SimulateElementClick(const std::string
& element_id
) {
323 gfx::Rect bounds
= GetElementBounds(element_id
);
324 if (bounds
.IsEmpty())
326 SimulatePointClick(bounds
.CenterPoint());
330 void RenderViewTest::SimulatePointClick(const gfx::Point
& point
) {
331 WebMouseEvent mouse_event
;
332 mouse_event
.type
= WebInputEvent::MouseDown
;
333 mouse_event
.button
= WebMouseEvent::ButtonLeft
;
334 mouse_event
.x
= point
.x();
335 mouse_event
.y
= point
.y();
336 mouse_event
.clickCount
= 1;
337 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
338 impl
->OnMessageReceived(
339 InputMsg_HandleInputEvent(0, &mouse_event
, ui::LatencyInfo(), false));
340 mouse_event
.type
= WebInputEvent::MouseUp
;
341 impl
->OnMessageReceived(
342 InputMsg_HandleInputEvent(0, &mouse_event
, ui::LatencyInfo(), false));
345 void RenderViewTest::SimulateRectTap(const gfx::Rect
& rect
) {
346 WebGestureEvent gesture_event
;
347 gesture_event
.x
= rect
.CenterPoint().x();
348 gesture_event
.y
= rect
.CenterPoint().y();
349 gesture_event
.data
.tap
.tapCount
= 1;
350 gesture_event
.data
.tap
.width
= rect
.width();
351 gesture_event
.data
.tap
.height
= rect
.height();
352 gesture_event
.type
= WebInputEvent::GestureTap
;
353 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
354 impl
->OnMessageReceived(
355 InputMsg_HandleInputEvent(0, &gesture_event
, ui::LatencyInfo(), false));
356 impl
->FocusChangeComplete();
359 void RenderViewTest::SetFocused(const blink::WebNode
& node
) {
360 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
361 impl
->focusedNodeChanged(blink::WebNode(), node
);
364 void RenderViewTest::Reload(const GURL
& url
) {
365 CommonNavigationParams
common_params(
366 url
, Referrer(), ui::PAGE_TRANSITION_LINK
, FrameMsg_Navigate_Type::RELOAD
,
367 true, base::TimeTicks(), FrameMsg_UILoadMetricsReportType::NO_REPORT
,
369 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
370 impl
->GetMainRenderFrame()->OnNavigate(common_params
, StartNavigationParams(),
371 RequestNavigationParams());
372 FrameLoadWaiter(impl
->GetMainRenderFrame()).Wait();
375 uint32
RenderViewTest::GetNavigationIPCType() {
376 return FrameHostMsg_DidCommitProvisionalLoad::ID
;
379 void RenderViewTest::Resize(gfx::Size new_size
,
380 gfx::Rect resizer_rect
,
381 bool is_fullscreen
) {
382 ViewMsg_Resize_Params params
;
383 params
.screen_info
= blink::WebScreenInfo();
384 params
.new_size
= new_size
;
385 params
.physical_backing_size
= new_size
;
386 params
.top_controls_height
= 0.f
;
387 params
.top_controls_shrink_blink_size
= false;
388 params
.resizer_rect
= resizer_rect
;
389 params
.is_fullscreen
= is_fullscreen
;
390 scoped_ptr
<IPC::Message
> resize_message(new ViewMsg_Resize(0, params
));
391 OnMessageReceived(*resize_message
);
394 bool RenderViewTest::OnMessageReceived(const IPC::Message
& msg
) {
395 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
396 return impl
->OnMessageReceived(msg
);
399 void RenderViewTest::DidNavigateWithinPage(blink::WebLocalFrame
* frame
,
400 bool is_new_navigation
) {
401 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
402 blink::WebHistoryItem item
;
404 impl
->GetMainRenderFrame()->didNavigateWithinPage(
407 is_new_navigation
? blink::WebStandardCommit
408 : blink::WebHistoryInertCommit
);
411 void RenderViewTest::SendContentStateImmediately() {
412 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
413 impl
->set_send_content_state_immediately(true);
416 blink::WebWidget
* RenderViewTest::GetWebWidget() {
417 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
418 return impl
->webwidget();
422 ContentClient
* RenderViewTest::CreateContentClient() {
423 return new TestContentClient
;
426 ContentBrowserClient
* RenderViewTest::CreateContentBrowserClient() {
427 return new ContentBrowserClient
;
430 ContentRendererClient
* RenderViewTest::CreateContentRendererClient() {
431 return new ContentRendererClient
;
434 scoped_ptr
<ViewMsg_Resize_Params
> RenderViewTest::InitialSizeParams() {
435 return make_scoped_ptr(new ViewMsg_Resize_Params());
438 void RenderViewTest::GoToOffset(int offset
, const PageState
& state
) {
439 RenderViewImpl
* impl
= static_cast<RenderViewImpl
*>(view_
);
441 int history_list_length
= impl
->historyBackListCount() +
442 impl
->historyForwardListCount() + 1;
443 int pending_offset
= offset
+ impl
->history_list_offset_
;
445 CommonNavigationParams
common_params(
446 GURL(), Referrer(), ui::PAGE_TRANSITION_FORWARD_BACK
,
447 FrameMsg_Navigate_Type::NORMAL
, true, base::TimeTicks(),
448 FrameMsg_UILoadMetricsReportType::NO_REPORT
, GURL(), GURL());
449 RequestNavigationParams request_params
;
450 request_params
.page_state
= state
;
451 request_params
.page_id
= impl
->page_id_
+ offset
;
452 request_params
.pending_history_list_offset
= pending_offset
;
453 request_params
.current_history_list_offset
= impl
->history_list_offset_
;
454 request_params
.current_history_list_length
= history_list_length
;
456 impl
->GetMainRenderFrame()->OnNavigate(common_params
, StartNavigationParams(),
459 // The load actually happens asynchronously, so we pump messages to process
460 // the pending continuation.
461 FrameLoadWaiter(view_
->GetMainRenderFrame()).Wait();
464 } // namespace content