1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/renderer_host/render_view_host_impl.h"
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"
86 #if defined(OS_MACOSX)
87 #include "content/browser/renderer_host/popup_menu_helper_mac.h"
89 #include "base/win/win_util.h"
92 #if defined(ENABLE_BROWSER_CDMS)
93 #include "content/browser/media/media_web_contents_observer.h"
96 #if defined(OS_TIZEN) && defined(ENABLE_MURPHY)
97 #include "xwalk/tizen/browser/media/media_webcontents_observer.h"
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;
114 const int kVirtualKeyboardDisplayWaitTimeoutMs = 100;
115 const int kMaxVirtualKeyboardDisplayRetries = 5;
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;
129 virtual_keyboard_display_retries = 0;
138 const int RenderViewHostImpl::kUnloadTimeoutMS = 1000;
140 ///////////////////////////////////////////////////////////////////////////////
141 // RenderViewHost, public:
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)
154 RenderViewHost* RenderViewHost::FromID(int render_process_id,
155 int render_view_id) {
156 return RenderViewHostImpl::FromID(render_process_id, render_view_id);
160 RenderViewHost* RenderViewHost::From(RenderWidgetHost* rwh) {
161 DCHECK(rwh->IsRenderView());
162 return static_cast<RenderViewHostImpl*>(RenderWidgetHostImpl::From(rwh));
165 ///////////////////////////////////////////////////////////////////////////////
166 // RenderViewHostImpl, public:
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())
175 return static_cast<RenderViewHostImpl*>(RenderWidgetHostImpl::From(widget));
178 RenderViewHostImpl::RenderViewHostImpl(
179 SiteInstance* instance,
180 RenderViewHostDelegate* delegate,
181 RenderWidgetHostDelegate* widget_delegate,
183 int main_frame_routing_id,
186 : RenderWidgetHostImpl(widget_delegate,
187 instance->GetProcess(),
190 frames_ref_count_(0),
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),
204 is_focused_element_editable_(false),
205 updating_web_preferences_(false) {
206 DCHECK(instance_.get());
207 CHECK(delegate_); // http://crbug.com/82827
209 GetProcess()->EnableSendQueue();
212 rvh_state_ = STATE_SWAPPED_OUT;
214 rvh_state_ = STATE_DEFAULT;
215 instance_->increment_active_view_count();
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()));
226 #if defined(ENABLE_BROWSER_CDMS)
227 media_web_contents_observer_.reset(new MediaWebContentsObserver(this));
230 #if defined(OS_TIZEN) && defined(ENABLE_MURPHY)
231 media_webcontents_observer_.reset(new tizen::MediaWebContentsObserver(this));
234 unload_event_monitor_timeout_.reset(new TimeoutMonitor(base::Bind(
235 &RenderViewHostImpl::OnSwappedOut, weak_factory_.GetWeakPtr(), true)));
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()));
247 delegate_->RenderViewDeleted(this);
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();
255 RenderViewHostDelegate* RenderViewHostImpl::GetDelegate() const {
259 SiteInstance* RenderViewHostImpl::GetSiteInstance() const {
260 return instance_.get();
263 bool RenderViewHostImpl::CreateRenderView(
264 const base::string16& frame_name,
268 bool window_was_created_with_opener) {
269 TRACE_EVENT0("renderer_host", "RenderViewHostImpl::CreateRenderView");
270 DCHECK(!IsRenderViewLive()) << "Creating view twice";
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())
278 DCHECK(GetProcess()->HasConnection());
279 DCHECK(GetProcess()->GetBrowserContext());
281 renderer_initialized_ = true;
283 GpuSurfaceTracker::Get()->SetSurfaceHandle(
284 surface_id(), GetCompositingSurface());
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;
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(¶ms.screen_info);
312 Send(new ViewMsg_New(params));
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);
325 bool RenderViewHostImpl::IsRenderViewLive() const {
326 return GetProcess()->HasConnection() && renderer_initialized_;
329 void RenderViewHostImpl::SyncRendererPrefs() {
330 Send(new ViewMsg_SetRendererPrefs(GetRoutingID(),
331 delegate_->GetRendererPrefs(
332 GetProcess()->GetBrowserContext())));
335 WebPreferences RenderViewHostImpl::ComputeWebkitPrefs(const GURL& url) {
336 TRACE_EVENT0("browser", "RenderViewHostImpl::GetWebkitPrefs");
337 WebPreferences prefs;
339 const base::CommandLine& command_line =
340 *base::CommandLine::ForCurrentProcess();
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);
349 !command_line.HasSwitch(switches::kDisableJava);
351 prefs.remote_fonts_enabled =
352 !command_line.HasSwitch(switches::kDisableRemoteFonts);
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);
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);
370 prefs.experimental_webgl_enabled =
371 GpuProcessHost::gpu_enabled() &&
372 !command_line.HasSwitch(switches::kDisable3DAPIs) &&
373 !command_line.HasSwitch(switches::kDisableExperimentalWebGL);
375 prefs.pepper_3d_enabled =
376 !command_line.HasSwitch(switches::kDisablePepper3d);
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);
388 prefs.allow_file_access_from_file_urls =
389 command_line.HasSwitch(switches::kAllowFileAccessFromFiles);
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;
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);
412 if (IsPinchVirtualViewportEnabled()) {
413 prefs.pinch_virtual_viewport_enabled = true;
414 prefs.pinch_overlay_scrollbar_thickness = 10;
416 prefs.use_solid_color_scrollbars = ui::IsOverlayScrollbarEnabled();
418 #if defined(OS_ANDROID)
419 prefs.user_gesture_required_for_media_playback = !command_line.HasSwitch(
420 switches::kDisableGestureRequirementForMediaPlayback);
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;
430 prefs.pointer_events_max_touch_points = ui::MaxTouchPoints();
432 prefs.touch_adjustment_enabled =
433 !command_line.HasSwitch(switches::kDisableTouchAdjustment);
435 #if defined(OS_MACOSX) || defined(OS_CHROMEOS)
436 bool default_enable_scroll_animator = true;
438 bool default_enable_scroll_animator = false;
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;
446 // Certain GPU features might have been blacklisted.
447 GpuDataManagerImpl::GetInstance()->UpdateRendererWebPrefs(&prefs);
449 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
450 GetProcess()->GetID())) {
451 prefs.loads_images_automatically = true;
452 prefs.javascript_enabled = true;
455 prefs.connection_type = net::NetworkChangeNotifier::GetConnectionType();
457 prefs.connection_type != net::NetworkChangeNotifier::CONNECTION_NONE;
459 prefs.number_of_cpu_cores = base::SysInfo::NumberOfProcessors();
461 prefs.viewport_meta_enabled =
462 command_line.HasSwitch(switches::kEnableViewportMeta);
464 prefs.viewport_enabled =
465 command_line.HasSwitch(switches::kEnableViewport) ||
466 prefs.viewport_meta_enabled;
468 prefs.main_frame_resizes_are_orientation_changes =
469 command_line.HasSwitch(switches::kMainFrameResizesAreOrientationChanges);
471 prefs.deferred_image_decoding_enabled =
472 command_line.HasSwitch(switches::kEnableDeferredImageDecoding) ||
473 content::IsImplSidePaintingEnabled();
475 prefs.spatial_navigation_enabled = command_line.HasSwitch(
476 switches::kEnableSpatialNavigation);
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;
486 prefs.v8_cache_options = V8_CACHE_OPTIONS_OFF;
490 GetContentClient()->browser()->OverrideWebkitPrefs(this, url, &prefs);
494 void RenderViewHostImpl::Navigate(const FrameMsg_Navigate_Params& params) {
495 TRACE_EVENT0("renderer_host", "RenderViewHostImpl::Navigate");
496 delegate_->GetFrameTree()->GetMainFrame()->Navigate(params);
499 void RenderViewHostImpl::NavigateToURL(const GURL& url) {
500 delegate_->GetFrameTree()->GetMainFrame()->NavigateToURL(url);
503 void RenderViewHostImpl::SuppressDialogsUntilSwapOut() {
504 Send(new ViewMsg_SuppressDialogsUntilSwapOut(GetRoutingID()));
507 void RenderViewHostImpl::OnSwappedOut(bool timed_out) {
508 // Ignore spurious swap out ack.
509 if (!IsWaitingForUnloadACK())
511 unload_event_monitor_timeout_->Stop();
513 base::ProcessHandle process_handle = GetProcess()->GetHandle();
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())
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.
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
543 UMA_HISTOGRAM_PERCENTAGE(
544 "BrowserRenderProcessHost.ChildKillsUnresponsive", 1);
549 switch (rvh_state_) {
550 case STATE_WAITING_FOR_UNLOAD_ACK:
551 SetState(STATE_WAITING_FOR_COMMIT);
553 case STATE_PENDING_SWAP_OUT:
554 SetState(STATE_SWAPPED_OUT);
556 case STATE_PENDING_SHUTDOWN:
557 DCHECK(!pending_shutdown_on_swap_out_.is_null());
558 pending_shutdown_on_swap_out_.Run();
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);
585 void RenderViewHostImpl::SetPendingShutdown(const base::Closure& on_swap_out) {
586 pending_shutdown_on_swap_out_ = on_swap_out;
587 SetState(STATE_PENDING_SHUTDOWN);
590 void RenderViewHostImpl::ClosePage() {
591 SetState(STATE_WAITING_FOR_CLOSE);
592 StartHangMonitorTimeout(TimeDelta::FromMilliseconds(kUnloadTimeoutMS));
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();
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());
607 Send(new ViewMsg_ClosePage(GetRoutingID()));
609 // This RenderViewHost doesn't have a live renderer, so just skip the unload
610 // event and close the page.
611 ClosePageIgnoringUnloadEvents();
615 void RenderViewHostImpl::ClosePageIgnoringUnloadEvents() {
616 StopHangMonitorTimeout();
617 is_waiting_for_beforeunload_ack_ = false;
619 sudden_termination_allowed_ = true;
620 delegate_->Close(this);
623 #if defined(OS_ANDROID)
624 void RenderViewHostImpl::ActivateNearestFindResult(int request_id,
627 Send(new InputMsg_ActivateNearestFindResult(GetRoutingID(),
631 void RenderViewHostImpl::RequestFindMatchRects(int current_version) {
632 Send(new ViewMsg_FindMatchRects(GetRoutingID(), current_version));
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,
642 const int renderer_id = GetProcess()->GetID();
643 ChildProcessSecurityPolicyImpl* policy =
644 ChildProcessSecurityPolicyImpl::GetInstance();
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();
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();
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.
667 // Make sure we have the same display_name as the one we register.
668 if (iter->display_name.empty()) {
670 files.AddPath(iter->path, &name);
671 iter->display_name = base::FilePath::FromUTF8Unsafe(name);
673 files.AddPathWithName(iter->path, iter->display_name.AsUTF8Unsafe());
676 policy->GrantRequestSpecificFileURL(renderer_id,
677 net::FilePathToFileURL(iter->path));
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);
689 fileapi::IsolatedContext* isolated_context =
690 fileapi::IsolatedContext::GetInstance();
691 DCHECK(isolated_context);
692 std::string filesystem_id = isolated_context->RegisterDraggedFileSystem(
694 if (!filesystem_id.empty()) {
695 // Grant the permission iff the ID is valid.
696 policy->GrantReadFileSystem(renderer_id, filesystem_id);
698 filtered_data.filesystem_id = base::UTF8ToUTF16(filesystem_id);
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);
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(), ®ister_name);
712 policy->GrantReadFileSystem(renderer_id, filesystem_id);
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(),
720 std::string()).append(register_name));
723 Send(new DragMsg_TargetDragEnter(GetRoutingID(), filtered_data, client_pt,
724 screen_pt, operations_allowed,
728 void RenderViewHostImpl::DragTargetDragOver(
729 const gfx::Point& client_pt,
730 const gfx::Point& screen_pt,
731 WebDragOperationsMask operations_allowed,
733 Send(new DragMsg_TargetDragOver(GetRoutingID(), client_pt, screen_pt,
734 operations_allowed, key_modifiers));
737 void RenderViewHostImpl::DragTargetDragLeave() {
738 Send(new DragMsg_TargetDragLeave(GetRoutingID()));
741 void RenderViewHostImpl::DragTargetDrop(
742 const gfx::Point& client_pt,
743 const gfx::Point& screen_pt,
745 Send(new DragMsg_TargetDrop(GetRoutingID(), client_pt, screen_pt,
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),
758 void RenderViewHostImpl::DragSourceSystemDragEnded() {
759 Send(new DragMsg_SourceSystemDragEnded(GetRoutingID()));
762 RenderFrameHost* RenderViewHostImpl::GetMainFrame() {
763 return RenderFrameHost::FromID(GetProcess()->GetID(), main_frame_routing_id_);
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.";
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))
790 if (bindings_flags & BINDINGS_POLICY_WEB_UI) {
791 ChildProcessSecurityPolicyImpl::GetInstance()->GrantWebUIBindings(
792 GetProcess()->GetID());
795 enabled_bindings_ |= bindings_flags;
796 if (renderer_initialized_)
797 Send(new ViewMsg_AllowBindings(GetRoutingID(), enabled_bindings_));
800 int RenderViewHostImpl::GetEnabledBindings() const {
801 return enabled_bindings_;
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));
814 base::UserMetricsAction("BindingsMismatchTerminate_RVH_WebUI"));
816 GetProcess()->GetHandle(), content::RESULT_CODE_KILLED, false);
820 void RenderViewHostImpl::GotFocus() {
821 RenderWidgetHostImpl::GotFocus(); // Notifies the renderer it got focus.
823 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
828 void RenderViewHostImpl::LostCapture() {
829 RenderWidgetHostImpl::LostCapture();
830 delegate_->LostCapture();
833 void RenderViewHostImpl::LostMouseLock() {
834 RenderWidgetHostImpl::LostMouseLock();
835 delegate_->LostMouseLock();
838 void RenderViewHostImpl::SetInitialFocus(bool reverse) {
839 Send(new ViewMsg_SetInitialFocus(GetRoutingID(), reverse));
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);
852 ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
853 GetProcess()->GetID(), file.local_path);
856 Send(new ViewMsg_RunFileChooserResponse(GetRoutingID(), files));
859 void RenderViewHostImpl::DirectoryEnumerationFinished(
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);
868 Send(new ViewMsg_EnumerateDirectoryResponse(GetRoutingID(),
873 void RenderViewHostImpl::LoadStateChanged(
875 const net::LoadStateWithParam& load_state,
876 uint64 upload_position,
877 uint64 upload_size) {
878 delegate_->LoadStateChanged(url, load_state, upload_position, upload_size);
881 bool RenderViewHostImpl::SuddenTerminationAllowed() const {
882 return sudden_termination_allowed_ ||
883 GetProcess()->SuddenTerminationAllowed();
886 ///////////////////////////////////////////////////////////////////////////////
887 // RenderViewHostImpl, IPC message handlers:
889 bool RenderViewHostImpl::OnMessageReceived(const IPC::Message& msg) {
890 if (!BrowserMessageFilter::CheckCanDispatchOnUI(msg, this))
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.
901 IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
902 reply->set_reply_error();
905 // Don't continue looking for someone to handle it.
910 if (delegate_->OnMessageReceived(this, msg))
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,
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)
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()
959 void RenderViewHostImpl::Init() {
960 RenderWidgetHostImpl::Init();
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_);
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();
976 run_modal_opener_id_ = MSG_ROUTING_NONE;
979 // We can't release the SessionStorageNamespace until our peer
980 // in the renderer has wound down.
981 if (GetProcess()->HasConnection()) {
982 RenderProcessHostImpl::ReleaseOnCloseACK(
984 delegate_->GetSessionStorageNamespaceMap(),
988 RenderWidgetHostImpl::Shutdown();
991 bool RenderViewHostImpl::IsRenderView() const {
995 void RenderViewHostImpl::CreateNewWindow(
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);
1005 delegate_->CreateNewWindow(
1006 GetProcess()->GetID(), route_id, main_frame_route_id, validated_params,
1007 session_storage_namespace);
1010 void RenderViewHostImpl::CreateNewWidget(int route_id,
1011 blink::WebPopupType popup_type) {
1012 delegate_->CreateNewWidget(GetProcess()->GetID(), route_id, popup_type);
1015 void RenderViewHostImpl::CreateNewFullscreenWidget(int route_id) {
1016 delegate_->CreateNewFullscreenWidget(GetProcess()->GetID(), route_id);
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);
1027 Send(new ViewMsg_Move_ACK(route_id));
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));
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));
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;
1048 RecordAction(base::UserMetricsAction("ShowModalDialog"));
1050 RenderViewHostImpl* opener =
1051 RenderViewHostImpl::FromID(GetProcess()->GetID(), run_modal_opener_id_);
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();
1059 // TODO(darin): Bug 1107929: Need to inform our delegate to show this view in
1060 // an app-modal fashion.
1063 void RenderViewHostImpl::OnRenderViewReady() {
1064 render_view_termination_status_ = base::TERMINATION_STATUS_STILL_RUNNING;
1067 delegate_->RenderViewReady(this);
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);
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);
1081 // Our base class RenderWidgetHost needs to reset some stuff.
1082 RendererExited(render_view_termination_status_, exit_code);
1084 delegate_->RenderViewTerminated(this,
1085 static_cast<base::TerminationStatus>(status),
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();
1097 delegate_->UpdateState(this, page_id, state);
1100 void RenderViewHostImpl::OnUpdateTargetURL(int32 page_id, const GURL& url) {
1101 if (IsRVHStateActive(rvh_state_))
1102 delegate_->UpdateTargetURL(page_id, url);
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()));
1109 void RenderViewHostImpl::OnUpdateInspectorSetting(
1110 const std::string& key, const std::string& value) {
1111 GetContentClient()->browser()->UpdateInspectorSetting(
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();
1121 void RenderViewHostImpl::OnRequestMove(const gfx::Rect& pos) {
1122 if (IsRVHStateActive(rvh_state_))
1123 delegate_->RequestMove(pos);
1124 Send(new ViewMsg_Move_ACK(GetRoutingID()));
1127 void RenderViewHostImpl::OnDocumentAvailableInMainFrame(
1128 bool uses_temporary_zoom_level) {
1129 delegate_->DocumentAvailableInMainFrame(this);
1131 if (!uses_temporary_zoom_level)
1134 HostZoomMapImpl* host_zoom_map = static_cast<HostZoomMapImpl*>(
1135 HostZoomMap::GetForBrowserContext(GetProcess()->GetBrowserContext()));
1136 host_zoom_map->SetTemporaryZoomLevel(GetProcess()->GetID(),
1138 host_zoom_map->GetDefaultZoomLevel());
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.
1149 void RenderViewHostImpl::OnDidContentsPreferredSizeChange(
1150 const gfx::Size& new_size) {
1151 delegate_->UpdatePreferredSize(new_size);
1154 void RenderViewHostImpl::OnRenderAutoResized(const gfx::Size& new_size) {
1155 delegate_->ResizeDueToAutoResize(new_size);
1158 void RenderViewHostImpl::OnDidChangeScrollOffset() {
1160 view_->ScrollOffsetChanged();
1163 void RenderViewHostImpl::OnRouteCloseEvent() {
1164 // Have the delegate route this to the active RenderViewHost.
1165 delegate_->RouteCloseEvent(this);
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);
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();
1184 DropData filtered_data(drop_data);
1185 RenderProcessHost* process = GetProcess();
1186 ChildProcessSecurityPolicyImpl* policy =
1187 ChildProcessSecurityPolicyImpl::GetInstance();
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();
1206 if (policy->CanReadFile(GetProcess()->GetID(), it->path))
1207 filtered_data.filenames.push_back(*it);
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]);
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);
1228 void RenderViewHostImpl::OnUpdateDragCursor(WebDragOperation current_op) {
1229 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1231 view->UpdateDragCursor(current_op);
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());
1241 void RenderViewHostImpl::OnTakeFocus(bool reverse) {
1242 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1244 view->TakeFocus(reverse);
1247 void RenderViewHostImpl::OnFocusedNodeChanged(bool is_editable_node) {
1248 is_focused_element_editable_ = is_editable_node;
1250 view_->FocusedNodeChanged(is_editable_node);
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));
1260 NotificationService::current()->Notify(
1261 NOTIFICATION_FOCUS_CHANGED_IN_PAGE,
1262 Source<RenderViewHost>(this),
1263 Details<const bool>(&is_editable_node));
1266 void RenderViewHostImpl::OnUserGesture() {
1267 delegate_->OnUserGesture();
1270 void RenderViewHostImpl::OnClosePageACK() {
1271 decrement_in_flight_event_count();
1272 ClosePageIgnoringUnloadEvents();
1275 void RenderViewHostImpl::NotifyRendererUnresponsive() {
1276 delegate_->RendererUnresponsive(
1277 this, is_waiting_for_beforeunload_ack_, IsWaitingForUnloadACK());
1280 void RenderViewHostImpl::NotifyRendererResponsive() {
1281 delegate_->RendererResponsive(this);
1284 void RenderViewHostImpl::RequestToLockMouse(bool user_gesture,
1285 bool last_unlocked_by_target) {
1286 delegate_->RequestToLockMouse(user_gesture, last_unlocked_by_target);
1289 bool RenderViewHostImpl::IsFullscreen() const {
1290 return delegate_->IsFullscreenForCurrentTab();
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();
1299 void RenderViewHostImpl::OnBlur() {
1300 delegate_->Deactivate();
1303 gfx::Rect RenderViewHostImpl::GetRootWindowResizerRect() const {
1304 return delegate_->GetRootWindowResizerRect();
1307 void RenderViewHostImpl::ForwardMouseEvent(
1308 const blink::WebMouseEvent& mouse_event) {
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);
1315 switch (event_copy.type) {
1316 case WebInputEvent::MouseMove:
1317 delegate_->HandleMouseMove();
1319 case WebInputEvent::MouseLeave:
1320 delegate_->HandleMouseLeave();
1322 case WebInputEvent::MouseDown:
1323 delegate_->HandleMouseDown();
1325 case WebInputEvent::MouseWheel:
1326 if (ignore_input_events())
1327 delegate_->OnIgnoredUIEvent();
1329 case WebInputEvent::MouseUp:
1330 delegate_->HandleMouseUp();
1332 // For now, we don't care about the rest.
1337 void RenderViewHostImpl::OnPointerEventActivate() {
1338 delegate_->HandlePointerActivate();
1341 void RenderViewHostImpl::ForwardKeyboardEvent(
1342 const NativeWebKeyboardEvent& key_event) {
1343 if (ignore_input_events()) {
1344 if (key_event.type == WebInputEvent::RawKeyDown)
1345 delegate_->OnIgnoredUIEvent();
1348 RenderWidgetHostImpl::ForwardKeyboardEvent(key_event);
1351 #if defined(OS_ANDROID)
1352 void RenderViewHostImpl::DidSelectPopupMenuItems(
1353 const std::vector<int>& selected_indices) {
1354 Send(new ViewMsg_SelectPopupMenuItems(GetRoutingID(), false,
1358 void RenderViewHostImpl::DidCancelPopupMenu() {
1359 Send(new ViewMsg_SelectPopupMenuItems(GetRoutingID(), true,
1360 std::vector<int>()));
1364 #if defined(OS_MACOSX)
1365 void RenderViewHostImpl::DidSelectPopupMenuItem(int selected_index) {
1366 Send(new ViewMsg_SelectPopupMenuItem(GetRoutingID(), selected_index));
1369 void RenderViewHostImpl::DidCancelPopupMenu() {
1370 Send(new ViewMsg_SelectPopupMenuItem(GetRoutingID(), -1));
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;
1381 void RenderViewHostImpl::OnTextSurroundingSelectionResponse(
1382 const base::string16& content,
1383 size_t start_offset,
1384 size_t end_offset) {
1387 view_->OnTextSurroundingSelectionResponse(content, start_offset, end_offset);
1390 void RenderViewHostImpl::ExitFullscreen() {
1391 RejectMouseLockOrUnlockIfNecessary();
1392 // Notify delegate_ and renderer of fullscreen state change.
1393 OnToggleFullscreen(false);
1396 WebPreferences RenderViewHostImpl::GetWebkitPreferences() {
1397 if (!web_preferences_.get()) {
1398 OnWebkitPreferencesChanged();
1400 return *web_preferences_;
1403 void RenderViewHostImpl::DisownOpener() {
1404 // This should only be called when swapped out.
1405 DCHECK(IsSwappedOut());
1407 Send(new ViewMsg_DisownOpener(GetRoutingID()));
1410 void RenderViewHostImpl::UpdateWebkitPreferences(const WebPreferences& prefs) {
1411 web_preferences_.reset(new WebPreferences(prefs));
1412 Send(new ViewMsg_UpdateWebPreferences(GetRoutingID(), prefs));
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_)
1421 updating_web_preferences_ = true;
1422 UpdateWebkitPreferences(delegate_->ComputeWebkitPrefs());
1423 updating_web_preferences_ = false;
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);
1433 void RenderViewHostImpl::ClearFocusedElement() {
1434 is_focused_element_editable_ = false;
1435 Send(new ViewMsg_ClearFocusedElement(GetRoutingID()));
1438 bool RenderViewHostImpl::IsFocusedElementEditable() {
1439 return is_focused_element_editable_;
1442 void RenderViewHostImpl::Zoom(PageZoom zoom) {
1443 Send(new ViewMsg_Zoom(GetRoutingID(), zoom));
1446 void RenderViewHostImpl::DisableScrollbarsForThreshold(const gfx::Size& size) {
1447 Send(new ViewMsg_DisableScrollbarsForSmallWindows(GetRoutingID(), size));
1450 void RenderViewHostImpl::EnablePreferredSizeMode() {
1451 Send(new ViewMsg_EnablePreferredSizeChangedMode(GetRoutingID()));
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));
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);
1467 void RenderViewHostImpl::CopyImageAt(int x, int y) {
1468 Send(new ViewMsg_CopyImageAt(GetRoutingID(), x, y));
1471 void RenderViewHostImpl::SaveImageAt(int x, int y) {
1472 Send(new ViewMsg_SaveImageAt(GetRoutingID(), x, y));
1475 void RenderViewHostImpl::ExecuteMediaPlayerActionAtLocation(
1476 const gfx::Point& location, const blink::WebMediaPlayerAction& action) {
1477 Send(new ViewMsg_MediaPlayerActionAt(GetRoutingID(), location, action));
1480 void RenderViewHostImpl::ExecutePluginActionAtLocation(
1481 const gfx::Point& location, const blink::WebPluginAction& action) {
1482 Send(new ViewMsg_PluginActionAt(GetRoutingID(), location, action));
1485 void RenderViewHostImpl::NotifyMoveOrResizeStarted() {
1486 Send(new ViewMsg_MoveOrResizeStarted(GetRoutingID()));
1489 void RenderViewHostImpl::OnDidZoomURL(double zoom_level,
1491 HostZoomMapImpl* host_zoom_map = static_cast<HostZoomMapImpl*>(
1492 HostZoomMap::GetForBrowserContext(GetProcess()->GetBrowserContext()));
1494 host_zoom_map->SetZoomLevelForView(GetProcess()->GetID(),
1497 net::GetHostOrSpecFromURL(url));
1500 void RenderViewHostImpl::OnRunFileChooser(const FileChooserParams& params) {
1501 delegate_->RunFileChooser(this, params);
1504 void RenderViewHostImpl::OnFocusedNodeTouched(bool editable) {
1507 virtual_keyboard_requested_ = base::win::DisplayVirtualKeyboard();
1509 virtual_keyboard_requested_ = false;
1510 base::win::DismissVirtualKeyboard();
1515 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1516 void RenderViewHostImpl::OnShowPopup(
1517 const ViewHostMsg_ShowPopup_Params& params) {
1518 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1520 view->ShowPopupMenu(params.bounds,
1522 params.item_font_size,
1523 params.selected_item,
1525 params.right_aligned,
1526 params.allow_multiple_selection);
1530 void RenderViewHostImpl::OnHidePopup() {
1531 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1533 view->HidePopupMenu();
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();
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;
1554 rvh_state_ = rvh_state;
1558 bool RenderViewHostImpl::CanAccessFilesOfPageState(
1559 const PageState& state) const {
1560 ChildProcessSecurityPolicyImpl* policy =
1561 ChildProcessSecurityPolicyImpl::GetInstance();
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))
1572 void RenderViewHostImpl::AttachToFrameTree() {
1573 FrameTree* frame_tree = delegate_->GetFrameTree();
1575 frame_tree->ResetForMainFrameSwap();
1578 void RenderViewHostImpl::SelectWordAroundCaret() {
1579 Send(new ViewMsg_SelectWordAroundCaret(GetRoutingID()));
1582 } // namespace content