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/input_messages.h"
10 #include "content/common/view_messages.h"
11 #include "content/public/browser/native_web_keyboard_event.h"
12 #include "content/public/common/renderer_preferences.h"
13 #include "content/public/renderer/history_item_serialization.h"
14 #include "content/renderer/render_thread_impl.h"
15 #include "content/renderer/render_view_impl.h"
16 #include "content/renderer/renderer_main_platform_delegate.h"
17 #include "content/renderer/renderer_webkitplatformsupport_impl.h"
18 #include "content/test/mock_render_process.h"
19 #include "third_party/WebKit/public/platform/WebScreenInfo.h"
20 #include "third_party/WebKit/public/platform/WebURLRequest.h"
21 #include "third_party/WebKit/public/web/WebFrame.h"
22 #include "third_party/WebKit/public/web/WebHistoryItem.h"
23 #include "third_party/WebKit/public/web/WebInputEvent.h"
24 #include "third_party/WebKit/public/web/WebKit.h"
25 #include "third_party/WebKit/public/web/WebScriptController.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 "webkit/glue/webkit_glue.h"
31 using blink::WebFrame;
32 using blink::WebInputEvent;
33 using blink::WebMouseEvent;
34 using blink::WebScriptController;
35 using blink::WebScriptSource;
36 using blink::WebString;
37 using blink::WebURLRequest;
40 const int32 kOpenerId = -2;
41 const int32 kRouteId = 5;
42 const int32 kMainFrameRouteId = 6;
43 const int32 kNewWindowRouteId = 7;
44 const int32 kNewFrameRouteId = 10;
45 const int32 kSurfaceId = 42;
51 class RendererWebKitPlatformSupportImplNoSandboxImpl
52 : public RendererWebKitPlatformSupportImpl {
54 virtual blink::WebSandboxSupport* sandboxSupport() {
59 RenderViewTest::RendererWebKitPlatformSupportImplNoSandbox::
60 RendererWebKitPlatformSupportImplNoSandbox() {
61 webkit_platform_support_.reset(
62 new RendererWebKitPlatformSupportImplNoSandboxImpl());
65 RenderViewTest::RendererWebKitPlatformSupportImplNoSandbox::
66 ~RendererWebKitPlatformSupportImplNoSandbox() {
70 RenderViewTest::RendererWebKitPlatformSupportImplNoSandbox::Get() {
71 return webkit_platform_support_.get();
74 RenderViewTest::RenderViewTest()
78 RenderViewTest::~RenderViewTest() {
81 void RenderViewTest::ProcessPendingMessages() {
82 msg_loop_.PostTask(FROM_HERE, base::MessageLoop::QuitClosure());
86 WebFrame* RenderViewTest::GetMainFrame() {
87 return view_->GetWebView()->mainFrame();
90 void RenderViewTest::ExecuteJavaScript(const char* js) {
91 GetMainFrame()->executeScript(WebScriptSource(WebString::fromUTF8(js)));
94 bool RenderViewTest::ExecuteJavaScriptAndReturnIntValue(
95 const base::string16& script,
97 v8::HandleScope handle_scope(v8::Isolate::GetCurrent());
98 v8::Handle<v8::Value> result =
99 GetMainFrame()->executeScriptAndReturnValue(WebScriptSource(script));
100 if (result.IsEmpty() || !result->IsInt32())
104 *int_result = result->Int32Value();
109 void RenderViewTest::LoadHTML(const char* html) {
110 std::string url_str = "data:text/html;charset=utf-8,";
111 url_str.append(html);
114 GetMainFrame()->loadRequest(WebURLRequest(url));
116 // The load actually happens asynchronously, so we pump messages to process
117 // the pending continuation.
118 ProcessPendingMessages();
121 void RenderViewTest::GoBack(const blink::WebHistoryItem& item) {
122 GoToOffset(-1, item);
125 void RenderViewTest::GoForward(const blink::WebHistoryItem& item) {
129 void RenderViewTest::SetUp() {
130 // Subclasses can set the ContentClient's renderer before calling
131 // RenderViewTest::SetUp().
132 ContentRendererClient* old_client =
133 SetRendererClientForTesting(&content_renderer_client_);
135 SetRendererClientForTesting(old_client);
137 // Subclasses can set render_thread_ with their own implementation before
138 // calling RenderViewTest::SetUp().
140 render_thread_.reset(new MockRenderThread());
141 render_thread_->set_routing_id(kRouteId);
142 render_thread_->set_surface_id(kSurfaceId);
143 render_thread_->set_new_window_routing_id(kNewWindowRouteId);
144 render_thread_->set_new_frame_routing_id(kNewFrameRouteId);
146 command_line_.reset(new CommandLine(CommandLine::NO_PROGRAM));
147 params_.reset(new MainFunctionParams(*command_line_));
148 platform_.reset(new RendererMainPlatformDelegate(*params_));
149 platform_->PlatformInitialize();
151 // Setting flags and really doing anything with WebKit is fairly fragile and
152 // hacky, but this is the world we live in...
153 webkit_glue::SetJavaScriptFlags(" --expose-gc");
154 blink::initialize(webkit_platform_support_.Get());
156 // Ensure that we register any necessary schemes when initializing WebKit,
157 // since we are using a MockRenderThread.
158 RenderThreadImpl::RegisterSchemes();
160 // This check is needed because when run under content_browsertests,
161 // ResourceBundle isn't initialized (since we have to use a diferent test
162 // suite implementation than for content_unittests). For browser_tests, this
163 // is already initialized.
164 if (!ResourceBundle::HasSharedInstance())
165 ResourceBundle::InitSharedInstanceWithLocale("en-US", NULL);
167 mock_process_.reset(new MockRenderProcess);
169 // This needs to pass the mock render thread to the view.
170 RenderViewImpl* view = RenderViewImpl::Create(
172 RendererPreferences(),
177 kInvalidSessionStorageNamespaceId,
179 false, // is_renderer_created
180 false, // swapped_out
183 blink::WebScreenInfo(),
184 AccessibilityModeOff,
190 void RenderViewTest::TearDown() {
191 // Try very hard to collect garbage before shutting down.
192 // "5" was chosen following http://crbug.com/46571#c9
193 const int kGCIterations = 5;
194 for (int i = 0; i < kGCIterations; i++)
195 GetMainFrame()->collectGarbage();
197 // Run the loop so the release task from the renderwidget executes.
198 ProcessPendingMessages();
200 for (int i = 0; i < kGCIterations; i++)
201 GetMainFrame()->collectGarbage();
203 render_thread_->SendCloseMessage();
205 mock_process_.reset();
207 // After telling the view to close and resetting mock_process_ we may get
208 // some new tasks which need to be processed before shutting down WebKit
209 // (http://crbug.com/21508).
210 base::RunLoop().RunUntilIdle();
214 platform_->PlatformUninitialize();
217 command_line_.reset();
220 void RenderViewTest::SendNativeKeyEvent(
221 const NativeWebKeyboardEvent& key_event) {
222 SendWebKeyboardEvent(key_event);
225 void RenderViewTest::SendWebKeyboardEvent(
226 const blink::WebKeyboardEvent& key_event) {
227 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
228 impl->OnMessageReceived(
229 InputMsg_HandleInputEvent(0, &key_event, ui::LatencyInfo(), false));
232 void RenderViewTest::SendWebMouseEvent(
233 const blink::WebMouseEvent& mouse_event) {
234 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
235 impl->OnMessageReceived(
236 InputMsg_HandleInputEvent(0, &mouse_event, ui::LatencyInfo(), false));
239 const char* const kGetCoordinatesScript =
241 " function GetCoordinates(elem) {"
244 " var coordinates = [ elem.offsetLeft, elem.offsetTop];"
245 " var parent_coordinates = GetCoordinates(elem.offsetParent);"
246 " coordinates[0] += parent_coordinates[0];"
247 " coordinates[1] += parent_coordinates[1];"
248 " return coordinates;"
250 " var elem = document.getElementById('$1');"
253 " var bounds = GetCoordinates(elem);"
254 " bounds[2] = elem.offsetWidth;"
255 " bounds[3] = elem.offsetHeight;"
258 gfx::Rect RenderViewTest::GetElementBounds(const std::string& element_id) {
259 std::vector<std::string> params;
260 params.push_back(element_id);
262 ReplaceStringPlaceholders(kGetCoordinatesScript, params, NULL);
264 v8::Isolate* isolate = v8::Isolate::GetCurrent();
265 v8::HandleScope handle_scope(isolate);
266 v8::Handle<v8::Value> value = GetMainFrame()->executeScriptAndReturnValue(
267 WebScriptSource(WebString::fromUTF8(script)));
268 if (value.IsEmpty() || !value->IsArray())
271 v8::Handle<v8::Array> array = value.As<v8::Array>();
272 if (array->Length() != 4)
274 std::vector<int> coords;
275 for (int i = 0; i < 4; ++i) {
276 v8::Handle<v8::Number> index = v8::Number::New(isolate, i);
277 v8::Local<v8::Value> value = array->Get(index);
278 if (value.IsEmpty() || !value->IsInt32())
280 coords.push_back(value->Int32Value());
282 return gfx::Rect(coords[0], coords[1], coords[2], coords[3]);
285 bool RenderViewTest::SimulateElementClick(const std::string& element_id) {
286 gfx::Rect bounds = GetElementBounds(element_id);
287 if (bounds.IsEmpty())
289 WebMouseEvent mouse_event;
290 mouse_event.type = WebInputEvent::MouseDown;
291 mouse_event.button = WebMouseEvent::ButtonLeft;
292 mouse_event.x = bounds.CenterPoint().x();
293 mouse_event.y = bounds.CenterPoint().y();
294 mouse_event.clickCount = 1;
295 scoped_ptr<IPC::Message> input_message(
296 new InputMsg_HandleInputEvent(0, &mouse_event, ui::LatencyInfo(), false));
297 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
298 impl->OnMessageReceived(*input_message);
302 void RenderViewTest::SetFocused(const blink::WebNode& node) {
303 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
304 impl->focusedNodeChanged(node);
307 void RenderViewTest::ClearHistory() {
308 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
310 impl->history_list_offset_ = -1;
311 impl->history_list_length_ = 0;
312 impl->history_page_ids_.clear();
315 void RenderViewTest::Reload(const GURL& url) {
316 ViewMsg_Navigate_Params params;
318 params.navigation_type = ViewMsg_Navigate_Type::RELOAD;
319 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
320 impl->OnNavigate(params);
323 uint32 RenderViewTest::GetNavigationIPCType() {
324 return ViewHostMsg_FrameNavigate::ID;
327 void RenderViewTest::Resize(gfx::Size new_size,
328 gfx::Rect resizer_rect,
329 bool is_fullscreen) {
330 ViewMsg_Resize_Params params;
331 params.screen_info = blink::WebScreenInfo();
332 params.new_size = new_size;
333 params.physical_backing_size = new_size;
334 params.overdraw_bottom_height = 0.f;
335 params.resizer_rect = resizer_rect;
336 params.is_fullscreen = is_fullscreen;
337 scoped_ptr<IPC::Message> resize_message(new ViewMsg_Resize(0, params));
338 OnMessageReceived(*resize_message);
341 bool RenderViewTest::OnMessageReceived(const IPC::Message& msg) {
342 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
343 return impl->OnMessageReceived(msg);
346 void RenderViewTest::DidNavigateWithinPage(blink::WebFrame* frame,
347 bool is_new_navigation) {
348 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
349 impl->didNavigateWithinPage(frame, is_new_navigation);
352 void RenderViewTest::SendContentStateImmediately() {
353 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
354 impl->set_send_content_state_immediately(true);
357 blink::WebWidget* RenderViewTest::GetWebWidget() {
358 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
359 return impl->webwidget();
362 void RenderViewTest::GoToOffset(int offset,
363 const blink::WebHistoryItem& history_item) {
364 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
366 int history_list_length = impl->historyBackListCount() +
367 impl->historyForwardListCount() + 1;
368 int pending_offset = offset + impl->history_list_offset();
370 ViewMsg_Navigate_Params navigate_params;
371 navigate_params.navigation_type = ViewMsg_Navigate_Type::NORMAL;
372 navigate_params.transition = PAGE_TRANSITION_FORWARD_BACK;
373 navigate_params.current_history_list_length = history_list_length;
374 navigate_params.current_history_list_offset = impl->history_list_offset();
375 navigate_params.pending_history_list_offset = pending_offset;
376 navigate_params.page_id = impl->GetPageId() + offset;
377 navigate_params.page_state = HistoryItemToPageState(history_item);
378 navigate_params.request_time = base::Time::Now();
380 ViewMsg_Navigate navigate_message(impl->GetRoutingID(), navigate_params);
381 OnMessageReceived(navigate_message);
383 // The load actually happens asynchronously, so we pump messages to process
384 // the pending continuation.
385 ProcessPendingMessages();
388 } // namespace content