Roll src/third_party/WebKit eac3800:0237a66 (svn 202606:202607)
[chromium-blink-merge.git] / content / browser / renderer_host / render_view_host_impl.cc
blobe7870524590791d2ea4769dee0ed26c01d35a12b
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"
7 #include <set>
8 #include <string>
9 #include <utility>
10 #include <vector>
12 #include "base/callback.h"
13 #include "base/command_line.h"
14 #include "base/i18n/rtl.h"
15 #include "base/json/json_reader.h"
16 #include "base/message_loop/message_loop.h"
17 #include "base/metrics/field_trial.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/trace_event/trace_event.h"
25 #include "base/values.h"
26 #include "cc/base/switches.h"
27 #include "content/browser/bad_message.h"
28 #include "content/browser/child_process_security_policy_impl.h"
29 #include "content/browser/dom_storage/session_storage_namespace_impl.h"
30 #include "content/browser/frame_host/frame_tree.h"
31 #include "content/browser/gpu/compositor_util.h"
32 #include "content/browser/gpu/gpu_data_manager_impl.h"
33 #include "content/browser/gpu/gpu_process_host.h"
34 #include "content/browser/gpu/gpu_surface_tracker.h"
35 #include "content/browser/host_zoom_map_impl.h"
36 #include "content/browser/loader/resource_dispatcher_host_impl.h"
37 #include "content/browser/renderer_host/dip_util.h"
38 #include "content/browser/renderer_host/media/audio_renderer_host.h"
39 #include "content/browser/renderer_host/render_process_host_impl.h"
40 #include "content/browser/renderer_host/render_view_host_delegate.h"
41 #include "content/browser/renderer_host/render_view_host_delegate_view.h"
42 #include "content/browser/renderer_host/render_widget_host_view_base.h"
43 #include "content/common/browser_plugin/browser_plugin_messages.h"
44 #include "content/common/content_switches_internal.h"
45 #include "content/common/drag_messages.h"
46 #include "content/common/frame_messages.h"
47 #include "content/common/input_messages.h"
48 #include "content/common/inter_process_time_ticks_converter.h"
49 #include "content/common/speech_recognition_messages.h"
50 #include "content/common/swapped_out_messages.h"
51 #include "content/common/view_messages.h"
52 #include "content/public/browser/ax_event_notification_details.h"
53 #include "content/public/browser/browser_accessibility_state.h"
54 #include "content/public/browser/browser_context.h"
55 #include "content/public/browser/browser_message_filter.h"
56 #include "content/public/browser/content_browser_client.h"
57 #include "content/public/browser/focused_node_details.h"
58 #include "content/public/browser/native_web_keyboard_event.h"
59 #include "content/public/browser/notification_details.h"
60 #include "content/public/browser/notification_service.h"
61 #include "content/public/browser/notification_types.h"
62 #include "content/public/browser/render_frame_host.h"
63 #include "content/public/browser/render_widget_host_iterator.h"
64 #include "content/public/browser/storage_partition.h"
65 #include "content/public/browser/user_metrics.h"
66 #include "content/public/common/bindings_policy.h"
67 #include "content/public/common/content_constants.h"
68 #include "content/public/common/content_switches.h"
69 #include "content/public/common/context_menu_params.h"
70 #include "content/public/common/drop_data.h"
71 #include "content/public/common/file_chooser_file_info.h"
72 #include "content/public/common/file_chooser_params.h"
73 #include "content/public/common/result_codes.h"
74 #include "content/public/common/url_constants.h"
75 #include "content/public/common/url_utils.h"
76 #include "net/base/filename_util.h"
77 #include "net/base/net_util.h"
78 #include "net/base/network_change_notifier.h"
79 #include "net/url_request/url_request_context_getter.h"
80 #include "storage/browser/fileapi/isolated_context.h"
81 #include "third_party/skia/include/core/SkBitmap.h"
82 #include "ui/base/touch/touch_device.h"
83 #include "ui/base/touch/touch_enabled.h"
84 #include "ui/base/ui_base_switches.h"
85 #include "ui/gfx/image/image_skia.h"
86 #include "ui/gfx/native_widget_types.h"
87 #include "ui/native_theme/native_theme_switches.h"
88 #include "url/url_constants.h"
90 #if defined(OS_WIN)
91 #include "base/win/win_util.h"
92 #include "ui/gfx/platform_font_win.h"
93 #include "ui/gfx/win/dpi.h"
94 #endif
96 using base::TimeDelta;
97 using blink::WebConsoleMessage;
98 using blink::WebDragOperation;
99 using blink::WebDragOperationNone;
100 using blink::WebDragOperationsMask;
101 using blink::WebInputEvent;
102 using blink::WebMediaPlayerAction;
103 using blink::WebPluginAction;
105 namespace content {
106 namespace {
108 #if defined(OS_WIN)
110 const int kVirtualKeyboardDisplayWaitTimeoutMs = 100;
111 const int kMaxVirtualKeyboardDisplayRetries = 5;
113 void DismissVirtualKeyboardTask() {
114 static int virtual_keyboard_display_retries = 0;
115 // If the virtual keyboard is not yet visible, then we execute the task again
116 // waiting for it to show up.
117 if (!base::win::DismissVirtualKeyboard()) {
118 if (virtual_keyboard_display_retries < kMaxVirtualKeyboardDisplayRetries) {
119 BrowserThread::PostDelayedTask(
120 BrowserThread::UI, FROM_HERE,
121 base::Bind(base::IgnoreResult(&DismissVirtualKeyboardTask)),
122 TimeDelta::FromMilliseconds(kVirtualKeyboardDisplayWaitTimeoutMs));
123 ++virtual_keyboard_display_retries;
124 } else {
125 virtual_keyboard_display_retries = 0;
130 void GetWindowsSpecificPrefs(RendererPreferences* prefs) {
131 NONCLIENTMETRICS_XP metrics = {0};
132 base::win::GetNonClientMetrics(&metrics);
134 prefs->caption_font_family_name = metrics.lfCaptionFont.lfFaceName;
135 prefs->caption_font_height = gfx::PlatformFontWin::GetFontSize(
136 metrics.lfCaptionFont);
138 prefs->small_caption_font_family_name = metrics.lfSmCaptionFont.lfFaceName;
139 prefs->small_caption_font_height = gfx::PlatformFontWin::GetFontSize(
140 metrics.lfSmCaptionFont);
142 prefs->menu_font_family_name = metrics.lfMenuFont.lfFaceName;
143 prefs->menu_font_height = gfx::PlatformFontWin::GetFontSize(
144 metrics.lfMenuFont);
146 prefs->status_font_family_name = metrics.lfStatusFont.lfFaceName;
147 prefs->status_font_height = gfx::PlatformFontWin::GetFontSize(
148 metrics.lfStatusFont);
150 prefs->message_font_family_name = metrics.lfMessageFont.lfFaceName;
151 prefs->message_font_height = gfx::PlatformFontWin::GetFontSize(
152 metrics.lfMessageFont);
154 prefs->vertical_scroll_bar_width_in_dips =
155 gfx::win::GetSystemMetricsInDIP(SM_CXVSCROLL);
156 prefs->horizontal_scroll_bar_height_in_dips =
157 gfx::win::GetSystemMetricsInDIP(SM_CYHSCROLL);
158 prefs->arrow_bitmap_height_vertical_scroll_bar_in_dips =
159 gfx::win::GetSystemMetricsInDIP(SM_CYVSCROLL);
160 prefs->arrow_bitmap_width_horizontal_scroll_bar_in_dips =
161 gfx::win::GetSystemMetricsInDIP(SM_CXHSCROLL);
163 #endif
165 } // namespace
167 // static
168 const int64 RenderViewHostImpl::kUnloadTimeoutMS = 1000;
170 ///////////////////////////////////////////////////////////////////////////////
171 // RenderViewHost, public:
173 // static
174 RenderViewHost* RenderViewHost::FromID(int render_process_id,
175 int render_view_id) {
176 return RenderViewHostImpl::FromID(render_process_id, render_view_id);
179 // static
180 RenderViewHost* RenderViewHost::From(RenderWidgetHost* rwh) {
181 DCHECK(rwh->IsRenderView());
182 return static_cast<RenderViewHostImpl*>(RenderWidgetHostImpl::From(rwh));
185 ///////////////////////////////////////////////////////////////////////////////
186 // RenderViewHostImpl, public:
188 // static
189 RenderViewHostImpl* RenderViewHostImpl::FromID(int render_process_id,
190 int render_view_id) {
191 RenderWidgetHost* widget =
192 RenderWidgetHost::FromID(render_process_id, render_view_id);
193 if (!widget || !widget->IsRenderView())
194 return NULL;
195 return static_cast<RenderViewHostImpl*>(RenderWidgetHostImpl::From(widget));
198 RenderViewHostImpl::RenderViewHostImpl(
199 SiteInstance* instance,
200 RenderViewHostDelegate* delegate,
201 RenderWidgetHostDelegate* widget_delegate,
202 int32 routing_id,
203 int32 surface_id,
204 int32 main_frame_routing_id,
205 bool swapped_out,
206 bool hidden,
207 bool has_initialized_audio_host)
208 : RenderWidgetHostImpl(widget_delegate,
209 instance->GetProcess(),
210 routing_id,
211 surface_id,
212 hidden),
213 frames_ref_count_(0),
214 delegate_(delegate),
215 instance_(static_cast<SiteInstanceImpl*>(instance)),
216 waiting_for_drag_context_response_(false),
217 enabled_bindings_(0),
218 page_id_(-1),
219 nav_entry_id_(0),
220 is_active_(!swapped_out),
221 is_swapped_out_(swapped_out),
222 main_frame_routing_id_(main_frame_routing_id),
223 is_waiting_for_close_ack_(false),
224 sudden_termination_allowed_(false),
225 render_view_termination_status_(base::TERMINATION_STATUS_STILL_RUNNING),
226 virtual_keyboard_requested_(false),
227 is_focused_element_editable_(false),
228 updating_web_preferences_(false),
229 weak_factory_(this) {
230 DCHECK(instance_.get());
231 CHECK(delegate_); // http://crbug.com/82827
233 GetProcess()->AddObserver(this);
234 GetProcess()->EnableSendQueue();
236 if (ResourceDispatcherHostImpl::Get()) {
237 bool has_active_audio = false;
238 if (has_initialized_audio_host) {
239 scoped_refptr<AudioRendererHost> arh =
240 static_cast<RenderProcessHostImpl*>(GetProcess())
241 ->audio_renderer_host();
242 if (arh.get())
243 has_active_audio =
244 arh->RenderFrameHasActiveAudio(main_frame_routing_id_);
246 BrowserThread::PostTask(
247 BrowserThread::IO,
248 FROM_HERE,
249 base::Bind(&ResourceDispatcherHostImpl::OnRenderViewHostCreated,
250 base::Unretained(ResourceDispatcherHostImpl::Get()),
251 GetProcess()->GetID(),
252 GetRoutingID(),
253 !is_hidden(),
254 has_active_audio));
258 RenderViewHostImpl::~RenderViewHostImpl() {
259 if (ResourceDispatcherHostImpl::Get()) {
260 BrowserThread::PostTask(
261 BrowserThread::IO, FROM_HERE,
262 base::Bind(&ResourceDispatcherHostImpl::OnRenderViewHostDeleted,
263 base::Unretained(ResourceDispatcherHostImpl::Get()),
264 GetProcess()->GetID(), GetRoutingID()));
267 delegate_->RenderViewDeleted(this);
268 GetProcess()->RemoveObserver(this);
271 RenderViewHostDelegate* RenderViewHostImpl::GetDelegate() const {
272 return delegate_;
275 SiteInstanceImpl* RenderViewHostImpl::GetSiteInstance() const {
276 return instance_.get();
279 bool RenderViewHostImpl::CreateRenderView(
280 int opener_frame_route_id,
281 int proxy_route_id,
282 int32 max_page_id,
283 const FrameReplicationState& replicated_frame_state,
284 bool window_was_created_with_opener) {
285 TRACE_EVENT0("renderer_host,navigation",
286 "RenderViewHostImpl::CreateRenderView");
287 DCHECK(!IsRenderViewLive()) << "Creating view twice";
289 // The process may (if we're sharing a process with another host that already
290 // initialized it) or may not (we have our own process or the old process
291 // crashed) have been initialized. Calling Init multiple times will be
292 // ignored, so this is safe.
293 if (!GetProcess()->Init())
294 return false;
295 DCHECK(GetProcess()->HasConnection());
296 DCHECK(GetProcess()->GetBrowserContext());
298 set_renderer_initialized(true);
300 // If this is not an active RenderView, then we need to create a
301 // handle with NULL_TRANSPORT type. Active RenderViews will implement
302 // GetCompositingSurface() in the RenderWidgetHostView delegate which returns
303 // the appropriate surface type.
304 if (proxy_route_id != MSG_ROUTING_NONE) {
305 GpuSurfaceTracker::Get()->SetSurfaceHandle(
306 surface_id(),
307 gfx::GLSurfaceHandle(gfx::kNullPluginWindow, gfx::NULL_TRANSPORT));
308 } else {
309 GpuSurfaceTracker::Get()->SetSurfaceHandle(surface_id(),
310 GetCompositingSurface());
313 // Ensure the RenderView starts with a next_page_id larger than any existing
314 // page ID it might be asked to render.
315 int32 next_page_id = 1;
316 if (max_page_id > -1)
317 next_page_id = max_page_id + 1;
319 ViewMsg_New_Params params;
320 params.renderer_preferences =
321 delegate_->GetRendererPrefs(GetProcess()->GetBrowserContext());
322 #if defined(OS_WIN)
323 GetWindowsSpecificPrefs(&params.renderer_preferences);
324 #endif
325 params.web_preferences = GetWebkitPreferences();
326 params.view_id = GetRoutingID();
327 params.main_frame_routing_id = main_frame_routing_id_;
328 params.surface_id = surface_id();
329 params.session_storage_namespace_id =
330 delegate_->GetSessionStorageNamespace(instance_.get())->id();
331 // Ensure the RenderView sets its opener correctly.
332 params.opener_frame_route_id = opener_frame_route_id;
333 params.swapped_out = !is_active_;
334 params.replicated_frame_state = replicated_frame_state;
335 params.proxy_routing_id = proxy_route_id;
336 params.hidden = is_hidden();
337 params.never_visible = delegate_->IsNeverVisible();
338 params.window_was_created_with_opener = window_was_created_with_opener;
339 params.next_page_id = next_page_id;
340 params.enable_auto_resize = auto_resize_enabled();
341 params.min_size = min_size_for_auto_resize();
342 params.max_size = max_size_for_auto_resize();
343 GetResizeParams(&params.initial_size);
345 if (!Send(new ViewMsg_New(params)))
346 return false;
347 SetInitialRenderSizeParams(params.initial_size);
349 // If the RWHV has not yet been set, the surface ID namespace will get
350 // passed down by the call to SetView().
351 if (view_) {
352 Send(new ViewMsg_SetSurfaceIdNamespace(GetRoutingID(),
353 view_->GetSurfaceIdNamespace()));
356 // If it's enabled, tell the renderer to set up the Javascript bindings for
357 // sending messages back to the browser.
358 if (GetProcess()->IsForGuestsOnly())
359 DCHECK_EQ(0, enabled_bindings_);
360 Send(new ViewMsg_AllowBindings(GetRoutingID(), enabled_bindings_));
361 // Let our delegate know that we created a RenderView.
362 delegate_->RenderViewCreated(this);
364 // Since this method can create the main RenderFrame in the renderer process,
365 // set the proper state on its corresponding RenderFrameHost.
366 if (main_frame_routing_id_ != MSG_ROUTING_NONE) {
367 RenderFrameHostImpl::FromID(GetProcess()->GetID(), main_frame_routing_id_)
368 ->SetRenderFrameCreated(true);
371 return true;
374 bool RenderViewHostImpl::IsRenderViewLive() const {
375 return GetProcess()->HasConnection() && renderer_initialized();
378 void RenderViewHostImpl::SyncRendererPrefs() {
379 RendererPreferences renderer_preferences =
380 delegate_->GetRendererPrefs(GetProcess()->GetBrowserContext());
381 #if defined(OS_WIN)
382 GetWindowsSpecificPrefs(&renderer_preferences);
383 #endif
384 Send(new ViewMsg_SetRendererPrefs(GetRoutingID(), renderer_preferences));
387 WebPreferences RenderViewHostImpl::ComputeWebkitPrefs() {
388 TRACE_EVENT0("browser", "RenderViewHostImpl::GetWebkitPrefs");
389 WebPreferences prefs;
391 const base::CommandLine& command_line =
392 *base::CommandLine::ForCurrentProcess();
394 prefs.web_security_enabled =
395 !command_line.HasSwitch(switches::kDisableWebSecurity);
397 prefs.remote_fonts_enabled =
398 !command_line.HasSwitch(switches::kDisableRemoteFonts);
399 prefs.application_cache_enabled = true;
400 prefs.xss_auditor_enabled =
401 !command_line.HasSwitch(switches::kDisableXSSAuditor);
402 prefs.local_storage_enabled =
403 !command_line.HasSwitch(switches::kDisableLocalStorage);
404 prefs.databases_enabled =
405 !command_line.HasSwitch(switches::kDisableDatabases);
406 #if defined(OS_ANDROID)
407 // WebAudio is enabled by default on x86 and ARM.
408 prefs.webaudio_enabled =
409 !command_line.HasSwitch(switches::kDisableWebAudio);
410 #endif
412 prefs.experimental_webgl_enabled =
413 GpuProcessHost::gpu_enabled() &&
414 !command_line.HasSwitch(switches::kDisable3DAPIs) &&
415 !command_line.HasSwitch(switches::kDisableExperimentalWebGL);
417 prefs.pepper_3d_enabled =
418 !command_line.HasSwitch(switches::kDisablePepper3d);
420 prefs.flash_3d_enabled =
421 GpuProcessHost::gpu_enabled() &&
422 !command_line.HasSwitch(switches::kDisableFlash3d);
423 prefs.flash_stage3d_enabled =
424 GpuProcessHost::gpu_enabled() &&
425 !command_line.HasSwitch(switches::kDisableFlashStage3d);
426 prefs.flash_stage3d_baseline_enabled =
427 GpuProcessHost::gpu_enabled() &&
428 !command_line.HasSwitch(switches::kDisableFlashStage3d);
430 prefs.allow_file_access_from_file_urls =
431 command_line.HasSwitch(switches::kAllowFileAccessFromFiles);
433 prefs.accelerated_2d_canvas_enabled =
434 GpuProcessHost::gpu_enabled() &&
435 !command_line.HasSwitch(switches::kDisableAccelerated2dCanvas);
436 prefs.antialiased_2d_canvas_disabled =
437 command_line.HasSwitch(switches::kDisable2dCanvasAntialiasing);
438 prefs.antialiased_clips_2d_canvas_enabled =
439 command_line.HasSwitch(switches::kEnable2dCanvasClipAntialiasing);
440 prefs.accelerated_2d_canvas_msaa_sample_count =
441 atoi(command_line.GetSwitchValueASCII(
442 switches::kAcceleratedCanvas2dMSAASampleCount).c_str());
444 prefs.pinch_overlay_scrollbar_thickness = 10;
445 prefs.use_solid_color_scrollbars = ui::IsOverlayScrollbarEnabled();
447 #if defined(OS_ANDROID)
448 // On Android, user gestures are normally required, unless that requirement
449 // is disabled with a command-line switch or the equivalent field trial is
450 // is set to "Enabled".
451 const std::string autoplay_group_name = base::FieldTrialList::FindFullName(
452 "MediaElementAutoplay");
453 prefs.user_gesture_required_for_media_playback = !command_line.HasSwitch(
454 switches::kDisableGestureRequirementForMediaPlayback) &&
455 (autoplay_group_name.empty() || autoplay_group_name != "Enabled");
457 // Handle autoplay gesture override experiment.
458 // Note that anything but a well-formed string turns the experiment off.
459 prefs.autoplay_experiment_mode = base::FieldTrialList::FindFullName(
460 "MediaElementGestureOverrideExperiment");
461 #endif
463 prefs.touch_enabled = ui::AreTouchEventsEnabled();
464 prefs.device_supports_touch = prefs.touch_enabled &&
465 ui::IsTouchDevicePresent();
466 prefs.available_pointer_types = ui::GetAvailablePointerTypes();
467 prefs.primary_pointer_type = ui::GetPrimaryPointerType();
468 prefs.available_hover_types = ui::GetAvailableHoverTypes();
469 prefs.primary_hover_type = ui::GetPrimaryHoverType();
471 #if defined(OS_ANDROID)
472 prefs.device_supports_mouse = false;
473 #endif
475 prefs.pointer_events_max_touch_points = ui::MaxTouchPoints();
477 prefs.touch_adjustment_enabled =
478 !command_line.HasSwitch(switches::kDisableTouchAdjustment);
480 prefs.slimming_paint_v2_enabled =
481 command_line.HasSwitch(switches::kEnableSlimmingPaintV2);
483 #if defined(OS_MACOSX) || defined(OS_CHROMEOS)
484 bool default_enable_scroll_animator = true;
485 #else
486 bool default_enable_scroll_animator = false;
487 #endif
488 prefs.enable_scroll_animator = default_enable_scroll_animator;
489 if (command_line.HasSwitch(switches::kEnableSmoothScrolling))
490 prefs.enable_scroll_animator = true;
491 if (command_line.HasSwitch(switches::kDisableSmoothScrolling))
492 prefs.enable_scroll_animator = false;
494 // Certain GPU features might have been blacklisted.
495 GpuDataManagerImpl::GetInstance()->UpdateRendererWebPrefs(&prefs);
497 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
498 GetProcess()->GetID())) {
499 prefs.loads_images_automatically = true;
500 prefs.javascript_enabled = true;
503 net::NetworkChangeNotifier::GetMaxBandwidthAndConnectionType(
504 &prefs.net_info_max_bandwidth_mbps, &prefs.net_info_connection_type);
505 prefs.is_online = prefs.net_info_connection_type !=
506 net::NetworkChangeNotifier::CONNECTION_NONE;
508 prefs.number_of_cpu_cores = base::SysInfo::NumberOfProcessors();
510 prefs.viewport_enabled =
511 command_line.HasSwitch(switches::kEnableViewport) ||
512 prefs.viewport_meta_enabled;
514 prefs.main_frame_resizes_are_orientation_changes =
515 command_line.HasSwitch(switches::kMainFrameResizesAreOrientationChanges);
517 prefs.image_color_profiles_enabled =
518 command_line.HasSwitch(switches::kEnableImageColorProfiles);
520 prefs.spatial_navigation_enabled = command_line.HasSwitch(
521 switches::kEnableSpatialNavigation);
523 prefs.disable_reading_from_canvas = command_line.HasSwitch(
524 switches::kDisableReadingFromCanvas);
526 prefs.strict_mixed_content_checking = command_line.HasSwitch(
527 switches::kEnableStrictMixedContentChecking);
529 prefs.strict_powerful_feature_restrictions = command_line.HasSwitch(
530 switches::kEnableStrictPowerfulFeatureRestrictions);
532 const std::string blockable_mixed_content_group =
533 base::FieldTrialList::FindFullName("BlockableMixedContent");
534 prefs.strictly_block_blockable_mixed_content =
535 blockable_mixed_content_group == "StrictlyBlockBlockableMixedContent";
537 const std::string plugin_mixed_content_status =
538 base::FieldTrialList::FindFullName("PluginMixedContentStatus");
539 prefs.block_mixed_plugin_content =
540 plugin_mixed_content_status == "BlockableMixedContent";
542 prefs.v8_cache_options = GetV8CacheOptions();
544 GetContentClient()->browser()->OverrideWebkitPrefs(this, &prefs);
545 return prefs;
548 void RenderViewHostImpl::SuppressDialogsUntilSwapOut() {
549 Send(new ViewMsg_SuppressDialogsUntilSwapOut(GetRoutingID()));
552 void RenderViewHostImpl::ClosePage() {
553 is_waiting_for_close_ack_ = true;
554 StartHangMonitorTimeout(TimeDelta::FromMilliseconds(kUnloadTimeoutMS));
556 if (IsRenderViewLive()) {
557 // Since we are sending an IPC message to the renderer, increase the event
558 // count to prevent the hang monitor timeout from being stopped by input
559 // event acknowledgements.
560 increment_in_flight_event_count();
562 // TODO(creis): Should this be moved to Shutdown? It may not be called for
563 // RenderViewHosts that have been swapped out.
564 NotificationService::current()->Notify(
565 NOTIFICATION_RENDER_VIEW_HOST_WILL_CLOSE_RENDER_VIEW,
566 Source<RenderViewHost>(this),
567 NotificationService::NoDetails());
569 Send(new ViewMsg_ClosePage(GetRoutingID()));
570 } else {
571 // This RenderViewHost doesn't have a live renderer, so just skip the unload
572 // event and close the page.
573 ClosePageIgnoringUnloadEvents();
577 void RenderViewHostImpl::ClosePageIgnoringUnloadEvents() {
578 StopHangMonitorTimeout();
579 is_waiting_for_close_ack_ = false;
581 sudden_termination_allowed_ = true;
582 delegate_->Close(this);
585 #if defined(OS_ANDROID)
586 void RenderViewHostImpl::ActivateNearestFindResult(int request_id,
587 float x,
588 float y) {
589 Send(new InputMsg_ActivateNearestFindResult(GetRoutingID(),
590 request_id, x, y));
593 void RenderViewHostImpl::RequestFindMatchRects(int current_version) {
594 Send(new ViewMsg_FindMatchRects(GetRoutingID(), current_version));
596 #endif
598 void RenderViewHostImpl::RenderProcessExited(RenderProcessHost* host,
599 base::TerminationStatus status,
600 int exit_code) {
601 if (!renderer_initialized())
602 return;
604 RenderWidgetHostImpl::RendererExited(status, exit_code);
605 delegate_->RenderViewTerminated(this, status, exit_code);
608 void RenderViewHostImpl::DragTargetDragEnter(
609 const DropData& drop_data,
610 const gfx::Point& client_pt,
611 const gfx::Point& screen_pt,
612 WebDragOperationsMask operations_allowed,
613 int key_modifiers) {
614 const int renderer_id = GetProcess()->GetID();
615 ChildProcessSecurityPolicyImpl* policy =
616 ChildProcessSecurityPolicyImpl::GetInstance();
618 #if defined(OS_CHROMEOS)
619 // The externalfile:// scheme is used in Chrome OS to open external files in a
620 // browser tab.
621 if (drop_data.url.SchemeIs(content::kExternalFileScheme))
622 policy->GrantRequestURL(renderer_id, drop_data.url);
623 #endif
625 // The URL could have been cobbled together from any highlighted text string,
626 // and can't be interpreted as a capability.
627 DropData filtered_data(drop_data);
628 GetProcess()->FilterURL(true, &filtered_data.url);
629 if (drop_data.did_originate_from_renderer) {
630 filtered_data.filenames.clear();
633 // The filenames vector, on the other hand, does represent a capability to
634 // access the given files.
635 storage::IsolatedContext::FileInfoSet files;
636 for (std::vector<ui::FileInfo>::iterator iter(
637 filtered_data.filenames.begin());
638 iter != filtered_data.filenames.end();
639 ++iter) {
640 // A dragged file may wind up as the value of an input element, or it
641 // may be used as the target of a navigation instead. We don't know
642 // which will happen at this point, so generously grant both access
643 // and request permissions to the specific file to cover both cases.
644 // We do not give it the permission to request all file:// URLs.
646 // Make sure we have the same display_name as the one we register.
647 if (iter->display_name.empty()) {
648 std::string name;
649 files.AddPath(iter->path, &name);
650 iter->display_name = base::FilePath::FromUTF8Unsafe(name);
651 } else {
652 files.AddPathWithName(iter->path, iter->display_name.AsUTF8Unsafe());
655 policy->GrantRequestSpecificFileURL(renderer_id,
656 net::FilePathToFileURL(iter->path));
658 // If the renderer already has permission to read these paths, we don't need
659 // to re-grant them. This prevents problems with DnD for files in the CrOS
660 // file manager--the file manager already had read/write access to those
661 // directories, but dragging a file would cause the read/write access to be
662 // overwritten with read-only access, making them impossible to delete or
663 // rename until the renderer was killed.
664 if (!policy->CanReadFile(renderer_id, iter->path))
665 policy->GrantReadFile(renderer_id, iter->path);
668 storage::IsolatedContext* isolated_context =
669 storage::IsolatedContext::GetInstance();
670 DCHECK(isolated_context);
671 std::string filesystem_id = isolated_context->RegisterDraggedFileSystem(
672 files);
673 if (!filesystem_id.empty()) {
674 // Grant the permission iff the ID is valid.
675 policy->GrantReadFileSystem(renderer_id, filesystem_id);
677 filtered_data.filesystem_id = base::UTF8ToUTF16(filesystem_id);
679 storage::FileSystemContext* file_system_context =
680 BrowserContext::GetStoragePartition(GetProcess()->GetBrowserContext(),
681 GetSiteInstance())
682 ->GetFileSystemContext();
683 for (size_t i = 0; i < filtered_data.file_system_files.size(); ++i) {
684 storage::FileSystemURL file_system_url =
685 file_system_context->CrackURL(filtered_data.file_system_files[i].url);
687 std::string register_name;
688 std::string filesystem_id = isolated_context->RegisterFileSystemForPath(
689 file_system_url.type(), file_system_url.filesystem_id(),
690 file_system_url.path(), &register_name);
691 policy->GrantReadFileSystem(renderer_id, filesystem_id);
693 // Note: We are using the origin URL provided by the sender here. It may be
694 // different from the receiver's.
695 filtered_data.file_system_files[i].url =
696 GURL(storage::GetIsolatedFileSystemRootURIString(
697 file_system_url.origin(), filesystem_id, std::string())
698 .append(register_name));
701 Send(new DragMsg_TargetDragEnter(GetRoutingID(), filtered_data, client_pt,
702 screen_pt, operations_allowed,
703 key_modifiers));
706 void RenderViewHostImpl::DragTargetDragOver(
707 const gfx::Point& client_pt,
708 const gfx::Point& screen_pt,
709 WebDragOperationsMask operations_allowed,
710 int key_modifiers) {
711 Send(new DragMsg_TargetDragOver(GetRoutingID(), client_pt, screen_pt,
712 operations_allowed, key_modifiers));
715 void RenderViewHostImpl::DragTargetDragLeave() {
716 Send(new DragMsg_TargetDragLeave(GetRoutingID()));
719 void RenderViewHostImpl::DragTargetDrop(
720 const gfx::Point& client_pt,
721 const gfx::Point& screen_pt,
722 int key_modifiers) {
723 Send(new DragMsg_TargetDrop(GetRoutingID(), client_pt, screen_pt,
724 key_modifiers));
727 void RenderViewHostImpl::DragSourceEndedAt(
728 int client_x, int client_y, int screen_x, int screen_y,
729 WebDragOperation operation) {
730 Send(new DragMsg_SourceEnded(GetRoutingID(),
731 gfx::Point(client_x, client_y),
732 gfx::Point(screen_x, screen_y),
733 operation));
736 void RenderViewHostImpl::DragSourceSystemDragEnded() {
737 Send(new DragMsg_SourceSystemDragEnded(GetRoutingID()));
740 RenderFrameHost* RenderViewHostImpl::GetMainFrame() {
741 return RenderFrameHost::FromID(GetProcess()->GetID(), main_frame_routing_id_);
744 void RenderViewHostImpl::AllowBindings(int bindings_flags) {
745 // Never grant any bindings to browser plugin guests.
746 if (GetProcess()->IsForGuestsOnly()) {
747 NOTREACHED() << "Never grant bindings to a guest process.";
748 return;
751 // Ensure we aren't granting WebUI bindings to a process that has already
752 // been used for non-privileged views.
753 if (bindings_flags & BINDINGS_POLICY_WEB_UI &&
754 GetProcess()->HasConnection() &&
755 !ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
756 GetProcess()->GetID())) {
757 // This process has no bindings yet. Make sure it does not have more
758 // than this single active view.
759 // --single-process only has one renderer.
760 if (GetProcess()->GetActiveViewCount() > 1 &&
761 !base::CommandLine::ForCurrentProcess()->HasSwitch(
762 switches::kSingleProcess))
763 return;
766 if (bindings_flags & BINDINGS_POLICY_WEB_UI) {
767 ChildProcessSecurityPolicyImpl::GetInstance()->GrantWebUIBindings(
768 GetProcess()->GetID());
771 enabled_bindings_ |= bindings_flags;
772 if (renderer_initialized())
773 Send(new ViewMsg_AllowBindings(GetRoutingID(), enabled_bindings_));
776 int RenderViewHostImpl::GetEnabledBindings() const {
777 return enabled_bindings_;
780 void RenderViewHostImpl::SetWebUIProperty(const std::string& name,
781 const std::string& value) {
782 // This is a sanity check before telling the renderer to enable the property.
783 // It could lie and send the corresponding IPC messages anyway, but we will
784 // not act on them if enabled_bindings_ doesn't agree. If we get here without
785 // WebUI bindings, kill the renderer process.
786 if (enabled_bindings_ & BINDINGS_POLICY_WEB_UI) {
787 Send(new ViewMsg_SetWebUIProperty(GetRoutingID(), name, value));
788 } else {
789 RecordAction(
790 base::UserMetricsAction("BindingsMismatchTerminate_RVH_WebUI"));
791 GetProcess()->Shutdown(content::RESULT_CODE_KILLED, false);
795 void RenderViewHostImpl::GotFocus() {
796 RenderWidgetHostImpl::GotFocus(); // Notifies the renderer it got focus.
798 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
799 if (view)
800 view->GotFocus();
803 void RenderViewHostImpl::LostCapture() {
804 RenderWidgetHostImpl::LostCapture();
805 delegate_->LostCapture();
808 void RenderViewHostImpl::LostMouseLock() {
809 RenderWidgetHostImpl::LostMouseLock();
810 delegate_->LostMouseLock();
813 void RenderViewHostImpl::SetInitialFocus(bool reverse) {
814 Send(new ViewMsg_SetInitialFocus(GetRoutingID(), reverse));
817 void RenderViewHostImpl::FilesSelectedInChooser(
818 const std::vector<content::FileChooserFileInfo>& files,
819 FileChooserParams::Mode permissions) {
820 storage::FileSystemContext* const file_system_context =
821 BrowserContext::GetStoragePartition(GetProcess()->GetBrowserContext(),
822 GetSiteInstance())
823 ->GetFileSystemContext();
824 // Grant the security access requested to the given files.
825 for (size_t i = 0; i < files.size(); ++i) {
826 const content::FileChooserFileInfo& file = files[i];
827 if (permissions == FileChooserParams::Save) {
828 ChildProcessSecurityPolicyImpl::GetInstance()->GrantCreateReadWriteFile(
829 GetProcess()->GetID(), file.file_path);
830 } else {
831 ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
832 GetProcess()->GetID(), file.file_path);
834 if (file.file_system_url.is_valid()) {
835 ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFileSystem(
836 GetProcess()->GetID(),
837 file_system_context->CrackURL(file.file_system_url)
838 .mount_filesystem_id());
841 Send(new ViewMsg_RunFileChooserResponse(GetRoutingID(), files));
844 void RenderViewHostImpl::DirectoryEnumerationFinished(
845 int request_id,
846 const std::vector<base::FilePath>& files) {
847 // Grant the security access requested to the given files.
848 for (std::vector<base::FilePath>::const_iterator file = files.begin();
849 file != files.end(); ++file) {
850 ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
851 GetProcess()->GetID(), *file);
853 Send(new ViewMsg_EnumerateDirectoryResponse(GetRoutingID(),
854 request_id,
855 files));
858 void RenderViewHostImpl::SetIsLoading(bool is_loading) {
859 if (ResourceDispatcherHostImpl::Get()) {
860 BrowserThread::PostTask(
861 BrowserThread::IO,
862 FROM_HERE,
863 base::Bind(&ResourceDispatcherHostImpl::OnRenderViewHostSetIsLoading,
864 base::Unretained(ResourceDispatcherHostImpl::Get()),
865 GetProcess()->GetID(),
866 GetRoutingID(),
867 is_loading));
869 RenderWidgetHostImpl::SetIsLoading(is_loading);
872 void RenderViewHostImpl::LoadStateChanged(
873 const GURL& url,
874 const net::LoadStateWithParam& load_state,
875 uint64 upload_position,
876 uint64 upload_size) {
877 delegate_->LoadStateChanged(url, load_state, upload_position, upload_size);
880 bool RenderViewHostImpl::SuddenTerminationAllowed() const {
881 return sudden_termination_allowed_ ||
882 GetProcess()->SuddenTerminationAllowed();
885 ///////////////////////////////////////////////////////////////////////////////
886 // RenderViewHostImpl, IPC message handlers:
888 bool RenderViewHostImpl::OnMessageReceived(const IPC::Message& msg) {
889 if (!BrowserMessageFilter::CheckCanDispatchOnUI(msg, this))
890 return true;
892 // Filter out most IPC messages if this renderer is swapped out.
893 // We still want to handle certain ACKs to keep our state consistent.
894 if (is_swapped_out_) {
895 if (!SwappedOutMessages::CanHandleWhileSwappedOut(msg)) {
896 // If this is a synchronous message and we decided not to handle it,
897 // we must send an error reply, or else the renderer will be stuck
898 // and won't respond to future requests.
899 if (msg.is_sync()) {
900 IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
901 reply->set_reply_error();
902 Send(reply);
904 // Don't continue looking for someone to handle it.
905 return true;
909 if (delegate_->OnMessageReceived(this, msg))
910 return true;
912 bool handled = true;
913 IPC_BEGIN_MESSAGE_MAP(RenderViewHostImpl, msg)
914 IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone)
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(ViewHostMsg_RenderViewReady, OnRenderViewReady)
920 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateState, OnUpdateState)
921 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateTargetURL, OnUpdateTargetURL)
922 IPC_MESSAGE_HANDLER(ViewHostMsg_Close, OnClose)
923 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestMove, OnRequestMove)
924 IPC_MESSAGE_HANDLER(ViewHostMsg_DocumentAvailableInMainFrame,
925 OnDocumentAvailableInMainFrame)
926 IPC_MESSAGE_HANDLER(ViewHostMsg_DidContentsPreferredSizeChange,
927 OnDidContentsPreferredSizeChange)
928 IPC_MESSAGE_HANDLER(ViewHostMsg_RouteCloseEvent,
929 OnRouteCloseEvent)
930 IPC_MESSAGE_HANDLER(DragHostMsg_StartDragging, OnStartDragging)
931 IPC_MESSAGE_HANDLER(DragHostMsg_UpdateDragCursor, OnUpdateDragCursor)
932 IPC_MESSAGE_HANDLER(ViewHostMsg_TakeFocus, OnTakeFocus)
933 IPC_MESSAGE_HANDLER(ViewHostMsg_FocusedNodeChanged, OnFocusedNodeChanged)
934 IPC_MESSAGE_HANDLER(ViewHostMsg_ClosePage_ACK, OnClosePageACK)
935 IPC_MESSAGE_HANDLER(ViewHostMsg_DidZoomURL, OnDidZoomURL)
936 IPC_MESSAGE_HANDLER(ViewHostMsg_PageScaleFactorIsOneChanged,
937 OnPageScaleFactorIsOneChanged)
938 IPC_MESSAGE_HANDLER(ViewHostMsg_RunFileChooser, OnRunFileChooser)
939 IPC_MESSAGE_HANDLER(ViewHostMsg_FocusedNodeTouched, OnFocusedNodeTouched)
940 // Have the super handle all other messages.
941 IPC_MESSAGE_UNHANDLED(
942 handled = RenderWidgetHostImpl::OnMessageReceived(msg))
943 IPC_END_MESSAGE_MAP()
945 return handled;
948 void RenderViewHostImpl::Init() {
949 RenderWidgetHostImpl::Init();
952 void RenderViewHostImpl::Shutdown() {
953 // We can't release the SessionStorageNamespace until our peer
954 // in the renderer has wound down.
955 if (GetProcess()->HasConnection()) {
956 RenderProcessHostImpl::ReleaseOnCloseACK(
957 GetProcess(),
958 delegate_->GetSessionStorageNamespaceMap(),
959 GetRoutingID());
962 RenderWidgetHostImpl::Shutdown();
965 void RenderViewHostImpl::WasHidden() {
966 if (ResourceDispatcherHostImpl::Get()) {
967 BrowserThread::PostTask(
968 BrowserThread::IO, FROM_HERE,
969 base::Bind(&ResourceDispatcherHostImpl::OnRenderViewHostWasHidden,
970 base::Unretained(ResourceDispatcherHostImpl::Get()),
971 GetProcess()->GetID(), GetRoutingID()));
974 RenderWidgetHostImpl::WasHidden();
977 void RenderViewHostImpl::WasShown(const ui::LatencyInfo& latency_info) {
978 if (ResourceDispatcherHostImpl::Get()) {
979 BrowserThread::PostTask(
980 BrowserThread::IO, FROM_HERE,
981 base::Bind(&ResourceDispatcherHostImpl::OnRenderViewHostWasShown,
982 base::Unretained(ResourceDispatcherHostImpl::Get()),
983 GetProcess()->GetID(), GetRoutingID()));
986 RenderWidgetHostImpl::WasShown(latency_info);
989 bool RenderViewHostImpl::IsRenderView() const {
990 return true;
993 void RenderViewHostImpl::CreateNewWindow(
994 int route_id,
995 int main_frame_route_id,
996 const ViewHostMsg_CreateWindow_Params& params,
997 SessionStorageNamespace* session_storage_namespace) {
998 ViewHostMsg_CreateWindow_Params validated_params(params);
999 GetProcess()->FilterURL(false, &validated_params.target_url);
1000 GetProcess()->FilterURL(false, &validated_params.opener_url);
1001 GetProcess()->FilterURL(true, &validated_params.opener_security_origin);
1003 delegate_->CreateNewWindow(GetSiteInstance(), route_id, main_frame_route_id,
1004 validated_params, session_storage_namespace);
1007 void RenderViewHostImpl::CreateNewWidget(int32 route_id,
1008 int32 surface_id,
1009 blink::WebPopupType popup_type) {
1010 delegate_->CreateNewWidget(GetProcess()->GetID(), route_id, surface_id,
1011 popup_type);
1014 void RenderViewHostImpl::CreateNewFullscreenWidget(int32 route_id,
1015 int32 surface_id) {
1016 delegate_->CreateNewFullscreenWidget(GetProcess()->GetID(), route_id,
1017 surface_id);
1020 void RenderViewHostImpl::OnShowView(int route_id,
1021 WindowOpenDisposition disposition,
1022 const gfx::Rect& initial_rect,
1023 bool user_gesture) {
1024 delegate_->ShowCreatedWindow(route_id, disposition, initial_rect,
1025 user_gesture);
1026 Send(new ViewMsg_Move_ACK(route_id));
1029 void RenderViewHostImpl::OnShowWidget(int route_id,
1030 const gfx::Rect& initial_rect) {
1031 if (is_active_)
1032 delegate_->ShowCreatedWidget(route_id, initial_rect);
1033 Send(new ViewMsg_Move_ACK(route_id));
1036 void RenderViewHostImpl::OnShowFullscreenWidget(int route_id) {
1037 if (is_active_)
1038 delegate_->ShowCreatedFullscreenWidget(route_id);
1039 Send(new ViewMsg_Move_ACK(route_id));
1042 void RenderViewHostImpl::OnRenderViewReady() {
1043 render_view_termination_status_ = base::TERMINATION_STATUS_STILL_RUNNING;
1044 SendScreenRects();
1045 WasResized();
1046 delegate_->RenderViewReady(this);
1049 void RenderViewHostImpl::OnRenderProcessGone(int status, int exit_code) {
1050 // Do nothing, otherwise RenderWidgetHostImpl will assume it is not a
1051 // RenderViewHostImpl and destroy itself.
1052 // TODO(nasko): Remove this hack once RenderViewHost and RenderWidgetHost are
1053 // decoupled.
1056 void RenderViewHostImpl::OnUpdateState(int32 page_id, const PageState& state) {
1057 // If the following DCHECK fails, you have encountered a tricky edge-case that
1058 // has evaded reproduction for a very long time. Please report what you were
1059 // doing on http://crbug.com/407376, whether or not you can reproduce the
1060 // failure.
1061 DCHECK_EQ(page_id, page_id_);
1063 // Without this check, the renderer can trick the browser into using
1064 // filenames it can't access in a future session restore.
1065 if (!CanAccessFilesOfPageState(state)) {
1066 bad_message::ReceivedBadMessage(
1067 GetProcess(), bad_message::RVH_CAN_ACCESS_FILES_OF_PAGE_STATE);
1068 return;
1071 delegate_->UpdateState(this, page_id, state);
1074 void RenderViewHostImpl::OnUpdateTargetURL(const GURL& url) {
1075 if (is_active_)
1076 delegate_->UpdateTargetURL(this, url);
1078 // Send a notification back to the renderer that we are ready to
1079 // receive more target urls.
1080 Send(new ViewMsg_UpdateTargetURL_ACK(GetRoutingID()));
1083 void RenderViewHostImpl::OnClose() {
1084 // If the renderer is telling us to close, it has already run the unload
1085 // events, and we can take the fast path.
1086 ClosePageIgnoringUnloadEvents();
1089 void RenderViewHostImpl::OnRequestMove(const gfx::Rect& pos) {
1090 if (is_active_)
1091 delegate_->RequestMove(pos);
1092 Send(new ViewMsg_Move_ACK(GetRoutingID()));
1095 void RenderViewHostImpl::OnDocumentAvailableInMainFrame(
1096 bool uses_temporary_zoom_level) {
1097 delegate_->DocumentAvailableInMainFrame(this);
1099 if (!uses_temporary_zoom_level)
1100 return;
1102 HostZoomMapImpl* host_zoom_map =
1103 static_cast<HostZoomMapImpl*>(HostZoomMap::Get(GetSiteInstance()));
1104 host_zoom_map->SetTemporaryZoomLevel(GetProcess()->GetID(),
1105 GetRoutingID(),
1106 host_zoom_map->GetDefaultZoomLevel());
1109 void RenderViewHostImpl::OnDidContentsPreferredSizeChange(
1110 const gfx::Size& new_size) {
1111 delegate_->UpdatePreferredSize(new_size);
1114 void RenderViewHostImpl::OnRenderAutoResized(const gfx::Size& new_size) {
1115 delegate_->ResizeDueToAutoResize(new_size);
1118 void RenderViewHostImpl::OnRouteCloseEvent() {
1119 // Have the delegate route this to the active RenderViewHost.
1120 delegate_->RouteCloseEvent(this);
1123 void RenderViewHostImpl::OnStartDragging(
1124 const DropData& drop_data,
1125 WebDragOperationsMask drag_operations_mask,
1126 const SkBitmap& bitmap,
1127 const gfx::Vector2d& bitmap_offset_in_dip,
1128 const DragEventSourceInfo& event_info) {
1129 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1130 if (!view)
1131 return;
1133 DropData filtered_data(drop_data);
1134 RenderProcessHost* process = GetProcess();
1135 ChildProcessSecurityPolicyImpl* policy =
1136 ChildProcessSecurityPolicyImpl::GetInstance();
1138 // Allow drag of Javascript URLs to enable bookmarklet drag to bookmark bar.
1139 if (!filtered_data.url.SchemeIs(url::kJavaScriptScheme))
1140 process->FilterURL(true, &filtered_data.url);
1141 process->FilterURL(false, &filtered_data.html_base_url);
1142 // Filter out any paths that the renderer didn't have access to. This prevents
1143 // the following attack on a malicious renderer:
1144 // 1. StartDragging IPC sent with renderer-specified filesystem paths that it
1145 // doesn't have read permissions for.
1146 // 2. We initiate a native DnD operation.
1147 // 3. DnD operation immediately ends since mouse is not held down. DnD events
1148 // still fire though, which causes read permissions to be granted to the
1149 // renderer for any file paths in the drop.
1150 filtered_data.filenames.clear();
1151 for (std::vector<ui::FileInfo>::const_iterator it =
1152 drop_data.filenames.begin();
1153 it != drop_data.filenames.end();
1154 ++it) {
1155 if (policy->CanReadFile(GetProcess()->GetID(), it->path))
1156 filtered_data.filenames.push_back(*it);
1159 storage::FileSystemContext* file_system_context =
1160 BrowserContext::GetStoragePartition(GetProcess()->GetBrowserContext(),
1161 GetSiteInstance())
1162 ->GetFileSystemContext();
1163 filtered_data.file_system_files.clear();
1164 for (size_t i = 0; i < drop_data.file_system_files.size(); ++i) {
1165 storage::FileSystemURL file_system_url =
1166 file_system_context->CrackURL(drop_data.file_system_files[i].url);
1167 if (policy->CanReadFileSystemFile(GetProcess()->GetID(), file_system_url))
1168 filtered_data.file_system_files.push_back(drop_data.file_system_files[i]);
1171 float scale = GetScaleFactorForView(GetView());
1172 gfx::ImageSkia image(gfx::ImageSkiaRep(bitmap, scale));
1173 view->StartDragging(filtered_data, drag_operations_mask, image,
1174 bitmap_offset_in_dip, event_info);
1177 void RenderViewHostImpl::OnUpdateDragCursor(WebDragOperation current_op) {
1178 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1179 if (view)
1180 view->UpdateDragCursor(current_op);
1183 void RenderViewHostImpl::OnTakeFocus(bool reverse) {
1184 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1185 if (view)
1186 view->TakeFocus(reverse);
1189 void RenderViewHostImpl::OnFocusedNodeChanged(
1190 bool is_editable_node,
1191 const gfx::Rect& node_bounds_in_viewport) {
1192 is_focused_element_editable_ = is_editable_node;
1193 if (view_)
1194 view_->FocusedNodeChanged(is_editable_node);
1195 #if defined(OS_WIN)
1196 if (!is_editable_node && virtual_keyboard_requested_) {
1197 virtual_keyboard_requested_ = false;
1198 delegate_->SetIsVirtualKeyboardRequested(false);
1199 BrowserThread::PostDelayedTask(
1200 BrowserThread::UI, FROM_HERE,
1201 base::Bind(base::IgnoreResult(&DismissVirtualKeyboardTask)),
1202 TimeDelta::FromMilliseconds(kVirtualKeyboardDisplayWaitTimeoutMs));
1204 #endif
1206 // Convert node_bounds to screen coordinates.
1207 gfx::Rect view_bounds_in_screen = view_->GetViewBounds();
1208 gfx::Point origin = node_bounds_in_viewport.origin();
1209 origin.Offset(view_bounds_in_screen.x(), view_bounds_in_screen.y());
1210 gfx::Rect node_bounds_in_screen(origin.x(), origin.y(),
1211 node_bounds_in_viewport.width(),
1212 node_bounds_in_viewport.height());
1213 FocusedNodeDetails details = {is_editable_node, node_bounds_in_screen};
1214 NotificationService::current()->Notify(NOTIFICATION_FOCUS_CHANGED_IN_PAGE,
1215 Source<RenderViewHost>(this),
1216 Details<FocusedNodeDetails>(&details));
1219 void RenderViewHostImpl::OnUserGesture() {
1220 delegate_->OnUserGesture();
1223 void RenderViewHostImpl::OnClosePageACK() {
1224 decrement_in_flight_event_count();
1225 ClosePageIgnoringUnloadEvents();
1228 void RenderViewHostImpl::NotifyRendererUnresponsive() {
1229 delegate_->RendererUnresponsive(this);
1232 void RenderViewHostImpl::NotifyRendererResponsive() {
1233 delegate_->RendererResponsive(this);
1236 void RenderViewHostImpl::RequestToLockMouse(bool user_gesture,
1237 bool last_unlocked_by_target) {
1238 delegate_->RequestToLockMouse(user_gesture, last_unlocked_by_target);
1241 bool RenderViewHostImpl::IsFullscreenGranted() const {
1242 return delegate_->IsFullscreenForCurrentTab();
1245 blink::WebDisplayMode RenderViewHostImpl::GetDisplayMode() const {
1246 return delegate_->GetDisplayMode();
1249 void RenderViewHostImpl::OnFocus() {
1250 // Note: We allow focus and blur from swapped out RenderViewHosts, even when
1251 // the active RenderViewHost is in a different BrowsingInstance (e.g., WebUI).
1252 delegate_->Activate();
1255 void RenderViewHostImpl::OnBlur() {
1256 delegate_->Deactivate();
1259 gfx::Rect RenderViewHostImpl::GetRootWindowResizerRect() const {
1260 return delegate_->GetRootWindowResizerRect();
1263 void RenderViewHostImpl::ForwardMouseEvent(
1264 const blink::WebMouseEvent& mouse_event) {
1265 RenderWidgetHostImpl::ForwardMouseEvent(mouse_event);
1266 if (mouse_event.type == WebInputEvent::MouseWheel && ignore_input_events())
1267 delegate_->OnIgnoredUIEvent();
1270 void RenderViewHostImpl::ForwardKeyboardEvent(
1271 const NativeWebKeyboardEvent& key_event) {
1272 if (ignore_input_events()) {
1273 if (key_event.type == WebInputEvent::RawKeyDown)
1274 delegate_->OnIgnoredUIEvent();
1275 return;
1277 RenderWidgetHostImpl::ForwardKeyboardEvent(key_event);
1280 void RenderViewHostImpl::OnTextSurroundingSelectionResponse(
1281 const base::string16& content,
1282 size_t start_offset,
1283 size_t end_offset) {
1284 if (!view_)
1285 return;
1286 view_->OnTextSurroundingSelectionResponse(content, start_offset, end_offset);
1289 WebPreferences RenderViewHostImpl::GetWebkitPreferences() {
1290 if (!web_preferences_.get()) {
1291 OnWebkitPreferencesChanged();
1293 return *web_preferences_;
1296 void RenderViewHostImpl::UpdateWebkitPreferences(const WebPreferences& prefs) {
1297 web_preferences_.reset(new WebPreferences(prefs));
1298 Send(new ViewMsg_UpdateWebPreferences(GetRoutingID(), prefs));
1301 void RenderViewHostImpl::OnWebkitPreferencesChanged() {
1302 // This is defensive code to avoid infinite loops due to code run inside
1303 // UpdateWebkitPreferences() accidentally updating more preferences and thus
1304 // calling back into this code. See crbug.com/398751 for one past example.
1305 if (updating_web_preferences_)
1306 return;
1307 updating_web_preferences_ = true;
1308 UpdateWebkitPreferences(ComputeWebkitPrefs());
1309 updating_web_preferences_ = false;
1312 void RenderViewHostImpl::ClearFocusedElement() {
1313 is_focused_element_editable_ = false;
1314 Send(new ViewMsg_ClearFocusedElement(GetRoutingID()));
1317 bool RenderViewHostImpl::IsFocusedElementEditable() {
1318 return is_focused_element_editable_;
1321 void RenderViewHostImpl::Zoom(PageZoom zoom) {
1322 Send(new ViewMsg_Zoom(GetRoutingID(), zoom));
1325 void RenderViewHostImpl::DisableScrollbarsForThreshold(const gfx::Size& size) {
1326 Send(new ViewMsg_DisableScrollbarsForSmallWindows(GetRoutingID(), size));
1329 void RenderViewHostImpl::EnablePreferredSizeMode() {
1330 Send(new ViewMsg_EnablePreferredSizeChangedMode(GetRoutingID()));
1333 void RenderViewHostImpl::EnableAutoResize(const gfx::Size& min_size,
1334 const gfx::Size& max_size) {
1335 SetAutoResize(true, min_size, max_size);
1336 Send(new ViewMsg_EnableAutoResize(GetRoutingID(), min_size, max_size));
1339 void RenderViewHostImpl::DisableAutoResize(const gfx::Size& new_size) {
1340 SetAutoResize(false, gfx::Size(), gfx::Size());
1341 Send(new ViewMsg_DisableAutoResize(GetRoutingID(), new_size));
1342 if (!new_size.IsEmpty())
1343 GetView()->SetSize(new_size);
1346 void RenderViewHostImpl::CopyImageAt(int x, int y) {
1347 Send(new ViewMsg_CopyImageAt(GetRoutingID(), x, y));
1350 void RenderViewHostImpl::SaveImageAt(int x, int y) {
1351 Send(new ViewMsg_SaveImageAt(GetRoutingID(), x, y));
1354 void RenderViewHostImpl::ExecuteMediaPlayerActionAtLocation(
1355 const gfx::Point& location, const blink::WebMediaPlayerAction& action) {
1356 Send(new ViewMsg_MediaPlayerActionAt(GetRoutingID(), location, action));
1359 void RenderViewHostImpl::ExecutePluginActionAtLocation(
1360 const gfx::Point& location, const blink::WebPluginAction& action) {
1361 Send(new ViewMsg_PluginActionAt(GetRoutingID(), location, action));
1364 void RenderViewHostImpl::NotifyMoveOrResizeStarted() {
1365 Send(new ViewMsg_MoveOrResizeStarted(GetRoutingID()));
1368 void RenderViewHostImpl::OnDidZoomURL(double zoom_level,
1369 const GURL& url) {
1370 HostZoomMapImpl* host_zoom_map =
1371 static_cast<HostZoomMapImpl*>(HostZoomMap::Get(GetSiteInstance()));
1373 host_zoom_map->SetZoomLevelForView(GetProcess()->GetID(),
1374 GetRoutingID(),
1375 zoom_level,
1376 net::GetHostOrSpecFromURL(url));
1379 void RenderViewHostImpl::OnPageScaleFactorIsOneChanged(bool is_one) {
1380 if (!GetSiteInstance())
1381 return;
1382 HostZoomMapImpl* host_zoom_map =
1383 static_cast<HostZoomMapImpl*>(HostZoomMap::Get(GetSiteInstance()));
1384 if (!host_zoom_map)
1385 return;
1386 if (!GetProcess())
1387 return;
1388 host_zoom_map->SetPageScaleFactorIsOneForView(GetProcess()->GetID(),
1389 GetRoutingID(), is_one);
1392 void RenderViewHostImpl::OnRunFileChooser(const FileChooserParams& params) {
1393 // Do not allow messages with absolute paths in them as this can permit a
1394 // renderer to coerce the browser to perform I/O on a renderer controlled
1395 // path.
1396 if (params.default_file_name != params.default_file_name.BaseName()) {
1397 bad_message::ReceivedBadMessage(GetProcess(),
1398 bad_message::RVH_FILE_CHOOSER_PATH);
1399 return;
1402 delegate_->RunFileChooser(this, params);
1405 void RenderViewHostImpl::OnFocusedNodeTouched(bool editable) {
1406 #if defined(OS_WIN)
1407 if (editable) {
1408 virtual_keyboard_requested_ = base::win::DisplayVirtualKeyboard();
1409 delegate_->SetIsVirtualKeyboardRequested(true);
1410 } else {
1411 virtual_keyboard_requested_ = false;
1412 delegate_->SetIsVirtualKeyboardRequested(false);
1413 base::win::DismissVirtualKeyboard();
1415 #endif
1418 bool RenderViewHostImpl::CanAccessFilesOfPageState(
1419 const PageState& state) const {
1420 ChildProcessSecurityPolicyImpl* policy =
1421 ChildProcessSecurityPolicyImpl::GetInstance();
1423 const std::vector<base::FilePath>& file_paths = state.GetReferencedFiles();
1424 for (const auto& file : file_paths) {
1425 if (!policy->CanReadFile(GetProcess()->GetID(), file))
1426 return false;
1428 return true;
1431 void RenderViewHostImpl::GrantFileAccessFromPageState(const PageState& state) {
1432 ChildProcessSecurityPolicyImpl* policy =
1433 ChildProcessSecurityPolicyImpl::GetInstance();
1435 const std::vector<base::FilePath>& file_paths = state.GetReferencedFiles();
1436 for (const auto& file : file_paths) {
1437 if (!policy->CanReadFile(GetProcess()->GetID(), file))
1438 policy->GrantReadFile(GetProcess()->GetID(), file);
1442 void RenderViewHostImpl::SelectWordAroundCaret() {
1443 Send(new ViewMsg_SelectWordAroundCaret(GetRoutingID()));
1446 } // namespace content