ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / content / public / test / render_view_test.cc
blob9f49968b92321bb94fa634c49fb87dd6222cddfa
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"
41 #endif
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;
51 namespace {
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;
59 } // namespace
61 namespace content {
63 class RendererBlinkPlatformImplNoSandboxImpl
64 : public RendererBlinkPlatformImpl {
65 public:
66 RendererBlinkPlatformImplNoSandboxImpl(RendererScheduler* scheduler)
67 : RendererBlinkPlatformImpl(scheduler) {}
69 virtual blink::WebSandboxSupport* sandboxSupport() {
70 return NULL;
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()
90 : view_(NULL) {
93 RenderViewTest::~RenderViewTest() {
96 void RenderViewTest::ProcessPendingMessages() {
97 msg_loop_.PostTask(FROM_HERE, base::MessageLoop::QuitClosure());
98 msg_loop_.Run();
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,
111 int* int_result) {
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())
116 return false;
118 if (int_result)
119 *int_result = result->Int32Value();
121 return true;
124 void RenderViewTest::LoadHTML(const char* html) {
125 std::string url_str = "data:text/html;charset=utf-8,";
126 url_str.append(html);
127 GURL url(url_str);
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().
157 if (!render_thread_)
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());
166 #endif
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);
217 view->AddRef();
218 view_ = view;
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();
235 view_ = NULL;
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);
246 #endif
248 blink::shutdown();
250 platform_->PlatformUninitialize();
251 platform_.reset();
252 params_.reset();
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 =
276 "(function() {"
277 " function GetCoordinates(elem) {"
278 " if (!elem)"
279 " return [ 0, 0];"
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])];"
286 " };"
287 " var elem = document.getElementById('$1');"
288 " if (!elem)"
289 " return null;"
290 " var bounds = GetCoordinates(elem);"
291 " bounds[2] = Math.round(elem.offsetWidth);"
292 " bounds[3] = Math.round(elem.offsetHeight);"
293 " return bounds;"
294 "})();";
295 gfx::Rect RenderViewTest::GetElementBounds(const std::string& element_id) {
296 std::vector<std::string> params;
297 params.push_back(element_id);
298 std::string script =
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())
306 return gfx::Rect();
308 v8::Handle<v8::Array> array = value.As<v8::Array>();
309 if (array->Length() != 4)
310 return gfx::Rect();
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())
316 return gfx::Rect();
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())
325 return false;
326 SimulatePointClick(bounds.CenterPoint());
327 return true;
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 FrameMsg_Navigate_Params params;
366 params.common_params.url = url;
367 params.common_params.navigation_type = FrameMsg_Navigate_Type::RELOAD;
368 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
369 impl->GetMainRenderFrame()->OnNavigate(params);
370 FrameLoadWaiter(impl->GetMainRenderFrame()).Wait();
373 uint32 RenderViewTest::GetNavigationIPCType() {
374 return FrameHostMsg_DidCommitProvisionalLoad::ID;
377 void RenderViewTest::Resize(gfx::Size new_size,
378 gfx::Rect resizer_rect,
379 bool is_fullscreen) {
380 ViewMsg_Resize_Params params;
381 params.screen_info = blink::WebScreenInfo();
382 params.new_size = new_size;
383 params.physical_backing_size = new_size;
384 params.top_controls_height = 0.f;
385 params.top_controls_shrink_blink_size = false;
386 params.resizer_rect = resizer_rect;
387 params.is_fullscreen = is_fullscreen;
388 scoped_ptr<IPC::Message> resize_message(new ViewMsg_Resize(0, params));
389 OnMessageReceived(*resize_message);
392 bool RenderViewTest::OnMessageReceived(const IPC::Message& msg) {
393 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
394 return impl->OnMessageReceived(msg);
397 void RenderViewTest::DidNavigateWithinPage(blink::WebLocalFrame* frame,
398 bool is_new_navigation) {
399 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
400 blink::WebHistoryItem item;
401 item.initialize();
402 impl->GetMainRenderFrame()->didNavigateWithinPage(
403 frame,
404 item,
405 is_new_navigation ? blink::WebStandardCommit
406 : blink::WebHistoryInertCommit);
409 void RenderViewTest::SendContentStateImmediately() {
410 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
411 impl->set_send_content_state_immediately(true);
414 blink::WebWidget* RenderViewTest::GetWebWidget() {
415 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
416 return impl->webwidget();
420 ContentClient* RenderViewTest::CreateContentClient() {
421 return new TestContentClient;
424 ContentBrowserClient* RenderViewTest::CreateContentBrowserClient() {
425 return new ContentBrowserClient;
428 ContentRendererClient* RenderViewTest::CreateContentRendererClient() {
429 return new ContentRendererClient;
432 scoped_ptr<ViewMsg_Resize_Params> RenderViewTest::InitialSizeParams() {
433 return make_scoped_ptr(new ViewMsg_Resize_Params());
436 void RenderViewTest::GoToOffset(int offset, const PageState& state) {
437 RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
439 int history_list_length = impl->historyBackListCount() +
440 impl->historyForwardListCount() + 1;
441 int pending_offset = offset + impl->history_list_offset_;
443 FrameMsg_Navigate_Params navigate_params;
444 navigate_params.common_params.navigation_type =
445 FrameMsg_Navigate_Type::NORMAL;
446 navigate_params.common_params.transition = ui::PAGE_TRANSITION_FORWARD_BACK;
447 navigate_params.current_history_list_length = history_list_length;
448 navigate_params.current_history_list_offset = impl->history_list_offset_;
449 navigate_params.pending_history_list_offset = pending_offset;
450 navigate_params.page_id = impl->page_id_ + offset;
451 navigate_params.commit_params.page_state = state;
452 navigate_params.request_time = base::Time::Now();
454 FrameMsg_Navigate navigate_message(impl->GetMainRenderFrame()->GetRoutingID(),
455 navigate_params);
456 impl->GetMainRenderFrame()->OnMessageReceived(navigate_message);
458 // The load actually happens asynchronously, so we pump messages to process
459 // the pending continuation.
460 FrameLoadWaiter(view_->GetMainRenderFrame()).Wait();
463 } // namespace content