Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / content / public / test / render_view_test.cc
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.
4
5 #include "content/public/test/render_view_test.h"
6
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"
30
31 #if defined(OS_MACOSX)
32 #include "base/mac/scoped_nsautorelease_pool.h"
33 #endif
34
35 using blink::WebFrame;
36 using blink::WebInputEvent;
37 using blink::WebMouseEvent;
38 using blink::WebScriptSource;
39 using blink::WebString;
40 using blink::WebURLRequest;
41
42 namespace {
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;
49
50 }  // namespace
51
52 namespace content {
53
54 class RendererWebKitPlatformSupportImplNoSandboxImpl
55     : public RendererWebKitPlatformSupportImpl {
56  public:
57   virtual blink::WebSandboxSupport* sandboxSupport() {
58     return NULL;
59   }
60 };
61
62 RenderViewTest::RendererWebKitPlatformSupportImplNoSandbox::
63     RendererWebKitPlatformSupportImplNoSandbox() {
64   webkit_platform_support_.reset(
65       new RendererWebKitPlatformSupportImplNoSandboxImpl());
66 }
67
68 RenderViewTest::RendererWebKitPlatformSupportImplNoSandbox::
69     ~RendererWebKitPlatformSupportImplNoSandbox() {
70 }
71
72 blink::Platform*
73     RenderViewTest::RendererWebKitPlatformSupportImplNoSandbox::Get() {
74   return webkit_platform_support_.get();
75 }
76
77 RenderViewTest::RenderViewTest()
78     : view_(NULL) {
79 }
80
81 RenderViewTest::~RenderViewTest() {
82 }
83
84 void RenderViewTest::ProcessPendingMessages() {
85   msg_loop_.PostTask(FROM_HERE, base::MessageLoop::QuitClosure());
86   msg_loop_.Run();
87 }
88
89 WebFrame* RenderViewTest::GetMainFrame() {
90   return view_->GetWebView()->mainFrame();
91 }
92
93 void RenderViewTest::ExecuteJavaScript(const char* js) {
94   GetMainFrame()->executeScript(WebScriptSource(WebString::fromUTF8(js)));
95 }
96
97 bool RenderViewTest::ExecuteJavaScriptAndReturnIntValue(
98     const base::string16& script,
99     int* int_result) {
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())
104     return false;
105
106   if (int_result)
107     *int_result = result->Int32Value();
108
109   return true;
110 }
111
112 void RenderViewTest::LoadHTML(const char* html) {
113   std::string url_str = "data:text/html;charset=utf-8,";
114   url_str.append(html);
115   GURL url(url_str);
116
117   GetMainFrame()->loadRequest(WebURLRequest(url));
118
119   // The load actually happens asynchronously, so we pump messages to process
120   // the pending continuation.
121   ProcessPendingMessages();
122 }
123
124 void RenderViewTest::GoBack(const blink::WebHistoryItem& item) {
125   GoToOffset(-1, item);
126 }
127
128 void RenderViewTest::GoForward(const blink::WebHistoryItem& item) {
129   GoToOffset(1, item);
130 }
131
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_);
137   if (old_client)
138     SetRendererClientForTesting(old_client);
139
140   // Subclasses can set render_thread_ with their own implementation before
141   // calling RenderViewTest::SetUp().
142   if (!render_thread_)
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);
148
149 #if defined(OS_MACOSX)
150   autorelease_pool_.reset(new base::mac::ScopedNSAutoreleasePool());
151 #endif
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();
156
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());
162
163   // Ensure that we register any necessary schemes when initializing WebKit,
164   // since we are using a MockRenderThread.
165   RenderThreadImpl::RegisterSchemes();
166
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);
173
174   mock_process_.reset(new MockRenderProcess);
175
176   // This needs to pass the mock render thread to the view.
177   RenderViewImpl* view = RenderViewImpl::Create(
178       kOpenerId,
179       RendererPreferences(),
180       WebPreferences(),
181       kRouteId,
182       kMainFrameRouteId,
183       kSurfaceId,
184       kInvalidSessionStorageNamespaceId,
185       base::string16(),
186       false, // is_renderer_created
187       false, // swapped_out
188       false, // hidden
189       1, // next_page_id
190       blink::WebScreenInfo(),
191       AccessibilityModeOff,
192       true);
193   view->AddRef();
194   view_ = view;
195 }
196
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();
203
204   // Run the loop so the release task from the renderwidget executes.
205   ProcessPendingMessages();
206
207   for (int i = 0; i < kGCIterations; i++)
208     GetMainFrame()->collectGarbage();
209
210   render_thread_->SendCloseMessage();
211   view_ = NULL;
212   mock_process_.reset();
213
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();
218
219 #if defined(OS_MACOSX)
220   // Needs to run before blink::shutdown().
221   autorelease_pool_.reset(NULL);
222 #endif
223
224   blink::shutdown();
225
226   platform_->PlatformUninitialize();
227   platform_.reset();
228   params_.reset();
229   command_line_.reset();
230 }
231
232 void RenderViewTest::SendNativeKeyEvent(
233     const NativeWebKeyboardEvent& key_event) {
234   SendWebKeyboardEvent(key_event);
235 }
236
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));
242 }
243
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));
249 }
250
251 const char* const kGetCoordinatesScript =
252     "(function() {"
253     "  function GetCoordinates(elem) {"
254     "    if (!elem)"
255     "      return [ 0, 0];"
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;"
261     "  };"
262     "  var elem = document.getElementById('$1');"
263     "  if (!elem)"
264     "    return null;"
265     "  var bounds = GetCoordinates(elem);"
266     "  bounds[2] = elem.offsetWidth;"
267     "  bounds[3] = elem.offsetHeight;"
268     "  return bounds;"
269     "})();";
270 gfx::Rect RenderViewTest::GetElementBounds(const std::string& element_id) {
271   std::vector<std::string> params;
272   params.push_back(element_id);
273   std::string script =
274       ReplaceStringPlaceholders(kGetCoordinatesScript, params, NULL);
275
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())
281     return gfx::Rect();
282
283   v8::Handle<v8::Array> array = value.As<v8::Array>();
284   if (array->Length() != 4)
285     return gfx::Rect();
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())
291       return gfx::Rect();
292     coords.push_back(value->Int32Value());
293   }
294   return gfx::Rect(coords[0], coords[1], coords[2], coords[3]);
295 }
296
297 bool RenderViewTest::SimulateElementClick(const std::string& element_id) {
298   gfx::Rect bounds = GetElementBounds(element_id);
299   if (bounds.IsEmpty())
300     return false;
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);
311   return true;
312 }
313
314 void RenderViewTest::SetFocused(const blink::WebNode& node) {
315   RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
316   impl->focusedNodeChanged(node);
317 }
318
319 void RenderViewTest::ClearHistory() {
320   RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
321   impl->page_id_ = -1;
322   impl->history_list_offset_ = -1;
323   impl->history_list_length_ = 0;
324   impl->history_page_ids_.clear();
325 }
326
327 void RenderViewTest::Reload(const GURL& url) {
328   FrameMsg_Navigate_Params params;
329   params.url = url;
330   params.navigation_type = FrameMsg_Navigate_Type::RELOAD;
331   RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
332   impl->main_render_frame()->OnNavigate(params);
333 }
334
335 uint32 RenderViewTest::GetNavigationIPCType() {
336   return FrameHostMsg_DidCommitProvisionalLoad::ID;
337 }
338
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);
351 }
352
353 bool RenderViewTest::OnMessageReceived(const IPC::Message& msg) {
354   RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
355   return impl->OnMessageReceived(msg);
356 }
357
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);
362 }
363
364 void RenderViewTest::SendContentStateImmediately() {
365   RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
366   impl->set_send_content_state_immediately(true);
367 }
368
369 blink::WebWidget* RenderViewTest::GetWebWidget() {
370   RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
371   return impl->webwidget();
372 }
373
374 void RenderViewTest::GoToOffset(int offset,
375                                 const blink::WebHistoryItem& history_item) {
376   RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
377
378   int history_list_length = impl->historyBackListCount() +
379                             impl->historyForwardListCount() + 1;
380   int pending_offset = offset + impl->history_list_offset();
381
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();
391
392   FrameMsg_Navigate navigate_message(impl->main_render_frame()->GetRoutingID(),
393                                      navigate_params);
394   impl->main_render_frame()->OnMessageReceived(navigate_message);
395
396   // The load actually happens asynchronously, so we pump messages to process
397   // the pending continuation.
398   ProcessPendingMessages();
399 }
400
401 }  // namespace content