Upstream version 9.38.204.0
[platform/framework/web/crosswalk.git] / src / content / browser / renderer_host / render_view_host_impl.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/browser/renderer_host/render_view_host_impl.h"
6
7 #include <set>
8 #include <string>
9 #include <utility>
10 #include <vector>
11
12 #include "base/callback.h"
13 #include "base/command_line.h"
14 #include "base/debug/trace_event.h"
15 #include "base/i18n/rtl.h"
16 #include "base/json/json_reader.h"
17 #include "base/message_loop/message_loop.h"
18 #include "base/metrics/histogram.h"
19 #include "base/stl_util.h"
20 #include "base/strings/string_util.h"
21 #include "base/strings/utf_string_conversions.h"
22 #include "base/sys_info.h"
23 #include "base/time/time.h"
24 #include "base/values.h"
25 #include "cc/base/switches.h"
26 #include "content/browser/child_process_security_policy_impl.h"
27 #include "content/browser/dom_storage/session_storage_namespace_impl.h"
28 #include "content/browser/frame_host/frame_tree.h"
29 #include "content/browser/gpu/compositor_util.h"
30 #include "content/browser/gpu/gpu_data_manager_impl.h"
31 #include "content/browser/gpu/gpu_process_host.h"
32 #include "content/browser/gpu/gpu_surface_tracker.h"
33 #include "content/browser/host_zoom_map_impl.h"
34 #include "content/browser/loader/resource_dispatcher_host_impl.h"
35 #include "content/browser/renderer_host/dip_util.h"
36 #include "content/browser/renderer_host/input/timeout_monitor.h"
37 #include "content/browser/renderer_host/media/audio_renderer_host.h"
38 #include "content/browser/renderer_host/render_process_host_impl.h"
39 #include "content/browser/renderer_host/render_view_host_delegate.h"
40 #include "content/browser/renderer_host/render_view_host_delegate_view.h"
41 #include "content/browser/renderer_host/render_widget_host_view_base.h"
42 #include "content/common/browser_plugin/browser_plugin_messages.h"
43 #include "content/common/content_switches_internal.h"
44 #include "content/common/drag_messages.h"
45 #include "content/common/frame_messages.h"
46 #include "content/common/input_messages.h"
47 #include "content/common/inter_process_time_ticks_converter.h"
48 #include "content/common/speech_recognition_messages.h"
49 #include "content/common/swapped_out_messages.h"
50 #include "content/common/view_messages.h"
51 #include "content/public/browser/ax_event_notification_details.h"
52 #include "content/public/browser/browser_accessibility_state.h"
53 #include "content/public/browser/browser_context.h"
54 #include "content/public/browser/browser_message_filter.h"
55 #include "content/public/browser/content_browser_client.h"
56 #include "content/public/browser/native_web_keyboard_event.h"
57 #include "content/public/browser/notification_details.h"
58 #include "content/public/browser/notification_service.h"
59 #include "content/public/browser/notification_types.h"
60 #include "content/public/browser/render_frame_host.h"
61 #include "content/public/browser/render_widget_host_iterator.h"
62 #include "content/public/browser/storage_partition.h"
63 #include "content/public/browser/user_metrics.h"
64 #include "content/public/common/bindings_policy.h"
65 #include "content/public/common/content_constants.h"
66 #include "content/public/common/content_switches.h"
67 #include "content/public/common/context_menu_params.h"
68 #include "content/public/common/drop_data.h"
69 #include "content/public/common/result_codes.h"
70 #include "content/public/common/url_utils.h"
71 #include "net/base/filename_util.h"
72 #include "net/base/net_util.h"
73 #include "net/base/network_change_notifier.h"
74 #include "net/url_request/url_request_context_getter.h"
75 #include "third_party/skia/include/core/SkBitmap.h"
76 #include "ui/base/touch/touch_device.h"
77 #include "ui/base/touch/touch_enabled.h"
78 #include "ui/base/ui_base_switches.h"
79 #include "ui/gfx/image/image_skia.h"
80 #include "ui/gfx/native_widget_types.h"
81 #include "ui/native_theme/native_theme_switches.h"
82 #include "ui/shell_dialogs/selected_file_info.h"
83 #include "url/url_constants.h"
84 #include "webkit/browser/fileapi/isolated_context.h"
85
86 #if defined(OS_MACOSX)
87 #include "content/browser/renderer_host/popup_menu_helper_mac.h"
88 #elif defined(OS_WIN)
89 #include "base/win/win_util.h"
90 #endif
91
92 #if defined(ENABLE_BROWSER_CDMS)
93 #include "content/browser/media/media_web_contents_observer.h"
94 #endif
95
96 #if defined(OS_TIZEN) && defined(ENABLE_MURPHY)
97 #include "xwalk/tizen/browser/media/media_webcontents_observer.h"
98 #endif
99
100 using base::TimeDelta;
101 using blink::WebConsoleMessage;
102 using blink::WebDragOperation;
103 using blink::WebDragOperationNone;
104 using blink::WebDragOperationsMask;
105 using blink::WebInputEvent;
106 using blink::WebMediaPlayerAction;
107 using blink::WebPluginAction;
108
109 namespace content {
110 namespace {
111
112 #if defined(OS_WIN)
113
114 const int kVirtualKeyboardDisplayWaitTimeoutMs = 100;
115 const int kMaxVirtualKeyboardDisplayRetries = 5;
116
117 void DismissVirtualKeyboardTask() {
118   static int virtual_keyboard_display_retries = 0;
119   // If the virtual keyboard is not yet visible, then we execute the task again
120   // waiting for it to show up.
121   if (!base::win::DismissVirtualKeyboard()) {
122     if (virtual_keyboard_display_retries < kMaxVirtualKeyboardDisplayRetries) {
123       BrowserThread::PostDelayedTask(
124           BrowserThread::UI, FROM_HERE,
125           base::Bind(base::IgnoreResult(&DismissVirtualKeyboardTask)),
126           TimeDelta::FromMilliseconds(kVirtualKeyboardDisplayWaitTimeoutMs));
127       ++virtual_keyboard_display_retries;
128     } else {
129       virtual_keyboard_display_retries = 0;
130     }
131   }
132 }
133 #endif
134
135 }  // namespace
136
137 // static
138 const int RenderViewHostImpl::kUnloadTimeoutMS = 1000;
139
140 ///////////////////////////////////////////////////////////////////////////////
141 // RenderViewHost, public:
142
143 // static
144 bool RenderViewHostImpl::IsRVHStateActive(RenderViewHostImplState rvh_state) {
145   if (rvh_state == STATE_DEFAULT ||
146       rvh_state == STATE_WAITING_FOR_UNLOAD_ACK ||
147       rvh_state == STATE_WAITING_FOR_COMMIT ||
148       rvh_state == STATE_WAITING_FOR_CLOSE)
149     return true;
150   return false;
151 }
152
153 // static
154 RenderViewHost* RenderViewHost::FromID(int render_process_id,
155                                        int render_view_id) {
156   return RenderViewHostImpl::FromID(render_process_id, render_view_id);
157 }
158
159 // static
160 RenderViewHost* RenderViewHost::From(RenderWidgetHost* rwh) {
161   DCHECK(rwh->IsRenderView());
162   return static_cast<RenderViewHostImpl*>(RenderWidgetHostImpl::From(rwh));
163 }
164
165 ///////////////////////////////////////////////////////////////////////////////
166 // RenderViewHostImpl, public:
167
168 // static
169 RenderViewHostImpl* RenderViewHostImpl::FromID(int render_process_id,
170                                                int render_view_id) {
171   RenderWidgetHost* widget =
172       RenderWidgetHost::FromID(render_process_id, render_view_id);
173   if (!widget || !widget->IsRenderView())
174     return NULL;
175   return static_cast<RenderViewHostImpl*>(RenderWidgetHostImpl::From(widget));
176 }
177
178 RenderViewHostImpl::RenderViewHostImpl(
179     SiteInstance* instance,
180     RenderViewHostDelegate* delegate,
181     RenderWidgetHostDelegate* widget_delegate,
182     int routing_id,
183     int main_frame_routing_id,
184     bool swapped_out,
185     bool hidden)
186     : RenderWidgetHostImpl(widget_delegate,
187                            instance->GetProcess(),
188                            routing_id,
189                            hidden),
190       frames_ref_count_(0),
191       delegate_(delegate),
192       instance_(static_cast<SiteInstanceImpl*>(instance)),
193       waiting_for_drag_context_response_(false),
194       enabled_bindings_(0),
195       main_frame_routing_id_(main_frame_routing_id),
196       run_modal_reply_msg_(NULL),
197       run_modal_opener_id_(MSG_ROUTING_NONE),
198       is_waiting_for_beforeunload_ack_(false),
199       unload_ack_is_for_cross_site_transition_(false),
200       sudden_termination_allowed_(false),
201       render_view_termination_status_(base::TERMINATION_STATUS_STILL_RUNNING),
202       virtual_keyboard_requested_(false),
203       weak_factory_(this),
204       is_focused_element_editable_(false),
205       updating_web_preferences_(false) {
206   DCHECK(instance_.get());
207   CHECK(delegate_);  // http://crbug.com/82827
208
209   GetProcess()->EnableSendQueue();
210
211   if (swapped_out) {
212     rvh_state_ = STATE_SWAPPED_OUT;
213   } else {
214     rvh_state_ = STATE_DEFAULT;
215     instance_->increment_active_view_count();
216   }
217
218   if (ResourceDispatcherHostImpl::Get()) {
219     BrowserThread::PostTask(
220         BrowserThread::IO, FROM_HERE,
221         base::Bind(&ResourceDispatcherHostImpl::OnRenderViewHostCreated,
222                    base::Unretained(ResourceDispatcherHostImpl::Get()),
223                    GetProcess()->GetID(), GetRoutingID()));
224   }
225
226 #if defined(ENABLE_BROWSER_CDMS)
227   media_web_contents_observer_.reset(new MediaWebContentsObserver(this));
228 #endif
229
230 #if defined(OS_TIZEN) && defined(ENABLE_MURPHY)
231   media_webcontents_observer_.reset(new tizen::MediaWebContentsObserver(this));
232 #endif
233
234   unload_event_monitor_timeout_.reset(new TimeoutMonitor(base::Bind(
235       &RenderViewHostImpl::OnSwappedOut, weak_factory_.GetWeakPtr(), true)));
236 }
237
238 RenderViewHostImpl::~RenderViewHostImpl() {
239   if (ResourceDispatcherHostImpl::Get()) {
240     BrowserThread::PostTask(
241         BrowserThread::IO, FROM_HERE,
242         base::Bind(&ResourceDispatcherHostImpl::OnRenderViewHostDeleted,
243                    base::Unretained(ResourceDispatcherHostImpl::Get()),
244                    GetProcess()->GetID(), GetRoutingID()));
245   }
246
247   delegate_->RenderViewDeleted(this);
248
249   // If this was swapped out, it already decremented the active view
250   // count of the SiteInstance it belongs to.
251   if (IsRVHStateActive(rvh_state_))
252     instance_->decrement_active_view_count();
253 }
254
255 RenderViewHostDelegate* RenderViewHostImpl::GetDelegate() const {
256   return delegate_;
257 }
258
259 SiteInstance* RenderViewHostImpl::GetSiteInstance() const {
260   return instance_.get();
261 }
262
263 bool RenderViewHostImpl::CreateRenderView(
264     const base::string16& frame_name,
265     int opener_route_id,
266     int proxy_route_id,
267     int32 max_page_id,
268     bool window_was_created_with_opener) {
269   TRACE_EVENT0("renderer_host", "RenderViewHostImpl::CreateRenderView");
270   DCHECK(!IsRenderViewLive()) << "Creating view twice";
271
272   // The process may (if we're sharing a process with another host that already
273   // initialized it) or may not (we have our own process or the old process
274   // crashed) have been initialized. Calling Init multiple times will be
275   // ignored, so this is safe.
276   if (!GetProcess()->Init())
277     return false;
278   DCHECK(GetProcess()->HasConnection());
279   DCHECK(GetProcess()->GetBrowserContext());
280
281   renderer_initialized_ = true;
282
283   GpuSurfaceTracker::Get()->SetSurfaceHandle(
284       surface_id(), GetCompositingSurface());
285
286   // Ensure the RenderView starts with a next_page_id larger than any existing
287   // page ID it might be asked to render.
288   int32 next_page_id = 1;
289   if (max_page_id > -1)
290     next_page_id = max_page_id + 1;
291
292   ViewMsg_New_Params params;
293   params.renderer_preferences =
294       delegate_->GetRendererPrefs(GetProcess()->GetBrowserContext());
295   params.web_preferences = GetWebkitPreferences();
296   params.view_id = GetRoutingID();
297   params.main_frame_routing_id = main_frame_routing_id_;
298   params.surface_id = surface_id();
299   params.session_storage_namespace_id =
300       delegate_->GetSessionStorageNamespace(instance_)->id();
301   params.frame_name = frame_name;
302   // Ensure the RenderView sets its opener correctly.
303   params.opener_route_id = opener_route_id;
304   params.swapped_out = !IsRVHStateActive(rvh_state_);
305   params.proxy_routing_id = proxy_route_id;
306   params.hidden = is_hidden();
307   params.never_visible = delegate_->IsNeverVisible();
308   params.window_was_created_with_opener = window_was_created_with_opener;
309   params.next_page_id = next_page_id;
310   GetWebScreenInfo(&params.screen_info);
311
312   Send(new ViewMsg_New(params));
313
314   // If it's enabled, tell the renderer to set up the Javascript bindings for
315   // sending messages back to the browser.
316   if (GetProcess()->IsIsolatedGuest())
317     DCHECK_EQ(0, enabled_bindings_);
318   Send(new ViewMsg_AllowBindings(GetRoutingID(), enabled_bindings_));
319   // Let our delegate know that we created a RenderView.
320   delegate_->RenderViewCreated(this);
321
322   return true;
323 }
324
325 bool RenderViewHostImpl::IsRenderViewLive() const {
326   return GetProcess()->HasConnection() && renderer_initialized_;
327 }
328
329 void RenderViewHostImpl::SyncRendererPrefs() {
330   Send(new ViewMsg_SetRendererPrefs(GetRoutingID(),
331                                     delegate_->GetRendererPrefs(
332                                         GetProcess()->GetBrowserContext())));
333 }
334
335 WebPreferences RenderViewHostImpl::ComputeWebkitPrefs(const GURL& url) {
336   TRACE_EVENT0("browser", "RenderViewHostImpl::GetWebkitPrefs");
337   WebPreferences prefs;
338
339   const base::CommandLine& command_line =
340       *base::CommandLine::ForCurrentProcess();
341
342   prefs.javascript_enabled =
343       !command_line.HasSwitch(switches::kDisableJavaScript);
344   prefs.web_security_enabled =
345       !command_line.HasSwitch(switches::kDisableWebSecurity);
346   prefs.plugins_enabled =
347       !command_line.HasSwitch(switches::kDisablePlugins);
348   prefs.java_enabled =
349       !command_line.HasSwitch(switches::kDisableJava);
350
351   prefs.remote_fonts_enabled =
352       !command_line.HasSwitch(switches::kDisableRemoteFonts);
353   prefs.xslt_enabled =
354       !command_line.HasSwitch(switches::kDisableXSLT);
355   prefs.xss_auditor_enabled =
356       !command_line.HasSwitch(switches::kDisableXSSAuditor);
357   prefs.application_cache_enabled =
358       !command_line.HasSwitch(switches::kDisableApplicationCache);
359
360   prefs.local_storage_enabled =
361       !command_line.HasSwitch(switches::kDisableLocalStorage);
362   prefs.databases_enabled =
363       !command_line.HasSwitch(switches::kDisableDatabases);
364 #if defined(OS_ANDROID)
365   // WebAudio is enabled by default on x86 and ARM.
366   prefs.webaudio_enabled =
367       !command_line.HasSwitch(switches::kDisableWebAudio);
368 #endif
369
370   prefs.experimental_webgl_enabled =
371       GpuProcessHost::gpu_enabled() &&
372       !command_line.HasSwitch(switches::kDisable3DAPIs) &&
373       !command_line.HasSwitch(switches::kDisableExperimentalWebGL);
374
375   prefs.pepper_3d_enabled =
376       !command_line.HasSwitch(switches::kDisablePepper3d);
377
378   prefs.flash_3d_enabled =
379       GpuProcessHost::gpu_enabled() &&
380       !command_line.HasSwitch(switches::kDisableFlash3d);
381   prefs.flash_stage3d_enabled =
382       GpuProcessHost::gpu_enabled() &&
383       !command_line.HasSwitch(switches::kDisableFlashStage3d);
384   prefs.flash_stage3d_baseline_enabled =
385       GpuProcessHost::gpu_enabled() &&
386       !command_line.HasSwitch(switches::kDisableFlashStage3d);
387
388   prefs.allow_file_access_from_file_urls =
389       command_line.HasSwitch(switches::kAllowFileAccessFromFiles);
390
391   prefs.layer_squashing_enabled = true;
392   if (command_line.HasSwitch(switches::kEnableLayerSquashing))
393       prefs.layer_squashing_enabled = true;
394   if (command_line.HasSwitch(switches::kDisableLayerSquashing))
395       prefs.layer_squashing_enabled = false;
396
397   prefs.accelerated_2d_canvas_enabled =
398       GpuProcessHost::gpu_enabled() &&
399       !command_line.HasSwitch(switches::kDisableAccelerated2dCanvas);
400   prefs.antialiased_2d_canvas_disabled =
401       command_line.HasSwitch(switches::kDisable2dCanvasAntialiasing);
402   prefs.accelerated_2d_canvas_msaa_sample_count =
403       atoi(command_line.GetSwitchValueASCII(
404       switches::kAcceleratedCanvas2dMSAASampleCount).c_str());
405   prefs.deferred_filters_enabled =
406       !command_line.HasSwitch(switches::kDisableDeferredFilters);
407   prefs.container_culling_enabled =
408       command_line.HasSwitch(switches::kEnableContainerCulling);
409   prefs.region_based_columns_enabled =
410       command_line.HasSwitch(switches::kEnableRegionBasedColumns);
411
412   if (IsPinchVirtualViewportEnabled()) {
413     prefs.pinch_virtual_viewport_enabled = true;
414     prefs.pinch_overlay_scrollbar_thickness = 10;
415   }
416   prefs.use_solid_color_scrollbars = ui::IsOverlayScrollbarEnabled();
417
418 #if defined(OS_ANDROID)
419   prefs.user_gesture_required_for_media_playback = !command_line.HasSwitch(
420       switches::kDisableGestureRequirementForMediaPlayback);
421 #endif
422
423   prefs.touch_enabled = ui::AreTouchEventsEnabled();
424   prefs.device_supports_touch = prefs.touch_enabled &&
425       ui::IsTouchDevicePresent();
426 #if defined(OS_ANDROID)
427   prefs.device_supports_mouse = false;
428 #endif
429
430   prefs.pointer_events_max_touch_points = ui::MaxTouchPoints();
431
432   prefs.touch_adjustment_enabled =
433       !command_line.HasSwitch(switches::kDisableTouchAdjustment);
434
435 #if defined(OS_MACOSX) || defined(OS_CHROMEOS)
436   bool default_enable_scroll_animator = true;
437 #else
438   bool default_enable_scroll_animator = false;
439 #endif
440   prefs.enable_scroll_animator = default_enable_scroll_animator;
441   if (command_line.HasSwitch(switches::kEnableSmoothScrolling))
442     prefs.enable_scroll_animator = true;
443   if (command_line.HasSwitch(switches::kDisableSmoothScrolling))
444     prefs.enable_scroll_animator = false;
445
446   // Certain GPU features might have been blacklisted.
447   GpuDataManagerImpl::GetInstance()->UpdateRendererWebPrefs(&prefs);
448
449   if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
450           GetProcess()->GetID())) {
451     prefs.loads_images_automatically = true;
452     prefs.javascript_enabled = true;
453   }
454
455   prefs.connection_type = net::NetworkChangeNotifier::GetConnectionType();
456   prefs.is_online =
457       prefs.connection_type != net::NetworkChangeNotifier::CONNECTION_NONE;
458
459   prefs.number_of_cpu_cores = base::SysInfo::NumberOfProcessors();
460
461   prefs.viewport_meta_enabled =
462       command_line.HasSwitch(switches::kEnableViewportMeta);
463
464   prefs.viewport_enabled =
465       command_line.HasSwitch(switches::kEnableViewport) ||
466       prefs.viewport_meta_enabled;
467
468   prefs.main_frame_resizes_are_orientation_changes =
469       command_line.HasSwitch(switches::kMainFrameResizesAreOrientationChanges);
470
471   prefs.deferred_image_decoding_enabled =
472       command_line.HasSwitch(switches::kEnableDeferredImageDecoding) ||
473       content::IsImplSidePaintingEnabled();
474
475   prefs.spatial_navigation_enabled = command_line.HasSwitch(
476       switches::kEnableSpatialNavigation);
477
478   if (command_line.HasSwitch(switches::kV8CacheOptions)) {
479     const std::string v8_cache_options =
480         command_line.GetSwitchValueASCII(switches::kV8CacheOptions);
481     if (v8_cache_options == "parse") {
482       prefs.v8_cache_options = V8_CACHE_OPTIONS_PARSE;
483     } else if (v8_cache_options == "code") {
484       prefs.v8_cache_options = V8_CACHE_OPTIONS_CODE;
485     } else {
486       prefs.v8_cache_options = V8_CACHE_OPTIONS_OFF;
487     }
488   }
489
490   GetContentClient()->browser()->OverrideWebkitPrefs(this, url, &prefs);
491   return prefs;
492 }
493
494 void RenderViewHostImpl::Navigate(const FrameMsg_Navigate_Params& params) {
495   TRACE_EVENT0("renderer_host", "RenderViewHostImpl::Navigate");
496   delegate_->GetFrameTree()->GetMainFrame()->Navigate(params);
497 }
498
499 void RenderViewHostImpl::NavigateToURL(const GURL& url) {
500   delegate_->GetFrameTree()->GetMainFrame()->NavigateToURL(url);
501 }
502
503 void RenderViewHostImpl::SuppressDialogsUntilSwapOut() {
504   Send(new ViewMsg_SuppressDialogsUntilSwapOut(GetRoutingID()));
505 }
506
507 void RenderViewHostImpl::OnSwappedOut(bool timed_out) {
508   // Ignore spurious swap out ack.
509   if (!IsWaitingForUnloadACK())
510     return;
511   unload_event_monitor_timeout_->Stop();
512   if (timed_out) {
513     base::ProcessHandle process_handle = GetProcess()->GetHandle();
514     int views = 0;
515
516     // Count the number of active widget hosts for the process, which
517     // is equivalent to views using the process as of this writing.
518     scoped_ptr<RenderWidgetHostIterator> widgets(
519       RenderWidgetHost::GetRenderWidgetHosts());
520     while (RenderWidgetHost* widget = widgets->GetNextHost()) {
521       if (widget->GetProcess()->GetID() == GetProcess()->GetID())
522         ++views;
523     }
524
525     if (!RenderProcessHost::run_renderer_in_process() &&
526         process_handle && views <= 1) {
527       // The process can safely be terminated, only if WebContents sets
528       // SuddenTerminationAllowed, which indicates that the timer has expired.
529       // This is not the case if we load data URLs or about:blank. The reason
530       // is that those have no network requests and this code is hit without
531       // setting the unresponsiveness timer. This allows a corner case where a
532       // navigation to a data URL will leave a process running, if the
533       // beforeunload handler completes fine, but the unload handler hangs.
534       // At this time, the complexity to solve this edge case is not worthwhile.
535       if (SuddenTerminationAllowed()) {
536         // We should kill the process, but for now, just log the data so we can
537         // diagnose the kill rate and investigate if separate timer is needed.
538         // http://crbug.com/104346.
539
540         // Log a histogram point to help us diagnose how many of those kills
541         // we have performed. 1 is the enum value for RendererType Normal for
542         // the histogram.
543         UMA_HISTOGRAM_PERCENTAGE(
544             "BrowserRenderProcessHost.ChildKillsUnresponsive", 1);
545       }
546     }
547   }
548
549   switch (rvh_state_) {
550     case STATE_WAITING_FOR_UNLOAD_ACK:
551       SetState(STATE_WAITING_FOR_COMMIT);
552       break;
553     case STATE_PENDING_SWAP_OUT:
554       SetState(STATE_SWAPPED_OUT);
555       break;
556     case STATE_PENDING_SHUTDOWN:
557       DCHECK(!pending_shutdown_on_swap_out_.is_null());
558       pending_shutdown_on_swap_out_.Run();
559       break;
560     default:
561       NOTREACHED();
562   }
563 }
564
565 void RenderViewHostImpl::WasSwappedOut(
566     const base::Closure& pending_delete_on_swap_out) {
567   Send(new ViewMsg_WasSwappedOut(GetRoutingID()));
568   if (rvh_state_ == STATE_WAITING_FOR_UNLOAD_ACK) {
569     SetState(STATE_PENDING_SWAP_OUT);
570     if (!instance_->active_view_count())
571       SetPendingShutdown(pending_delete_on_swap_out);
572   } else if (rvh_state_ == STATE_WAITING_FOR_COMMIT) {
573     SetState(STATE_SWAPPED_OUT);
574   } else if (rvh_state_ == STATE_DEFAULT) {
575     // When the RenderView is not live, the RenderFrameHostManager will call
576     // CommitPending directly, without calling SwapOut on the old RVH. This will
577     // cause WasSwappedOut to be called directly on the live old RVH.
578     DCHECK(!IsRenderViewLive());
579     SetState(STATE_SWAPPED_OUT);
580   } else {
581     NOTREACHED();
582   }
583 }
584
585 void RenderViewHostImpl::SetPendingShutdown(const base::Closure& on_swap_out) {
586   pending_shutdown_on_swap_out_ = on_swap_out;
587   SetState(STATE_PENDING_SHUTDOWN);
588 }
589
590 void RenderViewHostImpl::ClosePage() {
591   SetState(STATE_WAITING_FOR_CLOSE);
592   StartHangMonitorTimeout(TimeDelta::FromMilliseconds(kUnloadTimeoutMS));
593
594   if (IsRenderViewLive()) {
595     // Since we are sending an IPC message to the renderer, increase the event
596     // count to prevent the hang monitor timeout from being stopped by input
597     // event acknowledgements.
598     increment_in_flight_event_count();
599
600     // TODO(creis): Should this be moved to Shutdown?  It may not be called for
601     // RenderViewHosts that have been swapped out.
602     NotificationService::current()->Notify(
603         NOTIFICATION_RENDER_VIEW_HOST_WILL_CLOSE_RENDER_VIEW,
604         Source<RenderViewHost>(this),
605         NotificationService::NoDetails());
606
607     Send(new ViewMsg_ClosePage(GetRoutingID()));
608   } else {
609     // This RenderViewHost doesn't have a live renderer, so just skip the unload
610     // event and close the page.
611     ClosePageIgnoringUnloadEvents();
612   }
613 }
614
615 void RenderViewHostImpl::ClosePageIgnoringUnloadEvents() {
616   StopHangMonitorTimeout();
617   is_waiting_for_beforeunload_ack_ = false;
618
619   sudden_termination_allowed_ = true;
620   delegate_->Close(this);
621 }
622
623 #if defined(OS_ANDROID)
624 void RenderViewHostImpl::ActivateNearestFindResult(int request_id,
625                                                    float x,
626                                                    float y) {
627   Send(new InputMsg_ActivateNearestFindResult(GetRoutingID(),
628                                               request_id, x, y));
629 }
630
631 void RenderViewHostImpl::RequestFindMatchRects(int current_version) {
632   Send(new ViewMsg_FindMatchRects(GetRoutingID(), current_version));
633 }
634 #endif
635
636 void RenderViewHostImpl::DragTargetDragEnter(
637     const DropData& drop_data,
638     const gfx::Point& client_pt,
639     const gfx::Point& screen_pt,
640     WebDragOperationsMask operations_allowed,
641     int key_modifiers) {
642   const int renderer_id = GetProcess()->GetID();
643   ChildProcessSecurityPolicyImpl* policy =
644       ChildProcessSecurityPolicyImpl::GetInstance();
645
646   // The URL could have been cobbled together from any highlighted text string,
647   // and can't be interpreted as a capability.
648   DropData filtered_data(drop_data);
649   GetProcess()->FilterURL(true, &filtered_data.url);
650   if (drop_data.did_originate_from_renderer) {
651     filtered_data.filenames.clear();
652   }
653
654   // The filenames vector, on the other hand, does represent a capability to
655   // access the given files.
656   fileapi::IsolatedContext::FileInfoSet files;
657   for (std::vector<ui::FileInfo>::iterator iter(
658            filtered_data.filenames.begin());
659        iter != filtered_data.filenames.end();
660        ++iter) {
661     // A dragged file may wind up as the value of an input element, or it
662     // may be used as the target of a navigation instead.  We don't know
663     // which will happen at this point, so generously grant both access
664     // and request permissions to the specific file to cover both cases.
665     // We do not give it the permission to request all file:// URLs.
666
667     // Make sure we have the same display_name as the one we register.
668     if (iter->display_name.empty()) {
669       std::string name;
670       files.AddPath(iter->path, &name);
671       iter->display_name = base::FilePath::FromUTF8Unsafe(name);
672     } else {
673       files.AddPathWithName(iter->path, iter->display_name.AsUTF8Unsafe());
674     }
675
676     policy->GrantRequestSpecificFileURL(renderer_id,
677                                         net::FilePathToFileURL(iter->path));
678
679     // If the renderer already has permission to read these paths, we don't need
680     // to re-grant them. This prevents problems with DnD for files in the CrOS
681     // file manager--the file manager already had read/write access to those
682     // directories, but dragging a file would cause the read/write access to be
683     // overwritten with read-only access, making them impossible to delete or
684     // rename until the renderer was killed.
685     if (!policy->CanReadFile(renderer_id, iter->path))
686       policy->GrantReadFile(renderer_id, iter->path);
687   }
688
689   fileapi::IsolatedContext* isolated_context =
690       fileapi::IsolatedContext::GetInstance();
691   DCHECK(isolated_context);
692   std::string filesystem_id = isolated_context->RegisterDraggedFileSystem(
693       files);
694   if (!filesystem_id.empty()) {
695     // Grant the permission iff the ID is valid.
696     policy->GrantReadFileSystem(renderer_id, filesystem_id);
697   }
698   filtered_data.filesystem_id = base::UTF8ToUTF16(filesystem_id);
699
700   fileapi::FileSystemContext* file_system_context =
701       BrowserContext::GetStoragePartition(
702           GetProcess()->GetBrowserContext(),
703           GetSiteInstance())->GetFileSystemContext();
704   for (size_t i = 0; i < filtered_data.file_system_files.size(); ++i) {
705     fileapi::FileSystemURL file_system_url =
706         file_system_context->CrackURL(filtered_data.file_system_files[i].url);
707
708     std::string register_name;
709     std::string filesystem_id = isolated_context->RegisterFileSystemForPath(
710         file_system_url.type(), file_system_url.filesystem_id(),
711         file_system_url.path(), &register_name);
712     policy->GrantReadFileSystem(renderer_id, filesystem_id);
713
714     // Note: We are using the origin URL provided by the sender here. It may be
715     // different from the receiver's.
716     filtered_data.file_system_files[i].url = GURL(
717         fileapi::GetIsolatedFileSystemRootURIString(
718             file_system_url.origin(),
719             filesystem_id,
720             std::string()).append(register_name));
721   }
722
723   Send(new DragMsg_TargetDragEnter(GetRoutingID(), filtered_data, client_pt,
724                                    screen_pt, operations_allowed,
725                                    key_modifiers));
726 }
727
728 void RenderViewHostImpl::DragTargetDragOver(
729     const gfx::Point& client_pt,
730     const gfx::Point& screen_pt,
731     WebDragOperationsMask operations_allowed,
732     int key_modifiers) {
733   Send(new DragMsg_TargetDragOver(GetRoutingID(), client_pt, screen_pt,
734                                   operations_allowed, key_modifiers));
735 }
736
737 void RenderViewHostImpl::DragTargetDragLeave() {
738   Send(new DragMsg_TargetDragLeave(GetRoutingID()));
739 }
740
741 void RenderViewHostImpl::DragTargetDrop(
742     const gfx::Point& client_pt,
743     const gfx::Point& screen_pt,
744     int key_modifiers) {
745   Send(new DragMsg_TargetDrop(GetRoutingID(), client_pt, screen_pt,
746                               key_modifiers));
747 }
748
749 void RenderViewHostImpl::DragSourceEndedAt(
750     int client_x, int client_y, int screen_x, int screen_y,
751     WebDragOperation operation) {
752   Send(new DragMsg_SourceEnded(GetRoutingID(),
753                                gfx::Point(client_x, client_y),
754                                gfx::Point(screen_x, screen_y),
755                                operation));
756 }
757
758 void RenderViewHostImpl::DragSourceSystemDragEnded() {
759   Send(new DragMsg_SourceSystemDragEnded(GetRoutingID()));
760 }
761
762 RenderFrameHost* RenderViewHostImpl::GetMainFrame() {
763   return RenderFrameHost::FromID(GetProcess()->GetID(), main_frame_routing_id_);
764 }
765
766 void RenderViewHostImpl::AllowBindings(int bindings_flags) {
767   // Never grant any bindings to browser plugin guests.
768   if (GetProcess()->IsIsolatedGuest()) {
769     NOTREACHED() << "Never grant bindings to a guest process.";
770     return;
771   }
772
773   // Ensure we aren't granting WebUI bindings to a process that has already
774   // been used for non-privileged views.
775   if (bindings_flags & BINDINGS_POLICY_WEB_UI &&
776       GetProcess()->HasConnection() &&
777       !ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
778           GetProcess()->GetID())) {
779     // This process has no bindings yet. Make sure it does not have more
780     // than this single active view.
781     RenderProcessHostImpl* process =
782         static_cast<RenderProcessHostImpl*>(GetProcess());
783     // --single-process only has one renderer.
784     if (process->GetActiveViewCount() > 1 &&
785         !base::CommandLine::ForCurrentProcess()->HasSwitch(
786             switches::kSingleProcess))
787       return;
788   }
789
790   if (bindings_flags & BINDINGS_POLICY_WEB_UI) {
791     ChildProcessSecurityPolicyImpl::GetInstance()->GrantWebUIBindings(
792         GetProcess()->GetID());
793   }
794
795   enabled_bindings_ |= bindings_flags;
796   if (renderer_initialized_)
797     Send(new ViewMsg_AllowBindings(GetRoutingID(), enabled_bindings_));
798 }
799
800 int RenderViewHostImpl::GetEnabledBindings() const {
801   return enabled_bindings_;
802 }
803
804 void RenderViewHostImpl::SetWebUIProperty(const std::string& name,
805                                           const std::string& value) {
806   // This is a sanity check before telling the renderer to enable the property.
807   // It could lie and send the corresponding IPC messages anyway, but we will
808   // not act on them if enabled_bindings_ doesn't agree. If we get here without
809   // WebUI bindings, kill the renderer process.
810   if (enabled_bindings_ & BINDINGS_POLICY_WEB_UI) {
811     Send(new ViewMsg_SetWebUIProperty(GetRoutingID(), name, value));
812   } else {
813     RecordAction(
814         base::UserMetricsAction("BindingsMismatchTerminate_RVH_WebUI"));
815     base::KillProcess(
816         GetProcess()->GetHandle(), content::RESULT_CODE_KILLED, false);
817   }
818 }
819
820 void RenderViewHostImpl::GotFocus() {
821   RenderWidgetHostImpl::GotFocus();  // Notifies the renderer it got focus.
822
823   RenderViewHostDelegateView* view = delegate_->GetDelegateView();
824   if (view)
825     view->GotFocus();
826 }
827
828 void RenderViewHostImpl::LostCapture() {
829   RenderWidgetHostImpl::LostCapture();
830   delegate_->LostCapture();
831 }
832
833 void RenderViewHostImpl::LostMouseLock() {
834   RenderWidgetHostImpl::LostMouseLock();
835   delegate_->LostMouseLock();
836 }
837
838 void RenderViewHostImpl::SetInitialFocus(bool reverse) {
839   Send(new ViewMsg_SetInitialFocus(GetRoutingID(), reverse));
840 }
841
842 void RenderViewHostImpl::FilesSelectedInChooser(
843     const std::vector<ui::SelectedFileInfo>& files,
844     FileChooserParams::Mode permissions) {
845   // Grant the security access requested to the given files.
846   for (size_t i = 0; i < files.size(); ++i) {
847     const ui::SelectedFileInfo& file = files[i];
848     if (permissions == FileChooserParams::Save) {
849       ChildProcessSecurityPolicyImpl::GetInstance()->GrantCreateReadWriteFile(
850           GetProcess()->GetID(), file.local_path);
851     } else {
852       ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
853           GetProcess()->GetID(), file.local_path);
854     }
855   }
856   Send(new ViewMsg_RunFileChooserResponse(GetRoutingID(), files));
857 }
858
859 void RenderViewHostImpl::DirectoryEnumerationFinished(
860     int request_id,
861     const std::vector<base::FilePath>& files) {
862   // Grant the security access requested to the given files.
863   for (std::vector<base::FilePath>::const_iterator file = files.begin();
864        file != files.end(); ++file) {
865     ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
866         GetProcess()->GetID(), *file);
867   }
868   Send(new ViewMsg_EnumerateDirectoryResponse(GetRoutingID(),
869                                               request_id,
870                                               files));
871 }
872
873 void RenderViewHostImpl::LoadStateChanged(
874     const GURL& url,
875     const net::LoadStateWithParam& load_state,
876     uint64 upload_position,
877     uint64 upload_size) {
878   delegate_->LoadStateChanged(url, load_state, upload_position, upload_size);
879 }
880
881 bool RenderViewHostImpl::SuddenTerminationAllowed() const {
882   return sudden_termination_allowed_ ||
883       GetProcess()->SuddenTerminationAllowed();
884 }
885
886 ///////////////////////////////////////////////////////////////////////////////
887 // RenderViewHostImpl, IPC message handlers:
888
889 bool RenderViewHostImpl::OnMessageReceived(const IPC::Message& msg) {
890   if (!BrowserMessageFilter::CheckCanDispatchOnUI(msg, this))
891     return true;
892
893   // Filter out most IPC messages if this renderer is swapped out.
894   // We still want to handle certain ACKs to keep our state consistent.
895   if (IsSwappedOut()) {
896     if (!SwappedOutMessages::CanHandleWhileSwappedOut(msg)) {
897       // If this is a synchronous message and we decided not to handle it,
898       // we must send an error reply, or else the renderer will be stuck
899       // and won't respond to future requests.
900       if (msg.is_sync()) {
901         IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
902         reply->set_reply_error();
903         Send(reply);
904       }
905       // Don't continue looking for someone to handle it.
906       return true;
907     }
908   }
909
910   if (delegate_->OnMessageReceived(this, msg))
911     return true;
912
913   bool handled = true;
914   IPC_BEGIN_MESSAGE_MAP(RenderViewHostImpl, msg)
915     IPC_MESSAGE_HANDLER(ViewHostMsg_ShowView, OnShowView)
916     IPC_MESSAGE_HANDLER(ViewHostMsg_ShowWidget, OnShowWidget)
917     IPC_MESSAGE_HANDLER(ViewHostMsg_ShowFullscreenWidget,
918                         OnShowFullscreenWidget)
919     IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_RunModal, OnRunModal)
920     IPC_MESSAGE_HANDLER(ViewHostMsg_RenderViewReady, OnRenderViewReady)
921     IPC_MESSAGE_HANDLER(ViewHostMsg_RenderProcessGone, OnRenderProcessGone)
922     IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateState, OnUpdateState)
923     IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateTargetURL, OnUpdateTargetURL)
924     IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateInspectorSetting,
925                         OnUpdateInspectorSetting)
926     IPC_MESSAGE_HANDLER(ViewHostMsg_Close, OnClose)
927     IPC_MESSAGE_HANDLER(ViewHostMsg_RequestMove, OnRequestMove)
928     IPC_MESSAGE_HANDLER(ViewHostMsg_DocumentAvailableInMainFrame,
929                         OnDocumentAvailableInMainFrame)
930     IPC_MESSAGE_HANDLER(ViewHostMsg_ToggleFullscreen, OnToggleFullscreen)
931     IPC_MESSAGE_HANDLER(ViewHostMsg_DidContentsPreferredSizeChange,
932                         OnDidContentsPreferredSizeChange)
933     IPC_MESSAGE_HANDLER(ViewHostMsg_DidChangeScrollOffset,
934                         OnDidChangeScrollOffset)
935     IPC_MESSAGE_HANDLER(ViewHostMsg_RouteCloseEvent,
936                         OnRouteCloseEvent)
937     IPC_MESSAGE_HANDLER(ViewHostMsg_RouteMessageEvent, OnRouteMessageEvent)
938     IPC_MESSAGE_HANDLER(DragHostMsg_StartDragging, OnStartDragging)
939     IPC_MESSAGE_HANDLER(DragHostMsg_UpdateDragCursor, OnUpdateDragCursor)
940     IPC_MESSAGE_HANDLER(DragHostMsg_TargetDrop_ACK, OnTargetDropACK)
941     IPC_MESSAGE_HANDLER(ViewHostMsg_TakeFocus, OnTakeFocus)
942     IPC_MESSAGE_HANDLER(ViewHostMsg_FocusedNodeChanged, OnFocusedNodeChanged)
943     IPC_MESSAGE_HANDLER(ViewHostMsg_ClosePage_ACK, OnClosePageACK)
944     IPC_MESSAGE_HANDLER(ViewHostMsg_DidZoomURL, OnDidZoomURL)
945 #if defined(OS_MACOSX) || defined(OS_ANDROID)
946     IPC_MESSAGE_HANDLER(ViewHostMsg_ShowPopup, OnShowPopup)
947     IPC_MESSAGE_HANDLER(ViewHostMsg_HidePopup, OnHidePopup)
948 #endif
949     IPC_MESSAGE_HANDLER(ViewHostMsg_RunFileChooser, OnRunFileChooser)
950     IPC_MESSAGE_HANDLER(ViewHostMsg_FocusedNodeTouched, OnFocusedNodeTouched)
951     // Have the super handle all other messages.
952     IPC_MESSAGE_UNHANDLED(
953         handled = RenderWidgetHostImpl::OnMessageReceived(msg))
954   IPC_END_MESSAGE_MAP()
955
956   return handled;
957 }
958
959 void RenderViewHostImpl::Init() {
960   RenderWidgetHostImpl::Init();
961 }
962
963 void RenderViewHostImpl::Shutdown() {
964   // If we are being run modally (see RunModal), then we need to cleanup.
965   if (run_modal_reply_msg_) {
966     Send(run_modal_reply_msg_);
967     run_modal_reply_msg_ = NULL;
968     RenderViewHostImpl* opener =
969         RenderViewHostImpl::FromID(GetProcess()->GetID(), run_modal_opener_id_);
970     if (opener) {
971       opener->StartHangMonitorTimeout(TimeDelta::FromMilliseconds(
972           hung_renderer_delay_ms_));
973       // Balance out the decrement when we got created.
974       opener->increment_in_flight_event_count();
975     }
976     run_modal_opener_id_ = MSG_ROUTING_NONE;
977   }
978
979   // We can't release the SessionStorageNamespace until our peer
980   // in the renderer has wound down.
981   if (GetProcess()->HasConnection()) {
982     RenderProcessHostImpl::ReleaseOnCloseACK(
983         GetProcess(),
984         delegate_->GetSessionStorageNamespaceMap(),
985         GetRoutingID());
986   }
987
988   RenderWidgetHostImpl::Shutdown();
989 }
990
991 bool RenderViewHostImpl::IsRenderView() const {
992   return true;
993 }
994
995 void RenderViewHostImpl::CreateNewWindow(
996     int route_id,
997     int main_frame_route_id,
998     const ViewHostMsg_CreateWindow_Params& params,
999     SessionStorageNamespace* session_storage_namespace) {
1000   ViewHostMsg_CreateWindow_Params validated_params(params);
1001   GetProcess()->FilterURL(false, &validated_params.target_url);
1002   GetProcess()->FilterURL(false, &validated_params.opener_url);
1003   GetProcess()->FilterURL(true, &validated_params.opener_security_origin);
1004
1005   delegate_->CreateNewWindow(
1006       GetProcess()->GetID(), route_id, main_frame_route_id, validated_params,
1007       session_storage_namespace);
1008 }
1009
1010 void RenderViewHostImpl::CreateNewWidget(int route_id,
1011                                      blink::WebPopupType popup_type) {
1012   delegate_->CreateNewWidget(GetProcess()->GetID(), route_id, popup_type);
1013 }
1014
1015 void RenderViewHostImpl::CreateNewFullscreenWidget(int route_id) {
1016   delegate_->CreateNewFullscreenWidget(GetProcess()->GetID(), route_id);
1017 }
1018
1019 void RenderViewHostImpl::OnShowView(int route_id,
1020                                     WindowOpenDisposition disposition,
1021                                     const gfx::Rect& initial_pos,
1022                                     bool user_gesture) {
1023   if (IsRVHStateActive(rvh_state_)) {
1024     delegate_->ShowCreatedWindow(
1025         route_id, disposition, initial_pos, user_gesture);
1026   }
1027   Send(new ViewMsg_Move_ACK(route_id));
1028 }
1029
1030 void RenderViewHostImpl::OnShowWidget(int route_id,
1031                                       const gfx::Rect& initial_pos) {
1032   if (IsRVHStateActive(rvh_state_))
1033     delegate_->ShowCreatedWidget(route_id, initial_pos);
1034   Send(new ViewMsg_Move_ACK(route_id));
1035 }
1036
1037 void RenderViewHostImpl::OnShowFullscreenWidget(int route_id) {
1038   if (IsRVHStateActive(rvh_state_))
1039     delegate_->ShowCreatedFullscreenWidget(route_id);
1040   Send(new ViewMsg_Move_ACK(route_id));
1041 }
1042
1043 void RenderViewHostImpl::OnRunModal(int opener_id, IPC::Message* reply_msg) {
1044   DCHECK(!run_modal_reply_msg_);
1045   run_modal_reply_msg_ = reply_msg;
1046   run_modal_opener_id_ = opener_id;
1047
1048   RecordAction(base::UserMetricsAction("ShowModalDialog"));
1049
1050   RenderViewHostImpl* opener =
1051       RenderViewHostImpl::FromID(GetProcess()->GetID(), run_modal_opener_id_);
1052   if (opener) {
1053     opener->StopHangMonitorTimeout();
1054     // The ack for the mouse down won't come until the dialog closes, so fake it
1055     // so that we don't get a timeout.
1056     opener->decrement_in_flight_event_count();
1057   }
1058
1059   // TODO(darin): Bug 1107929: Need to inform our delegate to show this view in
1060   // an app-modal fashion.
1061 }
1062
1063 void RenderViewHostImpl::OnRenderViewReady() {
1064   render_view_termination_status_ = base::TERMINATION_STATUS_STILL_RUNNING;
1065   SendScreenRects();
1066   WasResized();
1067   delegate_->RenderViewReady(this);
1068 }
1069
1070 void RenderViewHostImpl::OnRenderProcessGone(int status, int exit_code) {
1071   // Keep the termination status so we can get at it later when we
1072   // need to know why it died.
1073   render_view_termination_status_ =
1074       static_cast<base::TerminationStatus>(status);
1075
1076   // Reset frame tree state associated with this process.  This must happen
1077   // before RenderViewTerminated because observers expect the subframes of any
1078   // affected frames to be cleared first.
1079   delegate_->GetFrameTree()->RenderProcessGone(this);
1080
1081   // Our base class RenderWidgetHost needs to reset some stuff.
1082   RendererExited(render_view_termination_status_, exit_code);
1083
1084   delegate_->RenderViewTerminated(this,
1085                                   static_cast<base::TerminationStatus>(status),
1086                                   exit_code);
1087 }
1088
1089 void RenderViewHostImpl::OnUpdateState(int32 page_id, const PageState& state) {
1090   // Without this check, the renderer can trick the browser into using
1091   // filenames it can't access in a future session restore.
1092   if (!CanAccessFilesOfPageState(state)) {
1093     GetProcess()->ReceivedBadMessage();
1094     return;
1095   }
1096
1097   delegate_->UpdateState(this, page_id, state);
1098 }
1099
1100 void RenderViewHostImpl::OnUpdateTargetURL(int32 page_id, const GURL& url) {
1101   if (IsRVHStateActive(rvh_state_))
1102     delegate_->UpdateTargetURL(page_id, url);
1103
1104   // Send a notification back to the renderer that we are ready to
1105   // receive more target urls.
1106   Send(new ViewMsg_UpdateTargetURL_ACK(GetRoutingID()));
1107 }
1108
1109 void RenderViewHostImpl::OnUpdateInspectorSetting(
1110     const std::string& key, const std::string& value) {
1111   GetContentClient()->browser()->UpdateInspectorSetting(
1112       this, key, value);
1113 }
1114
1115 void RenderViewHostImpl::OnClose() {
1116   // If the renderer is telling us to close, it has already run the unload
1117   // events, and we can take the fast path.
1118   ClosePageIgnoringUnloadEvents();
1119 }
1120
1121 void RenderViewHostImpl::OnRequestMove(const gfx::Rect& pos) {
1122   if (IsRVHStateActive(rvh_state_))
1123     delegate_->RequestMove(pos);
1124   Send(new ViewMsg_Move_ACK(GetRoutingID()));
1125 }
1126
1127 void RenderViewHostImpl::OnDocumentAvailableInMainFrame(
1128     bool uses_temporary_zoom_level) {
1129   delegate_->DocumentAvailableInMainFrame(this);
1130
1131   if (!uses_temporary_zoom_level)
1132     return;
1133
1134   HostZoomMapImpl* host_zoom_map = static_cast<HostZoomMapImpl*>(
1135       HostZoomMap::GetForBrowserContext(GetProcess()->GetBrowserContext()));
1136   host_zoom_map->SetTemporaryZoomLevel(GetProcess()->GetID(),
1137                                        GetRoutingID(),
1138                                        host_zoom_map->GetDefaultZoomLevel());
1139 }
1140
1141 void RenderViewHostImpl::OnToggleFullscreen(bool enter_fullscreen) {
1142   DCHECK_CURRENTLY_ON(BrowserThread::UI);
1143   delegate_->ToggleFullscreenMode(enter_fullscreen);
1144   // We need to notify the contents that its fullscreen state has changed. This
1145   // is done as part of the resize message.
1146   WasResized();
1147 }
1148
1149 void RenderViewHostImpl::OnDidContentsPreferredSizeChange(
1150     const gfx::Size& new_size) {
1151   delegate_->UpdatePreferredSize(new_size);
1152 }
1153
1154 void RenderViewHostImpl::OnRenderAutoResized(const gfx::Size& new_size) {
1155   delegate_->ResizeDueToAutoResize(new_size);
1156 }
1157
1158 void RenderViewHostImpl::OnDidChangeScrollOffset() {
1159   if (view_)
1160     view_->ScrollOffsetChanged();
1161 }
1162
1163 void RenderViewHostImpl::OnRouteCloseEvent() {
1164   // Have the delegate route this to the active RenderViewHost.
1165   delegate_->RouteCloseEvent(this);
1166 }
1167
1168 void RenderViewHostImpl::OnRouteMessageEvent(
1169     const ViewMsg_PostMessage_Params& params) {
1170   // Give to the delegate to route to the active RenderViewHost.
1171   delegate_->RouteMessageEvent(this, params);
1172 }
1173
1174 void RenderViewHostImpl::OnStartDragging(
1175     const DropData& drop_data,
1176     WebDragOperationsMask drag_operations_mask,
1177     const SkBitmap& bitmap,
1178     const gfx::Vector2d& bitmap_offset_in_dip,
1179     const DragEventSourceInfo& event_info) {
1180   RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1181   if (!view)
1182     return;
1183
1184   DropData filtered_data(drop_data);
1185   RenderProcessHost* process = GetProcess();
1186   ChildProcessSecurityPolicyImpl* policy =
1187       ChildProcessSecurityPolicyImpl::GetInstance();
1188
1189   // Allow drag of Javascript URLs to enable bookmarklet drag to bookmark bar.
1190   if (!filtered_data.url.SchemeIs(url::kJavaScriptScheme))
1191     process->FilterURL(true, &filtered_data.url);
1192   process->FilterURL(false, &filtered_data.html_base_url);
1193   // Filter out any paths that the renderer didn't have access to. This prevents
1194   // the following attack on a malicious renderer:
1195   // 1. StartDragging IPC sent with renderer-specified filesystem paths that it
1196   //    doesn't have read permissions for.
1197   // 2. We initiate a native DnD operation.
1198   // 3. DnD operation immediately ends since mouse is not held down. DnD events
1199   //    still fire though, which causes read permissions to be granted to the
1200   //    renderer for any file paths in the drop.
1201   filtered_data.filenames.clear();
1202   for (std::vector<ui::FileInfo>::const_iterator it =
1203            drop_data.filenames.begin();
1204        it != drop_data.filenames.end();
1205        ++it) {
1206     if (policy->CanReadFile(GetProcess()->GetID(), it->path))
1207       filtered_data.filenames.push_back(*it);
1208   }
1209
1210   fileapi::FileSystemContext* file_system_context =
1211       BrowserContext::GetStoragePartition(
1212           GetProcess()->GetBrowserContext(),
1213           GetSiteInstance())->GetFileSystemContext();
1214   filtered_data.file_system_files.clear();
1215   for (size_t i = 0; i < drop_data.file_system_files.size(); ++i) {
1216     fileapi::FileSystemURL file_system_url =
1217         file_system_context->CrackURL(drop_data.file_system_files[i].url);
1218     if (policy->CanReadFileSystemFile(GetProcess()->GetID(), file_system_url))
1219       filtered_data.file_system_files.push_back(drop_data.file_system_files[i]);
1220   }
1221
1222   float scale = GetScaleFactorForView(GetView());
1223   gfx::ImageSkia image(gfx::ImageSkiaRep(bitmap, scale));
1224   view->StartDragging(filtered_data, drag_operations_mask, image,
1225       bitmap_offset_in_dip, event_info);
1226 }
1227
1228 void RenderViewHostImpl::OnUpdateDragCursor(WebDragOperation current_op) {
1229   RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1230   if (view)
1231     view->UpdateDragCursor(current_op);
1232 }
1233
1234 void RenderViewHostImpl::OnTargetDropACK() {
1235   NotificationService::current()->Notify(
1236       NOTIFICATION_RENDER_VIEW_HOST_DID_RECEIVE_DRAG_TARGET_DROP_ACK,
1237       Source<RenderViewHost>(this),
1238       NotificationService::NoDetails());
1239 }
1240
1241 void RenderViewHostImpl::OnTakeFocus(bool reverse) {
1242   RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1243   if (view)
1244     view->TakeFocus(reverse);
1245 }
1246
1247 void RenderViewHostImpl::OnFocusedNodeChanged(bool is_editable_node) {
1248   is_focused_element_editable_ = is_editable_node;
1249   if (view_)
1250     view_->FocusedNodeChanged(is_editable_node);
1251 #if defined(OS_WIN)
1252   if (!is_editable_node && virtual_keyboard_requested_) {
1253     virtual_keyboard_requested_ = false;
1254     BrowserThread::PostDelayedTask(
1255         BrowserThread::UI, FROM_HERE,
1256         base::Bind(base::IgnoreResult(&DismissVirtualKeyboardTask)),
1257         TimeDelta::FromMilliseconds(kVirtualKeyboardDisplayWaitTimeoutMs));
1258   }
1259 #endif
1260   NotificationService::current()->Notify(
1261       NOTIFICATION_FOCUS_CHANGED_IN_PAGE,
1262       Source<RenderViewHost>(this),
1263       Details<const bool>(&is_editable_node));
1264 }
1265
1266 void RenderViewHostImpl::OnUserGesture() {
1267   delegate_->OnUserGesture();
1268 }
1269
1270 void RenderViewHostImpl::OnClosePageACK() {
1271   decrement_in_flight_event_count();
1272   ClosePageIgnoringUnloadEvents();
1273 }
1274
1275 void RenderViewHostImpl::NotifyRendererUnresponsive() {
1276   delegate_->RendererUnresponsive(
1277       this, is_waiting_for_beforeunload_ack_, IsWaitingForUnloadACK());
1278 }
1279
1280 void RenderViewHostImpl::NotifyRendererResponsive() {
1281   delegate_->RendererResponsive(this);
1282 }
1283
1284 void RenderViewHostImpl::RequestToLockMouse(bool user_gesture,
1285                                             bool last_unlocked_by_target) {
1286   delegate_->RequestToLockMouse(user_gesture, last_unlocked_by_target);
1287 }
1288
1289 bool RenderViewHostImpl::IsFullscreen() const {
1290   return delegate_->IsFullscreenForCurrentTab();
1291 }
1292
1293 void RenderViewHostImpl::OnFocus() {
1294   // Note: We allow focus and blur from swapped out RenderViewHosts, even when
1295   // the active RenderViewHost is in a different BrowsingInstance (e.g., WebUI).
1296   delegate_->Activate();
1297 }
1298
1299 void RenderViewHostImpl::OnBlur() {
1300   delegate_->Deactivate();
1301 }
1302
1303 gfx::Rect RenderViewHostImpl::GetRootWindowResizerRect() const {
1304   return delegate_->GetRootWindowResizerRect();
1305 }
1306
1307 void RenderViewHostImpl::ForwardMouseEvent(
1308     const blink::WebMouseEvent& mouse_event) {
1309
1310   // We make a copy of the mouse event because
1311   // RenderWidgetHost::ForwardMouseEvent will delete |mouse_event|.
1312   blink::WebMouseEvent event_copy(mouse_event);
1313   RenderWidgetHostImpl::ForwardMouseEvent(event_copy);
1314
1315   switch (event_copy.type) {
1316     case WebInputEvent::MouseMove:
1317       delegate_->HandleMouseMove();
1318       break;
1319     case WebInputEvent::MouseLeave:
1320       delegate_->HandleMouseLeave();
1321       break;
1322     case WebInputEvent::MouseDown:
1323       delegate_->HandleMouseDown();
1324       break;
1325     case WebInputEvent::MouseWheel:
1326       if (ignore_input_events())
1327         delegate_->OnIgnoredUIEvent();
1328       break;
1329     case WebInputEvent::MouseUp:
1330       delegate_->HandleMouseUp();
1331     default:
1332       // For now, we don't care about the rest.
1333       break;
1334   }
1335 }
1336
1337 void RenderViewHostImpl::OnPointerEventActivate() {
1338   delegate_->HandlePointerActivate();
1339 }
1340
1341 void RenderViewHostImpl::ForwardKeyboardEvent(
1342     const NativeWebKeyboardEvent& key_event) {
1343   if (ignore_input_events()) {
1344     if (key_event.type == WebInputEvent::RawKeyDown)
1345       delegate_->OnIgnoredUIEvent();
1346     return;
1347   }
1348   RenderWidgetHostImpl::ForwardKeyboardEvent(key_event);
1349 }
1350
1351 #if defined(OS_ANDROID)
1352 void RenderViewHostImpl::DidSelectPopupMenuItems(
1353     const std::vector<int>& selected_indices) {
1354   Send(new ViewMsg_SelectPopupMenuItems(GetRoutingID(), false,
1355                                         selected_indices));
1356 }
1357
1358 void RenderViewHostImpl::DidCancelPopupMenu() {
1359   Send(new ViewMsg_SelectPopupMenuItems(GetRoutingID(), true,
1360                                         std::vector<int>()));
1361 }
1362 #endif
1363
1364 #if defined(OS_MACOSX)
1365 void RenderViewHostImpl::DidSelectPopupMenuItem(int selected_index) {
1366   Send(new ViewMsg_SelectPopupMenuItem(GetRoutingID(), selected_index));
1367 }
1368
1369 void RenderViewHostImpl::DidCancelPopupMenu() {
1370   Send(new ViewMsg_SelectPopupMenuItem(GetRoutingID(), -1));
1371 }
1372 #endif
1373
1374 bool RenderViewHostImpl::IsWaitingForUnloadACK() const {
1375   return rvh_state_ == STATE_WAITING_FOR_UNLOAD_ACK ||
1376          rvh_state_ == STATE_WAITING_FOR_CLOSE ||
1377          rvh_state_ == STATE_PENDING_SHUTDOWN ||
1378          rvh_state_ == STATE_PENDING_SWAP_OUT;
1379 }
1380
1381 void RenderViewHostImpl::OnTextSurroundingSelectionResponse(
1382     const base::string16& content,
1383     size_t start_offset,
1384     size_t end_offset) {
1385   if (!view_)
1386     return;
1387   view_->OnTextSurroundingSelectionResponse(content, start_offset, end_offset);
1388 }
1389
1390 void RenderViewHostImpl::ExitFullscreen() {
1391   RejectMouseLockOrUnlockIfNecessary();
1392   // Notify delegate_ and renderer of fullscreen state change.
1393   OnToggleFullscreen(false);
1394 }
1395
1396 WebPreferences RenderViewHostImpl::GetWebkitPreferences() {
1397   if (!web_preferences_.get()) {
1398     OnWebkitPreferencesChanged();
1399   }
1400   return *web_preferences_;
1401 }
1402
1403 void RenderViewHostImpl::DisownOpener() {
1404   // This should only be called when swapped out.
1405   DCHECK(IsSwappedOut());
1406
1407   Send(new ViewMsg_DisownOpener(GetRoutingID()));
1408 }
1409
1410 void RenderViewHostImpl::UpdateWebkitPreferences(const WebPreferences& prefs) {
1411   web_preferences_.reset(new WebPreferences(prefs));
1412   Send(new ViewMsg_UpdateWebPreferences(GetRoutingID(), prefs));
1413 }
1414
1415 void RenderViewHostImpl::OnWebkitPreferencesChanged() {
1416   // This is defensive code to avoid infinite loops due to code run inside
1417   // UpdateWebkitPreferences() accidentally updating more preferences and thus
1418   // calling back into this code. See crbug.com/398751 for one past example.
1419   if (updating_web_preferences_)
1420     return;
1421   updating_web_preferences_ = true;
1422   UpdateWebkitPreferences(delegate_->ComputeWebkitPrefs());
1423   updating_web_preferences_ = false;
1424 }
1425
1426 void RenderViewHostImpl::GetAudioOutputControllers(
1427     const GetAudioOutputControllersCallback& callback) const {
1428   AudioRendererHost* audio_host =
1429       static_cast<RenderProcessHostImpl*>(GetProcess())->audio_renderer_host();
1430   audio_host->GetOutputControllers(GetRoutingID(), callback);
1431 }
1432
1433 void RenderViewHostImpl::ClearFocusedElement() {
1434   is_focused_element_editable_ = false;
1435   Send(new ViewMsg_ClearFocusedElement(GetRoutingID()));
1436 }
1437
1438 bool RenderViewHostImpl::IsFocusedElementEditable() {
1439   return is_focused_element_editable_;
1440 }
1441
1442 void RenderViewHostImpl::Zoom(PageZoom zoom) {
1443   Send(new ViewMsg_Zoom(GetRoutingID(), zoom));
1444 }
1445
1446 void RenderViewHostImpl::DisableScrollbarsForThreshold(const gfx::Size& size) {
1447   Send(new ViewMsg_DisableScrollbarsForSmallWindows(GetRoutingID(), size));
1448 }
1449
1450 void RenderViewHostImpl::EnablePreferredSizeMode() {
1451   Send(new ViewMsg_EnablePreferredSizeChangedMode(GetRoutingID()));
1452 }
1453
1454 void RenderViewHostImpl::EnableAutoResize(const gfx::Size& min_size,
1455                                           const gfx::Size& max_size) {
1456   SetShouldAutoResize(true);
1457   Send(new ViewMsg_EnableAutoResize(GetRoutingID(), min_size, max_size));
1458 }
1459
1460 void RenderViewHostImpl::DisableAutoResize(const gfx::Size& new_size) {
1461   SetShouldAutoResize(false);
1462   Send(new ViewMsg_DisableAutoResize(GetRoutingID(), new_size));
1463   if (!new_size.IsEmpty())
1464     GetView()->SetSize(new_size);
1465 }
1466
1467 void RenderViewHostImpl::CopyImageAt(int x, int y) {
1468   Send(new ViewMsg_CopyImageAt(GetRoutingID(), x, y));
1469 }
1470
1471 void RenderViewHostImpl::SaveImageAt(int x, int y) {
1472   Send(new ViewMsg_SaveImageAt(GetRoutingID(), x, y));
1473 }
1474
1475 void RenderViewHostImpl::ExecuteMediaPlayerActionAtLocation(
1476   const gfx::Point& location, const blink::WebMediaPlayerAction& action) {
1477   Send(new ViewMsg_MediaPlayerActionAt(GetRoutingID(), location, action));
1478 }
1479
1480 void RenderViewHostImpl::ExecutePluginActionAtLocation(
1481   const gfx::Point& location, const blink::WebPluginAction& action) {
1482   Send(new ViewMsg_PluginActionAt(GetRoutingID(), location, action));
1483 }
1484
1485 void RenderViewHostImpl::NotifyMoveOrResizeStarted() {
1486   Send(new ViewMsg_MoveOrResizeStarted(GetRoutingID()));
1487 }
1488
1489 void RenderViewHostImpl::OnDidZoomURL(double zoom_level,
1490                                       const GURL& url) {
1491   HostZoomMapImpl* host_zoom_map = static_cast<HostZoomMapImpl*>(
1492       HostZoomMap::GetForBrowserContext(GetProcess()->GetBrowserContext()));
1493
1494   host_zoom_map->SetZoomLevelForView(GetProcess()->GetID(),
1495                                      GetRoutingID(),
1496                                      zoom_level,
1497                                      net::GetHostOrSpecFromURL(url));
1498 }
1499
1500 void RenderViewHostImpl::OnRunFileChooser(const FileChooserParams& params) {
1501   delegate_->RunFileChooser(this, params);
1502 }
1503
1504 void RenderViewHostImpl::OnFocusedNodeTouched(bool editable) {
1505 #if defined(OS_WIN)
1506   if (editable) {
1507     virtual_keyboard_requested_ = base::win::DisplayVirtualKeyboard();
1508   } else {
1509     virtual_keyboard_requested_ = false;
1510     base::win::DismissVirtualKeyboard();
1511   }
1512 #endif
1513 }
1514
1515 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1516 void RenderViewHostImpl::OnShowPopup(
1517     const ViewHostMsg_ShowPopup_Params& params) {
1518   RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1519   if (view) {
1520     view->ShowPopupMenu(params.bounds,
1521                         params.item_height,
1522                         params.item_font_size,
1523                         params.selected_item,
1524                         params.popup_items,
1525                         params.right_aligned,
1526                         params.allow_multiple_selection);
1527   }
1528 }
1529
1530 void RenderViewHostImpl::OnHidePopup() {
1531   RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1532   if (view)
1533     view->HidePopupMenu();
1534 }
1535 #endif
1536
1537 void RenderViewHostImpl::SetState(RenderViewHostImplState rvh_state) {
1538   // We update the number of RenderViews in a SiteInstance when the
1539   // swapped out status of this RenderView gets flipped to/from live.
1540   if (!IsRVHStateActive(rvh_state_) && IsRVHStateActive(rvh_state))
1541     instance_->increment_active_view_count();
1542   else if (IsRVHStateActive(rvh_state_) && !IsRVHStateActive(rvh_state))
1543     instance_->decrement_active_view_count();
1544
1545   // Whenever we change the RVH state to and from live or swapped out state, we
1546   // should not be waiting for beforeunload or unload acks.  We clear them here
1547   // to be safe, since they can cause navigations to be ignored in OnNavigate.
1548   if (rvh_state == STATE_DEFAULT ||
1549       rvh_state == STATE_SWAPPED_OUT ||
1550       rvh_state_ == STATE_DEFAULT ||
1551       rvh_state_ == STATE_SWAPPED_OUT) {
1552     is_waiting_for_beforeunload_ack_ = false;
1553   }
1554   rvh_state_ = rvh_state;
1555
1556 }
1557
1558 bool RenderViewHostImpl::CanAccessFilesOfPageState(
1559     const PageState& state) const {
1560   ChildProcessSecurityPolicyImpl* policy =
1561       ChildProcessSecurityPolicyImpl::GetInstance();
1562
1563   const std::vector<base::FilePath>& file_paths = state.GetReferencedFiles();
1564   for (std::vector<base::FilePath>::const_iterator file = file_paths.begin();
1565        file != file_paths.end(); ++file) {
1566     if (!policy->CanReadFile(GetProcess()->GetID(), *file))
1567       return false;
1568   }
1569   return true;
1570 }
1571
1572 void RenderViewHostImpl::AttachToFrameTree() {
1573   FrameTree* frame_tree = delegate_->GetFrameTree();
1574
1575   frame_tree->ResetForMainFrameSwap();
1576 }
1577
1578 void RenderViewHostImpl::SelectWordAroundCaret() {
1579   Send(new ViewMsg_SelectWordAroundCaret(GetRoutingID()));
1580 }
1581
1582 }  // namespace content