Upstream version 5.34.92.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/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"
30
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;
38
39 namespace {
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;
46
47 }  // namespace
48
49 namespace content {
50
51 class RendererWebKitPlatformSupportImplNoSandboxImpl
52     : public RendererWebKitPlatformSupportImpl {
53  public:
54   virtual blink::WebSandboxSupport* sandboxSupport() {
55     return NULL;
56   }
57 };
58
59 RenderViewTest::RendererWebKitPlatformSupportImplNoSandbox::
60     RendererWebKitPlatformSupportImplNoSandbox() {
61   webkit_platform_support_.reset(
62       new RendererWebKitPlatformSupportImplNoSandboxImpl());
63 }
64
65 RenderViewTest::RendererWebKitPlatformSupportImplNoSandbox::
66     ~RendererWebKitPlatformSupportImplNoSandbox() {
67 }
68
69 blink::Platform*
70     RenderViewTest::RendererWebKitPlatformSupportImplNoSandbox::Get() {
71   return webkit_platform_support_.get();
72 }
73
74 RenderViewTest::RenderViewTest()
75     : view_(NULL) {
76 }
77
78 RenderViewTest::~RenderViewTest() {
79 }
80
81 void RenderViewTest::ProcessPendingMessages() {
82   msg_loop_.PostTask(FROM_HERE, base::MessageLoop::QuitClosure());
83   msg_loop_.Run();
84 }
85
86 WebFrame* RenderViewTest::GetMainFrame() {
87   return view_->GetWebView()->mainFrame();
88 }
89
90 void RenderViewTest::ExecuteJavaScript(const char* js) {
91   GetMainFrame()->executeScript(WebScriptSource(WebString::fromUTF8(js)));
92 }
93
94 bool RenderViewTest::ExecuteJavaScriptAndReturnIntValue(
95     const base::string16& script,
96     int* int_result) {
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())
101     return false;
102
103   if (int_result)
104     *int_result = result->Int32Value();
105
106   return true;
107 }
108
109 void RenderViewTest::LoadHTML(const char* html) {
110   std::string url_str = "data:text/html;charset=utf-8,";
111   url_str.append(html);
112   GURL url(url_str);
113
114   GetMainFrame()->loadRequest(WebURLRequest(url));
115
116   // The load actually happens asynchronously, so we pump messages to process
117   // the pending continuation.
118   ProcessPendingMessages();
119 }
120
121 void RenderViewTest::GoBack(const blink::WebHistoryItem& item) {
122   GoToOffset(-1, item);
123 }
124
125 void RenderViewTest::GoForward(const blink::WebHistoryItem& item) {
126   GoToOffset(1, item);
127 }
128
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_);
134   if (old_client)
135     SetRendererClientForTesting(old_client);
136
137   // Subclasses can set render_thread_ with their own implementation before
138   // calling RenderViewTest::SetUp().
139   if (!render_thread_)
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);
145
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();
150
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());
155
156   // Ensure that we register any necessary schemes when initializing WebKit,
157   // since we are using a MockRenderThread.
158   RenderThreadImpl::RegisterSchemes();
159
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);
166
167   mock_process_.reset(new MockRenderProcess);
168
169   // This needs to pass the mock render thread to the view.
170   RenderViewImpl* view = RenderViewImpl::Create(
171       kOpenerId,
172       RendererPreferences(),
173       WebPreferences(),
174       kRouteId,
175       kMainFrameRouteId,
176       kSurfaceId,
177       kInvalidSessionStorageNamespaceId,
178       base::string16(),
179       false, // is_renderer_created
180       false, // swapped_out
181       false, // hidden
182       1, // next_page_id
183       blink::WebScreenInfo(),
184       AccessibilityModeOff,
185       true);
186   view->AddRef();
187   view_ = view;
188 }
189
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();
196
197   // Run the loop so the release task from the renderwidget executes.
198   ProcessPendingMessages();
199
200   for (int i = 0; i < kGCIterations; i++)
201     GetMainFrame()->collectGarbage();
202
203   render_thread_->SendCloseMessage();
204   view_ = NULL;
205   mock_process_.reset();
206
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();
211
212   blink::shutdown();
213
214   platform_->PlatformUninitialize();
215   platform_.reset();
216   params_.reset();
217   command_line_.reset();
218 }
219
220 void RenderViewTest::SendNativeKeyEvent(
221     const NativeWebKeyboardEvent& key_event) {
222   SendWebKeyboardEvent(key_event);
223 }
224
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));
230 }
231
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));
237 }
238
239 const char* const kGetCoordinatesScript =
240     "(function() {"
241     "  function GetCoordinates(elem) {"
242     "    if (!elem)"
243     "      return [ 0, 0];"
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;"
249     "  };"
250     "  var elem = document.getElementById('$1');"
251     "  if (!elem)"
252     "    return null;"
253     "  var bounds = GetCoordinates(elem);"
254     "  bounds[2] = elem.offsetWidth;"
255     "  bounds[3] = elem.offsetHeight;"
256     "  return bounds;"
257     "})();";
258 gfx::Rect RenderViewTest::GetElementBounds(const std::string& element_id) {
259   std::vector<std::string> params;
260   params.push_back(element_id);
261   std::string script =
262       ReplaceStringPlaceholders(kGetCoordinatesScript, params, NULL);
263
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())
269     return gfx::Rect();
270
271   v8::Handle<v8::Array> array = value.As<v8::Array>();
272   if (array->Length() != 4)
273     return gfx::Rect();
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())
279       return gfx::Rect();
280     coords.push_back(value->Int32Value());
281   }
282   return gfx::Rect(coords[0], coords[1], coords[2], coords[3]);
283 }
284
285 bool RenderViewTest::SimulateElementClick(const std::string& element_id) {
286   gfx::Rect bounds = GetElementBounds(element_id);
287   if (bounds.IsEmpty())
288     return false;
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);
299   return true;
300 }
301
302 void RenderViewTest::SetFocused(const blink::WebNode& node) {
303   RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
304   impl->focusedNodeChanged(node);
305 }
306
307 void RenderViewTest::ClearHistory() {
308   RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
309   impl->page_id_ = -1;
310   impl->history_list_offset_ = -1;
311   impl->history_list_length_ = 0;
312   impl->history_page_ids_.clear();
313 }
314
315 void RenderViewTest::Reload(const GURL& url) {
316   ViewMsg_Navigate_Params params;
317   params.url = url;
318   params.navigation_type = ViewMsg_Navigate_Type::RELOAD;
319   RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
320   impl->OnNavigate(params);
321 }
322
323 uint32 RenderViewTest::GetNavigationIPCType() {
324   return ViewHostMsg_FrameNavigate::ID;
325 }
326
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);
339 }
340
341 bool RenderViewTest::OnMessageReceived(const IPC::Message& msg) {
342   RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
343   return impl->OnMessageReceived(msg);
344 }
345
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);
350 }
351
352 void RenderViewTest::SendContentStateImmediately() {
353   RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
354   impl->set_send_content_state_immediately(true);
355 }
356
357 blink::WebWidget* RenderViewTest::GetWebWidget() {
358   RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
359   return impl->webwidget();
360 }
361
362 void RenderViewTest::GoToOffset(int offset,
363                                 const blink::WebHistoryItem& history_item) {
364   RenderViewImpl* impl = static_cast<RenderViewImpl*>(view_);
365
366   int history_list_length = impl->historyBackListCount() +
367                             impl->historyForwardListCount() + 1;
368   int pending_offset = offset + impl->history_list_offset();
369
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();
379
380   ViewMsg_Navigate navigate_message(impl->GetRoutingID(), navigate_params);
381   OnMessageReceived(navigate_message);
382
383   // The load actually happens asynchronously, so we pump messages to process
384   // the pending continuation.
385   ProcessPendingMessages();
386 }
387
388 }  // namespace content