[Session restore] Rename group name Enabled to Restore.
[chromium-blink-merge.git] / content / browser / renderer_host / render_view_host_impl.cc
blob730860e8ada8549224b94356ab45d66da0ee4d2d
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 int routing_id,
203 int main_frame_routing_id,
204 bool swapped_out,
205 bool hidden,
206 bool has_initialized_audio_host)
207 : RenderWidgetHostImpl(widget_delegate,
208 instance->GetProcess(),
209 routing_id,
210 hidden),
211 frames_ref_count_(0),
212 delegate_(delegate),
213 instance_(static_cast<SiteInstanceImpl*>(instance)),
214 waiting_for_drag_context_response_(false),
215 enabled_bindings_(0),
216 page_id_(-1),
217 is_active_(!swapped_out),
218 is_swapped_out_(swapped_out),
219 main_frame_routing_id_(main_frame_routing_id),
220 is_waiting_for_close_ack_(false),
221 sudden_termination_allowed_(false),
222 render_view_termination_status_(base::TERMINATION_STATUS_STILL_RUNNING),
223 virtual_keyboard_requested_(false),
224 is_focused_element_editable_(false),
225 updating_web_preferences_(false),
226 weak_factory_(this) {
227 DCHECK(instance_.get());
228 CHECK(delegate_); // http://crbug.com/82827
230 GetProcess()->EnableSendQueue();
232 if (ResourceDispatcherHostImpl::Get()) {
233 bool has_active_audio = false;
234 if (has_initialized_audio_host) {
235 scoped_refptr<AudioRendererHost> arh =
236 static_cast<RenderProcessHostImpl*>(GetProcess())
237 ->audio_renderer_host();
238 if (arh.get())
239 has_active_audio =
240 arh->RenderFrameHasActiveAudio(main_frame_routing_id_);
242 BrowserThread::PostTask(
243 BrowserThread::IO,
244 FROM_HERE,
245 base::Bind(&ResourceDispatcherHostImpl::OnRenderViewHostCreated,
246 base::Unretained(ResourceDispatcherHostImpl::Get()),
247 GetProcess()->GetID(),
248 GetRoutingID(),
249 !is_hidden(),
250 has_active_audio));
254 RenderViewHostImpl::~RenderViewHostImpl() {
255 if (ResourceDispatcherHostImpl::Get()) {
256 BrowserThread::PostTask(
257 BrowserThread::IO, FROM_HERE,
258 base::Bind(&ResourceDispatcherHostImpl::OnRenderViewHostDeleted,
259 base::Unretained(ResourceDispatcherHostImpl::Get()),
260 GetProcess()->GetID(), GetRoutingID()));
263 delegate_->RenderViewDeleted(this);
266 RenderViewHostDelegate* RenderViewHostImpl::GetDelegate() const {
267 return delegate_;
270 SiteInstanceImpl* RenderViewHostImpl::GetSiteInstance() const {
271 return instance_.get();
274 bool RenderViewHostImpl::CreateRenderView(
275 const base::string16& frame_name,
276 int opener_route_id,
277 int proxy_route_id,
278 int32 max_page_id,
279 bool window_was_created_with_opener) {
280 TRACE_EVENT0("renderer_host,navigation",
281 "RenderViewHostImpl::CreateRenderView");
282 DCHECK(!IsRenderViewLive()) << "Creating view twice";
284 // The process may (if we're sharing a process with another host that already
285 // initialized it) or may not (we have our own process or the old process
286 // crashed) have been initialized. Calling Init multiple times will be
287 // ignored, so this is safe.
288 if (!GetProcess()->Init())
289 return false;
290 DCHECK(GetProcess()->HasConnection());
291 DCHECK(GetProcess()->GetBrowserContext());
293 renderer_initialized_ = true;
295 GpuSurfaceTracker::Get()->SetSurfaceHandle(
296 surface_id(), GetCompositingSurface());
298 // Ensure the RenderView starts with a next_page_id larger than any existing
299 // page ID it might be asked to render.
300 int32 next_page_id = 1;
301 if (max_page_id > -1)
302 next_page_id = max_page_id + 1;
304 ViewMsg_New_Params params;
305 params.renderer_preferences =
306 delegate_->GetRendererPrefs(GetProcess()->GetBrowserContext());
307 #if defined(OS_WIN)
308 GetWindowsSpecificPrefs(&params.renderer_preferences);
309 #endif
310 params.web_preferences = GetWebkitPreferences();
311 params.view_id = GetRoutingID();
312 params.main_frame_routing_id = main_frame_routing_id_;
313 params.surface_id = surface_id();
314 params.session_storage_namespace_id =
315 delegate_->GetSessionStorageNamespace(instance_.get())->id();
316 params.frame_name = frame_name;
317 // Ensure the RenderView sets its opener correctly.
318 params.opener_route_id = opener_route_id;
319 params.swapped_out = !is_active_;
320 params.proxy_routing_id = proxy_route_id;
321 params.hidden = is_hidden();
322 params.never_visible = delegate_->IsNeverVisible();
323 params.window_was_created_with_opener = window_was_created_with_opener;
324 params.next_page_id = next_page_id;
325 params.enable_auto_resize = auto_resize_enabled();
326 params.min_size = min_size_for_auto_resize();
327 params.max_size = max_size_for_auto_resize();
328 GetResizeParams(&params.initial_size);
329 if (!is_active_) {
330 params.replicated_frame_state =
331 static_cast<RenderFrameHostImpl*>(GetMainFrame())->frame_tree_node()
332 ->current_replication_state();
335 if (!Send(new ViewMsg_New(params)))
336 return false;
337 SetInitialRenderSizeParams(params.initial_size);
339 // If it's enabled, tell the renderer to set up the Javascript bindings for
340 // sending messages back to the browser.
341 if (GetProcess()->IsIsolatedGuest())
342 DCHECK_EQ(0, enabled_bindings_);
343 Send(new ViewMsg_AllowBindings(GetRoutingID(), enabled_bindings_));
344 // Let our delegate know that we created a RenderView.
345 delegate_->RenderViewCreated(this);
347 // Since this method creates the main RenderFrame in the renderer process,
348 // set the proper state on its corresponding RenderFrameHost.
349 RenderFrameHostImpl::FromID(GetProcess()->GetID(), main_frame_routing_id_)
350 ->SetRenderFrameCreated(true);
352 return true;
355 bool RenderViewHostImpl::IsRenderViewLive() const {
356 return GetProcess()->HasConnection() && renderer_initialized_;
359 void RenderViewHostImpl::SyncRendererPrefs() {
360 Send(new ViewMsg_SetRendererPrefs(GetRoutingID(),
361 delegate_->GetRendererPrefs(
362 GetProcess()->GetBrowserContext())));
365 WebPreferences RenderViewHostImpl::ComputeWebkitPrefs() {
366 TRACE_EVENT0("browser", "RenderViewHostImpl::GetWebkitPrefs");
367 WebPreferences prefs;
369 const base::CommandLine& command_line =
370 *base::CommandLine::ForCurrentProcess();
372 prefs.web_security_enabled =
373 !command_line.HasSwitch(switches::kDisableWebSecurity);
374 prefs.java_enabled =
375 !command_line.HasSwitch(switches::kDisableJava);
377 prefs.remote_fonts_enabled =
378 !command_line.HasSwitch(switches::kDisableRemoteFonts);
379 prefs.application_cache_enabled = true;
380 prefs.xss_auditor_enabled =
381 !command_line.HasSwitch(switches::kDisableXSSAuditor);
382 prefs.local_storage_enabled =
383 !command_line.HasSwitch(switches::kDisableLocalStorage);
384 prefs.databases_enabled =
385 !command_line.HasSwitch(switches::kDisableDatabases);
386 #if defined(OS_ANDROID)
387 // WebAudio is enabled by default on x86 and ARM.
388 prefs.webaudio_enabled =
389 !command_line.HasSwitch(switches::kDisableWebAudio);
390 #endif
392 prefs.experimental_webgl_enabled =
393 GpuProcessHost::gpu_enabled() &&
394 !command_line.HasSwitch(switches::kDisable3DAPIs) &&
395 !command_line.HasSwitch(switches::kDisableExperimentalWebGL);
397 prefs.pepper_3d_enabled =
398 !command_line.HasSwitch(switches::kDisablePepper3d);
400 prefs.flash_3d_enabled =
401 GpuProcessHost::gpu_enabled() &&
402 !command_line.HasSwitch(switches::kDisableFlash3d);
403 prefs.flash_stage3d_enabled =
404 GpuProcessHost::gpu_enabled() &&
405 !command_line.HasSwitch(switches::kDisableFlashStage3d);
406 prefs.flash_stage3d_baseline_enabled =
407 GpuProcessHost::gpu_enabled() &&
408 !command_line.HasSwitch(switches::kDisableFlashStage3d);
410 prefs.allow_file_access_from_file_urls =
411 command_line.HasSwitch(switches::kAllowFileAccessFromFiles);
413 prefs.accelerated_2d_canvas_enabled =
414 GpuProcessHost::gpu_enabled() &&
415 !command_line.HasSwitch(switches::kDisableAccelerated2dCanvas);
416 prefs.antialiased_2d_canvas_disabled =
417 command_line.HasSwitch(switches::kDisable2dCanvasAntialiasing);
418 prefs.antialiased_clips_2d_canvas_enabled =
419 command_line.HasSwitch(switches::kEnable2dCanvasClipAntialiasing);
420 prefs.accelerated_2d_canvas_msaa_sample_count =
421 atoi(command_line.GetSwitchValueASCII(
422 switches::kAcceleratedCanvas2dMSAASampleCount).c_str());
423 // Text blobs rely on impl-side painting for proper LCD handling.
424 prefs.text_blobs_enabled = command_line.HasSwitch(switches::kForceTextBlobs)
425 || (content::IsImplSidePaintingEnabled() &&
426 !command_line.HasSwitch(switches::kDisableTextBlobs));
427 prefs.region_based_columns_enabled =
428 command_line.HasSwitch(switches::kEnableRegionBasedColumns);
430 if (IsPinchVirtualViewportEnabled()) {
431 prefs.pinch_virtual_viewport_enabled = true;
432 prefs.pinch_overlay_scrollbar_thickness = 10;
434 prefs.use_solid_color_scrollbars = ui::IsOverlayScrollbarEnabled();
436 #if defined(OS_ANDROID)
437 // On Android, user gestures are normally required, unless that requirement
438 // is disabled with a command-line switch or the equivalent field trial is
439 // is set to "Enabled".
440 const std::string autoplay_group_name = base::FieldTrialList::FindFullName(
441 "MediaElementAutoplay");
442 prefs.user_gesture_required_for_media_playback = !command_line.HasSwitch(
443 switches::kDisableGestureRequirementForMediaPlayback) &&
444 (autoplay_group_name.empty() || autoplay_group_name != "Enabled");
445 #endif
447 prefs.touch_enabled = ui::AreTouchEventsEnabled();
448 prefs.device_supports_touch = prefs.touch_enabled &&
449 ui::IsTouchDevicePresent();
450 prefs.available_pointer_types = ui::GetAvailablePointerTypes();
451 prefs.primary_pointer_type = ui::GetPrimaryPointerType();
452 prefs.available_hover_types = ui::GetAvailableHoverTypes();
453 prefs.primary_hover_type = ui::GetPrimaryHoverType();
455 #if defined(OS_ANDROID)
456 prefs.device_supports_mouse = false;
457 #endif
459 prefs.pointer_events_max_touch_points = ui::MaxTouchPoints();
461 prefs.touch_adjustment_enabled =
462 !command_line.HasSwitch(switches::kDisableTouchAdjustment);
464 prefs.slimming_paint_enabled =
465 command_line.HasSwitch(switches::kEnableSlimmingPaint);
467 #if defined(OS_MACOSX) || defined(OS_CHROMEOS)
468 bool default_enable_scroll_animator = true;
469 #else
470 bool default_enable_scroll_animator = false;
471 #endif
472 prefs.enable_scroll_animator = default_enable_scroll_animator;
473 if (command_line.HasSwitch(switches::kEnableSmoothScrolling))
474 prefs.enable_scroll_animator = true;
475 if (command_line.HasSwitch(switches::kDisableSmoothScrolling))
476 prefs.enable_scroll_animator = false;
478 // Certain GPU features might have been blacklisted.
479 GpuDataManagerImpl::GetInstance()->UpdateRendererWebPrefs(&prefs);
481 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
482 GetProcess()->GetID())) {
483 prefs.loads_images_automatically = true;
484 prefs.javascript_enabled = true;
487 prefs.connection_type = net::NetworkChangeNotifier::GetConnectionType();
488 prefs.is_online =
489 prefs.connection_type != net::NetworkChangeNotifier::CONNECTION_NONE;
491 prefs.number_of_cpu_cores = base::SysInfo::NumberOfProcessors();
493 prefs.viewport_meta_enabled =
494 command_line.HasSwitch(switches::kEnableViewportMeta);
496 prefs.viewport_enabled =
497 command_line.HasSwitch(switches::kEnableViewport) ||
498 prefs.viewport_meta_enabled;
500 prefs.main_frame_resizes_are_orientation_changes =
501 command_line.HasSwitch(switches::kMainFrameResizesAreOrientationChanges);
503 prefs.deferred_image_decoding_enabled =
504 command_line.HasSwitch(switches::kEnableDeferredImageDecoding) ||
505 content::IsImplSidePaintingEnabled();
507 prefs.image_color_profiles_enabled =
508 command_line.HasSwitch(switches::kEnableImageColorProfiles);
510 prefs.spatial_navigation_enabled = command_line.HasSwitch(
511 switches::kEnableSpatialNavigation);
513 prefs.disable_reading_from_canvas = command_line.HasSwitch(
514 switches::kDisableReadingFromCanvas);
516 prefs.strict_mixed_content_checking = command_line.HasSwitch(
517 switches::kEnableStrictMixedContentChecking);
519 prefs.strict_powerful_feature_restrictions = command_line.HasSwitch(
520 switches::kEnableStrictPowerfulFeatureRestrictions);
522 prefs.v8_cache_options = GetV8CacheOptions();
524 GetContentClient()->browser()->OverrideWebkitPrefs(this, &prefs);
525 return prefs;
528 void RenderViewHostImpl::SuppressDialogsUntilSwapOut() {
529 Send(new ViewMsg_SuppressDialogsUntilSwapOut(GetRoutingID()));
532 void RenderViewHostImpl::ClosePage() {
533 is_waiting_for_close_ack_ = true;
534 StartHangMonitorTimeout(TimeDelta::FromMilliseconds(kUnloadTimeoutMS));
536 if (IsRenderViewLive()) {
537 // Since we are sending an IPC message to the renderer, increase the event
538 // count to prevent the hang monitor timeout from being stopped by input
539 // event acknowledgements.
540 increment_in_flight_event_count();
542 // TODO(creis): Should this be moved to Shutdown? It may not be called for
543 // RenderViewHosts that have been swapped out.
544 NotificationService::current()->Notify(
545 NOTIFICATION_RENDER_VIEW_HOST_WILL_CLOSE_RENDER_VIEW,
546 Source<RenderViewHost>(this),
547 NotificationService::NoDetails());
549 Send(new ViewMsg_ClosePage(GetRoutingID()));
550 } else {
551 // This RenderViewHost doesn't have a live renderer, so just skip the unload
552 // event and close the page.
553 ClosePageIgnoringUnloadEvents();
557 void RenderViewHostImpl::ClosePageIgnoringUnloadEvents() {
558 StopHangMonitorTimeout();
559 is_waiting_for_close_ack_ = false;
561 sudden_termination_allowed_ = true;
562 delegate_->Close(this);
565 #if defined(OS_ANDROID)
566 void RenderViewHostImpl::ActivateNearestFindResult(int request_id,
567 float x,
568 float y) {
569 Send(new InputMsg_ActivateNearestFindResult(GetRoutingID(),
570 request_id, x, y));
573 void RenderViewHostImpl::RequestFindMatchRects(int current_version) {
574 Send(new ViewMsg_FindMatchRects(GetRoutingID(), current_version));
576 #endif
578 void RenderViewHostImpl::DragTargetDragEnter(
579 const DropData& drop_data,
580 const gfx::Point& client_pt,
581 const gfx::Point& screen_pt,
582 WebDragOperationsMask operations_allowed,
583 int key_modifiers) {
584 const int renderer_id = GetProcess()->GetID();
585 ChildProcessSecurityPolicyImpl* policy =
586 ChildProcessSecurityPolicyImpl::GetInstance();
588 #if defined(OS_CHROMEOS)
589 // The externalfile:// scheme is used in Chrome OS to open external files in a
590 // browser tab.
591 if (drop_data.url.SchemeIs(content::kExternalFileScheme))
592 policy->GrantRequestURL(renderer_id, drop_data.url);
593 #endif
595 // The URL could have been cobbled together from any highlighted text string,
596 // and can't be interpreted as a capability.
597 DropData filtered_data(drop_data);
598 GetProcess()->FilterURL(true, &filtered_data.url);
599 if (drop_data.did_originate_from_renderer) {
600 filtered_data.filenames.clear();
603 // The filenames vector, on the other hand, does represent a capability to
604 // access the given files.
605 storage::IsolatedContext::FileInfoSet files;
606 for (std::vector<ui::FileInfo>::iterator iter(
607 filtered_data.filenames.begin());
608 iter != filtered_data.filenames.end();
609 ++iter) {
610 // A dragged file may wind up as the value of an input element, or it
611 // may be used as the target of a navigation instead. We don't know
612 // which will happen at this point, so generously grant both access
613 // and request permissions to the specific file to cover both cases.
614 // We do not give it the permission to request all file:// URLs.
616 // Make sure we have the same display_name as the one we register.
617 if (iter->display_name.empty()) {
618 std::string name;
619 files.AddPath(iter->path, &name);
620 iter->display_name = base::FilePath::FromUTF8Unsafe(name);
621 } else {
622 files.AddPathWithName(iter->path, iter->display_name.AsUTF8Unsafe());
625 policy->GrantRequestSpecificFileURL(renderer_id,
626 net::FilePathToFileURL(iter->path));
628 // If the renderer already has permission to read these paths, we don't need
629 // to re-grant them. This prevents problems with DnD for files in the CrOS
630 // file manager--the file manager already had read/write access to those
631 // directories, but dragging a file would cause the read/write access to be
632 // overwritten with read-only access, making them impossible to delete or
633 // rename until the renderer was killed.
634 if (!policy->CanReadFile(renderer_id, iter->path))
635 policy->GrantReadFile(renderer_id, iter->path);
638 storage::IsolatedContext* isolated_context =
639 storage::IsolatedContext::GetInstance();
640 DCHECK(isolated_context);
641 std::string filesystem_id = isolated_context->RegisterDraggedFileSystem(
642 files);
643 if (!filesystem_id.empty()) {
644 // Grant the permission iff the ID is valid.
645 policy->GrantReadFileSystem(renderer_id, filesystem_id);
647 filtered_data.filesystem_id = base::UTF8ToUTF16(filesystem_id);
649 storage::FileSystemContext* file_system_context =
650 BrowserContext::GetStoragePartition(GetProcess()->GetBrowserContext(),
651 GetSiteInstance())
652 ->GetFileSystemContext();
653 for (size_t i = 0; i < filtered_data.file_system_files.size(); ++i) {
654 storage::FileSystemURL file_system_url =
655 file_system_context->CrackURL(filtered_data.file_system_files[i].url);
657 std::string register_name;
658 std::string filesystem_id = isolated_context->RegisterFileSystemForPath(
659 file_system_url.type(), file_system_url.filesystem_id(),
660 file_system_url.path(), &register_name);
661 policy->GrantReadFileSystem(renderer_id, filesystem_id);
663 // Note: We are using the origin URL provided by the sender here. It may be
664 // different from the receiver's.
665 filtered_data.file_system_files[i].url =
666 GURL(storage::GetIsolatedFileSystemRootURIString(
667 file_system_url.origin(), filesystem_id, std::string())
668 .append(register_name));
671 Send(new DragMsg_TargetDragEnter(GetRoutingID(), filtered_data, client_pt,
672 screen_pt, operations_allowed,
673 key_modifiers));
676 void RenderViewHostImpl::DragTargetDragOver(
677 const gfx::Point& client_pt,
678 const gfx::Point& screen_pt,
679 WebDragOperationsMask operations_allowed,
680 int key_modifiers) {
681 Send(new DragMsg_TargetDragOver(GetRoutingID(), client_pt, screen_pt,
682 operations_allowed, key_modifiers));
685 void RenderViewHostImpl::DragTargetDragLeave() {
686 Send(new DragMsg_TargetDragLeave(GetRoutingID()));
689 void RenderViewHostImpl::DragTargetDrop(
690 const gfx::Point& client_pt,
691 const gfx::Point& screen_pt,
692 int key_modifiers) {
693 Send(new DragMsg_TargetDrop(GetRoutingID(), client_pt, screen_pt,
694 key_modifiers));
697 void RenderViewHostImpl::DragSourceEndedAt(
698 int client_x, int client_y, int screen_x, int screen_y,
699 WebDragOperation operation) {
700 Send(new DragMsg_SourceEnded(GetRoutingID(),
701 gfx::Point(client_x, client_y),
702 gfx::Point(screen_x, screen_y),
703 operation));
706 void RenderViewHostImpl::DragSourceSystemDragEnded() {
707 Send(new DragMsg_SourceSystemDragEnded(GetRoutingID()));
710 RenderFrameHost* RenderViewHostImpl::GetMainFrame() {
711 return RenderFrameHost::FromID(GetProcess()->GetID(), main_frame_routing_id_);
714 void RenderViewHostImpl::AllowBindings(int bindings_flags) {
715 // Never grant any bindings to browser plugin guests.
716 if (GetProcess()->IsIsolatedGuest()) {
717 NOTREACHED() << "Never grant bindings to a guest process.";
718 return;
721 // Ensure we aren't granting WebUI bindings to a process that has already
722 // been used for non-privileged views.
723 if (bindings_flags & BINDINGS_POLICY_WEB_UI &&
724 GetProcess()->HasConnection() &&
725 !ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
726 GetProcess()->GetID())) {
727 // This process has no bindings yet. Make sure it does not have more
728 // than this single active view.
729 // --single-process only has one renderer.
730 if (GetProcess()->GetActiveViewCount() > 1 &&
731 !base::CommandLine::ForCurrentProcess()->HasSwitch(
732 switches::kSingleProcess))
733 return;
736 if (bindings_flags & BINDINGS_POLICY_WEB_UI) {
737 ChildProcessSecurityPolicyImpl::GetInstance()->GrantWebUIBindings(
738 GetProcess()->GetID());
741 enabled_bindings_ |= bindings_flags;
742 if (renderer_initialized_)
743 Send(new ViewMsg_AllowBindings(GetRoutingID(), enabled_bindings_));
746 int RenderViewHostImpl::GetEnabledBindings() const {
747 return enabled_bindings_;
750 void RenderViewHostImpl::SetWebUIProperty(const std::string& name,
751 const std::string& value) {
752 // This is a sanity check before telling the renderer to enable the property.
753 // It could lie and send the corresponding IPC messages anyway, but we will
754 // not act on them if enabled_bindings_ doesn't agree. If we get here without
755 // WebUI bindings, kill the renderer process.
756 if (enabled_bindings_ & BINDINGS_POLICY_WEB_UI) {
757 Send(new ViewMsg_SetWebUIProperty(GetRoutingID(), name, value));
758 } else {
759 RecordAction(
760 base::UserMetricsAction("BindingsMismatchTerminate_RVH_WebUI"));
761 GetProcess()->Shutdown(content::RESULT_CODE_KILLED, false);
765 void RenderViewHostImpl::GotFocus() {
766 RenderWidgetHostImpl::GotFocus(); // Notifies the renderer it got focus.
768 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
769 if (view)
770 view->GotFocus();
773 void RenderViewHostImpl::LostCapture() {
774 RenderWidgetHostImpl::LostCapture();
775 delegate_->LostCapture();
778 void RenderViewHostImpl::LostMouseLock() {
779 RenderWidgetHostImpl::LostMouseLock();
780 delegate_->LostMouseLock();
783 void RenderViewHostImpl::SetInitialFocus(bool reverse) {
784 Send(new ViewMsg_SetInitialFocus(GetRoutingID(), reverse));
787 void RenderViewHostImpl::FilesSelectedInChooser(
788 const std::vector<content::FileChooserFileInfo>& files,
789 FileChooserParams::Mode permissions) {
790 storage::FileSystemContext* const file_system_context =
791 BrowserContext::GetStoragePartition(GetProcess()->GetBrowserContext(),
792 GetSiteInstance())
793 ->GetFileSystemContext();
794 // Grant the security access requested to the given files.
795 for (size_t i = 0; i < files.size(); ++i) {
796 const content::FileChooserFileInfo& file = files[i];
797 if (permissions == FileChooserParams::Save) {
798 ChildProcessSecurityPolicyImpl::GetInstance()->GrantCreateReadWriteFile(
799 GetProcess()->GetID(), file.file_path);
800 } else {
801 ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
802 GetProcess()->GetID(), file.file_path);
804 if (file.file_system_url.is_valid()) {
805 ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFileSystem(
806 GetProcess()->GetID(),
807 file_system_context->CrackURL(file.file_system_url)
808 .mount_filesystem_id());
811 Send(new ViewMsg_RunFileChooserResponse(GetRoutingID(), files));
814 void RenderViewHostImpl::DirectoryEnumerationFinished(
815 int request_id,
816 const std::vector<base::FilePath>& files) {
817 // Grant the security access requested to the given files.
818 for (std::vector<base::FilePath>::const_iterator file = files.begin();
819 file != files.end(); ++file) {
820 ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
821 GetProcess()->GetID(), *file);
823 Send(new ViewMsg_EnumerateDirectoryResponse(GetRoutingID(),
824 request_id,
825 files));
828 void RenderViewHostImpl::SetIsLoading(bool is_loading) {
829 if (ResourceDispatcherHostImpl::Get()) {
830 BrowserThread::PostTask(
831 BrowserThread::IO,
832 FROM_HERE,
833 base::Bind(&ResourceDispatcherHostImpl::OnRenderViewHostSetIsLoading,
834 base::Unretained(ResourceDispatcherHostImpl::Get()),
835 GetProcess()->GetID(),
836 GetRoutingID(),
837 is_loading));
839 RenderWidgetHostImpl::SetIsLoading(is_loading);
842 void RenderViewHostImpl::LoadStateChanged(
843 const GURL& url,
844 const net::LoadStateWithParam& load_state,
845 uint64 upload_position,
846 uint64 upload_size) {
847 delegate_->LoadStateChanged(url, load_state, upload_position, upload_size);
850 bool RenderViewHostImpl::SuddenTerminationAllowed() const {
851 return sudden_termination_allowed_ ||
852 GetProcess()->SuddenTerminationAllowed();
855 ///////////////////////////////////////////////////////////////////////////////
856 // RenderViewHostImpl, IPC message handlers:
858 bool RenderViewHostImpl::OnMessageReceived(const IPC::Message& msg) {
859 if (!BrowserMessageFilter::CheckCanDispatchOnUI(msg, this))
860 return true;
862 // Filter out most IPC messages if this renderer is swapped out.
863 // We still want to handle certain ACKs to keep our state consistent.
864 if (is_swapped_out_) {
865 if (!SwappedOutMessages::CanHandleWhileSwappedOut(msg)) {
866 // If this is a synchronous message and we decided not to handle it,
867 // we must send an error reply, or else the renderer will be stuck
868 // and won't respond to future requests.
869 if (msg.is_sync()) {
870 IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
871 reply->set_reply_error();
872 Send(reply);
874 // Don't continue looking for someone to handle it.
875 return true;
879 if (delegate_->OnMessageReceived(this, msg))
880 return true;
882 bool handled = true;
883 IPC_BEGIN_MESSAGE_MAP(RenderViewHostImpl, msg)
884 IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone)
885 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowView, OnShowView)
886 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowWidget, OnShowWidget)
887 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowFullscreenWidget,
888 OnShowFullscreenWidget)
889 IPC_MESSAGE_HANDLER(ViewHostMsg_RenderViewReady, OnRenderViewReady)
890 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateState, OnUpdateState)
891 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateTargetURL, OnUpdateTargetURL)
892 IPC_MESSAGE_HANDLER(ViewHostMsg_Close, OnClose)
893 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestMove, OnRequestMove)
894 IPC_MESSAGE_HANDLER(ViewHostMsg_DocumentAvailableInMainFrame,
895 OnDocumentAvailableInMainFrame)
896 IPC_MESSAGE_HANDLER(ViewHostMsg_DidContentsPreferredSizeChange,
897 OnDidContentsPreferredSizeChange)
898 IPC_MESSAGE_HANDLER(ViewHostMsg_RouteCloseEvent,
899 OnRouteCloseEvent)
900 IPC_MESSAGE_HANDLER(ViewHostMsg_RouteMessageEvent, OnRouteMessageEvent)
901 IPC_MESSAGE_HANDLER(DragHostMsg_StartDragging, OnStartDragging)
902 IPC_MESSAGE_HANDLER(DragHostMsg_UpdateDragCursor, OnUpdateDragCursor)
903 IPC_MESSAGE_HANDLER(DragHostMsg_TargetDrop_ACK, OnTargetDropACK)
904 IPC_MESSAGE_HANDLER(ViewHostMsg_TakeFocus, OnTakeFocus)
905 IPC_MESSAGE_HANDLER(ViewHostMsg_FocusedNodeChanged, OnFocusedNodeChanged)
906 IPC_MESSAGE_HANDLER(ViewHostMsg_ClosePage_ACK, OnClosePageACK)
907 IPC_MESSAGE_HANDLER(ViewHostMsg_DidZoomURL, OnDidZoomURL)
908 IPC_MESSAGE_HANDLER(ViewHostMsg_PageScaleFactorIsOneChanged,
909 OnPageScaleFactorIsOneChanged)
910 IPC_MESSAGE_HANDLER(ViewHostMsg_RunFileChooser, OnRunFileChooser)
911 IPC_MESSAGE_HANDLER(ViewHostMsg_FocusedNodeTouched, OnFocusedNodeTouched)
912 // Have the super handle all other messages.
913 IPC_MESSAGE_UNHANDLED(
914 handled = RenderWidgetHostImpl::OnMessageReceived(msg))
915 IPC_END_MESSAGE_MAP()
917 return handled;
920 void RenderViewHostImpl::Init() {
921 RenderWidgetHostImpl::Init();
924 void RenderViewHostImpl::Shutdown() {
925 // We can't release the SessionStorageNamespace until our peer
926 // in the renderer has wound down.
927 if (GetProcess()->HasConnection()) {
928 RenderProcessHostImpl::ReleaseOnCloseACK(
929 GetProcess(),
930 delegate_->GetSessionStorageNamespaceMap(),
931 GetRoutingID());
934 RenderWidgetHostImpl::Shutdown();
937 void RenderViewHostImpl::WasHidden() {
938 if (ResourceDispatcherHostImpl::Get()) {
939 BrowserThread::PostTask(
940 BrowserThread::IO, FROM_HERE,
941 base::Bind(&ResourceDispatcherHostImpl::OnRenderViewHostWasHidden,
942 base::Unretained(ResourceDispatcherHostImpl::Get()),
943 GetProcess()->GetID(), GetRoutingID()));
946 RenderWidgetHostImpl::WasHidden();
949 void RenderViewHostImpl::WasShown(const ui::LatencyInfo& latency_info) {
950 if (ResourceDispatcherHostImpl::Get()) {
951 BrowserThread::PostTask(
952 BrowserThread::IO, FROM_HERE,
953 base::Bind(&ResourceDispatcherHostImpl::OnRenderViewHostWasShown,
954 base::Unretained(ResourceDispatcherHostImpl::Get()),
955 GetProcess()->GetID(), GetRoutingID()));
958 RenderWidgetHostImpl::WasShown(latency_info);
961 bool RenderViewHostImpl::IsRenderView() const {
962 return true;
965 void RenderViewHostImpl::CreateNewWindow(
966 int route_id,
967 int main_frame_route_id,
968 const ViewHostMsg_CreateWindow_Params& params,
969 SessionStorageNamespace* session_storage_namespace) {
970 ViewHostMsg_CreateWindow_Params validated_params(params);
971 GetProcess()->FilterURL(false, &validated_params.target_url);
972 GetProcess()->FilterURL(false, &validated_params.opener_url);
973 GetProcess()->FilterURL(true, &validated_params.opener_security_origin);
975 delegate_->CreateNewWindow(
976 GetProcess()->GetID(), route_id, main_frame_route_id, validated_params,
977 session_storage_namespace);
980 void RenderViewHostImpl::CreateNewWidget(int route_id,
981 blink::WebPopupType popup_type) {
982 delegate_->CreateNewWidget(GetProcess()->GetID(), route_id, popup_type);
985 void RenderViewHostImpl::CreateNewFullscreenWidget(int route_id) {
986 delegate_->CreateNewFullscreenWidget(GetProcess()->GetID(), route_id);
989 void RenderViewHostImpl::OnShowView(int route_id,
990 WindowOpenDisposition disposition,
991 const gfx::Rect& initial_rect,
992 bool user_gesture) {
993 if (is_active_) {
994 delegate_->ShowCreatedWindow(
995 route_id, disposition, initial_rect, user_gesture);
997 Send(new ViewMsg_Move_ACK(route_id));
1000 void RenderViewHostImpl::OnShowWidget(int route_id,
1001 const gfx::Rect& initial_rect) {
1002 if (is_active_)
1003 delegate_->ShowCreatedWidget(route_id, initial_rect);
1004 Send(new ViewMsg_Move_ACK(route_id));
1007 void RenderViewHostImpl::OnShowFullscreenWidget(int route_id) {
1008 if (is_active_)
1009 delegate_->ShowCreatedFullscreenWidget(route_id);
1010 Send(new ViewMsg_Move_ACK(route_id));
1013 void RenderViewHostImpl::OnRenderViewReady() {
1014 render_view_termination_status_ = base::TERMINATION_STATUS_STILL_RUNNING;
1015 SendScreenRects();
1016 WasResized();
1017 delegate_->RenderViewReady(this);
1020 void RenderViewHostImpl::OnRenderProcessGone(int status, int exit_code) {
1021 // Do nothing, otherwise RenderWidgetHostImpl will assume it is not a
1022 // RenderViewHostImpl and destroy itself.
1023 // TODO(nasko): Remove this hack once RenderViewHost and RenderWidgetHost are
1024 // decoupled.
1027 void RenderViewHostImpl::OnUpdateState(int32 page_id, const PageState& state) {
1028 // If the following DCHECK fails, you have encountered a tricky edge-case that
1029 // has evaded reproduction for a very long time. Please report what you were
1030 // doing on http://crbug.com/407376, whether or not you can reproduce the
1031 // failure.
1032 DCHECK_EQ(page_id, page_id_);
1034 // Without this check, the renderer can trick the browser into using
1035 // filenames it can't access in a future session restore.
1036 if (!CanAccessFilesOfPageState(state)) {
1037 bad_message::ReceivedBadMessage(
1038 GetProcess(), bad_message::RVH_CAN_ACCESS_FILES_OF_PAGE_STATE);
1039 return;
1042 delegate_->UpdateState(this, page_id, state);
1045 void RenderViewHostImpl::OnUpdateTargetURL(const GURL& url) {
1046 if (is_active_)
1047 delegate_->UpdateTargetURL(this, url);
1049 // Send a notification back to the renderer that we are ready to
1050 // receive more target urls.
1051 Send(new ViewMsg_UpdateTargetURL_ACK(GetRoutingID()));
1054 void RenderViewHostImpl::OnClose() {
1055 // If the renderer is telling us to close, it has already run the unload
1056 // events, and we can take the fast path.
1057 ClosePageIgnoringUnloadEvents();
1060 void RenderViewHostImpl::OnRequestMove(const gfx::Rect& pos) {
1061 if (is_active_)
1062 delegate_->RequestMove(pos);
1063 Send(new ViewMsg_Move_ACK(GetRoutingID()));
1066 void RenderViewHostImpl::OnDocumentAvailableInMainFrame(
1067 bool uses_temporary_zoom_level) {
1068 delegate_->DocumentAvailableInMainFrame(this);
1070 if (!uses_temporary_zoom_level)
1071 return;
1073 HostZoomMapImpl* host_zoom_map =
1074 static_cast<HostZoomMapImpl*>(HostZoomMap::Get(GetSiteInstance()));
1075 host_zoom_map->SetTemporaryZoomLevel(GetProcess()->GetID(),
1076 GetRoutingID(),
1077 host_zoom_map->GetDefaultZoomLevel());
1080 void RenderViewHostImpl::OnDidContentsPreferredSizeChange(
1081 const gfx::Size& new_size) {
1082 delegate_->UpdatePreferredSize(new_size);
1085 void RenderViewHostImpl::OnRenderAutoResized(const gfx::Size& new_size) {
1086 delegate_->ResizeDueToAutoResize(new_size);
1089 void RenderViewHostImpl::OnRouteCloseEvent() {
1090 // Have the delegate route this to the active RenderViewHost.
1091 delegate_->RouteCloseEvent(this);
1094 void RenderViewHostImpl::OnRouteMessageEvent(
1095 const ViewMsg_PostMessage_Params& params) {
1096 // Give to the delegate to route to the active RenderViewHost.
1097 delegate_->RouteMessageEvent(this, params);
1100 void RenderViewHostImpl::OnStartDragging(
1101 const DropData& drop_data,
1102 WebDragOperationsMask drag_operations_mask,
1103 const SkBitmap& bitmap,
1104 const gfx::Vector2d& bitmap_offset_in_dip,
1105 const DragEventSourceInfo& event_info) {
1106 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1107 if (!view)
1108 return;
1110 DropData filtered_data(drop_data);
1111 RenderProcessHost* process = GetProcess();
1112 ChildProcessSecurityPolicyImpl* policy =
1113 ChildProcessSecurityPolicyImpl::GetInstance();
1115 // Allow drag of Javascript URLs to enable bookmarklet drag to bookmark bar.
1116 if (!filtered_data.url.SchemeIs(url::kJavaScriptScheme))
1117 process->FilterURL(true, &filtered_data.url);
1118 process->FilterURL(false, &filtered_data.html_base_url);
1119 // Filter out any paths that the renderer didn't have access to. This prevents
1120 // the following attack on a malicious renderer:
1121 // 1. StartDragging IPC sent with renderer-specified filesystem paths that it
1122 // doesn't have read permissions for.
1123 // 2. We initiate a native DnD operation.
1124 // 3. DnD operation immediately ends since mouse is not held down. DnD events
1125 // still fire though, which causes read permissions to be granted to the
1126 // renderer for any file paths in the drop.
1127 filtered_data.filenames.clear();
1128 for (std::vector<ui::FileInfo>::const_iterator it =
1129 drop_data.filenames.begin();
1130 it != drop_data.filenames.end();
1131 ++it) {
1132 if (policy->CanReadFile(GetProcess()->GetID(), it->path))
1133 filtered_data.filenames.push_back(*it);
1136 storage::FileSystemContext* file_system_context =
1137 BrowserContext::GetStoragePartition(GetProcess()->GetBrowserContext(),
1138 GetSiteInstance())
1139 ->GetFileSystemContext();
1140 filtered_data.file_system_files.clear();
1141 for (size_t i = 0; i < drop_data.file_system_files.size(); ++i) {
1142 storage::FileSystemURL file_system_url =
1143 file_system_context->CrackURL(drop_data.file_system_files[i].url);
1144 if (policy->CanReadFileSystemFile(GetProcess()->GetID(), file_system_url))
1145 filtered_data.file_system_files.push_back(drop_data.file_system_files[i]);
1148 float scale = GetScaleFactorForView(GetView());
1149 gfx::ImageSkia image(gfx::ImageSkiaRep(bitmap, scale));
1150 view->StartDragging(filtered_data, drag_operations_mask, image,
1151 bitmap_offset_in_dip, event_info);
1154 void RenderViewHostImpl::OnUpdateDragCursor(WebDragOperation current_op) {
1155 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1156 if (view)
1157 view->UpdateDragCursor(current_op);
1160 void RenderViewHostImpl::OnTargetDropACK() {
1161 NotificationService::current()->Notify(
1162 NOTIFICATION_RENDER_VIEW_HOST_DID_RECEIVE_DRAG_TARGET_DROP_ACK,
1163 Source<RenderViewHost>(this),
1164 NotificationService::NoDetails());
1167 void RenderViewHostImpl::OnTakeFocus(bool reverse) {
1168 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1169 if (view)
1170 view->TakeFocus(reverse);
1173 void RenderViewHostImpl::OnFocusedNodeChanged(
1174 bool is_editable_node,
1175 const gfx::Rect& node_bounds_in_viewport) {
1176 is_focused_element_editable_ = is_editable_node;
1177 if (view_)
1178 view_->FocusedNodeChanged(is_editable_node);
1179 #if defined(OS_WIN)
1180 if (!is_editable_node && virtual_keyboard_requested_) {
1181 virtual_keyboard_requested_ = false;
1182 delegate_->SetIsVirtualKeyboardRequested(false);
1183 BrowserThread::PostDelayedTask(
1184 BrowserThread::UI, FROM_HERE,
1185 base::Bind(base::IgnoreResult(&DismissVirtualKeyboardTask)),
1186 TimeDelta::FromMilliseconds(kVirtualKeyboardDisplayWaitTimeoutMs));
1188 #endif
1190 // Convert node_bounds to screen coordinates.
1191 gfx::Rect view_bounds_in_screen = view_->GetViewBounds();
1192 gfx::Point origin = node_bounds_in_viewport.origin();
1193 origin.Offset(view_bounds_in_screen.x(), view_bounds_in_screen.y());
1194 gfx::Rect node_bounds_in_screen(origin.x(), origin.y(),
1195 node_bounds_in_viewport.width(),
1196 node_bounds_in_viewport.height());
1197 FocusedNodeDetails details = {is_editable_node, node_bounds_in_screen};
1198 NotificationService::current()->Notify(NOTIFICATION_FOCUS_CHANGED_IN_PAGE,
1199 Source<RenderViewHost>(this),
1200 Details<FocusedNodeDetails>(&details));
1203 void RenderViewHostImpl::OnUserGesture() {
1204 delegate_->OnUserGesture();
1207 void RenderViewHostImpl::OnClosePageACK() {
1208 decrement_in_flight_event_count();
1209 ClosePageIgnoringUnloadEvents();
1212 void RenderViewHostImpl::NotifyRendererUnresponsive() {
1213 delegate_->RendererUnresponsive(this);
1216 void RenderViewHostImpl::NotifyRendererResponsive() {
1217 delegate_->RendererResponsive(this);
1220 void RenderViewHostImpl::RequestToLockMouse(bool user_gesture,
1221 bool last_unlocked_by_target) {
1222 delegate_->RequestToLockMouse(user_gesture, last_unlocked_by_target);
1225 bool RenderViewHostImpl::IsFullscreen() const {
1226 return delegate_->IsFullscreenForCurrentTab();
1229 void RenderViewHostImpl::OnFocus() {
1230 // Note: We allow focus and blur from swapped out RenderViewHosts, even when
1231 // the active RenderViewHost is in a different BrowsingInstance (e.g., WebUI).
1232 delegate_->Activate();
1235 void RenderViewHostImpl::OnBlur() {
1236 delegate_->Deactivate();
1239 gfx::Rect RenderViewHostImpl::GetRootWindowResizerRect() const {
1240 return delegate_->GetRootWindowResizerRect();
1243 void RenderViewHostImpl::ForwardMouseEvent(
1244 const blink::WebMouseEvent& mouse_event) {
1245 RenderWidgetHostImpl::ForwardMouseEvent(mouse_event);
1246 if (mouse_event.type == WebInputEvent::MouseWheel && ignore_input_events())
1247 delegate_->OnIgnoredUIEvent();
1250 void RenderViewHostImpl::ForwardKeyboardEvent(
1251 const NativeWebKeyboardEvent& key_event) {
1252 if (ignore_input_events()) {
1253 if (key_event.type == WebInputEvent::RawKeyDown)
1254 delegate_->OnIgnoredUIEvent();
1255 return;
1257 RenderWidgetHostImpl::ForwardKeyboardEvent(key_event);
1260 void RenderViewHostImpl::OnTextSurroundingSelectionResponse(
1261 const base::string16& content,
1262 size_t start_offset,
1263 size_t end_offset) {
1264 if (!view_)
1265 return;
1266 view_->OnTextSurroundingSelectionResponse(content, start_offset, end_offset);
1269 WebPreferences RenderViewHostImpl::GetWebkitPreferences() {
1270 if (!web_preferences_.get()) {
1271 OnWebkitPreferencesChanged();
1273 return *web_preferences_;
1276 void RenderViewHostImpl::UpdateWebkitPreferences(const WebPreferences& prefs) {
1277 web_preferences_.reset(new WebPreferences(prefs));
1278 Send(new ViewMsg_UpdateWebPreferences(GetRoutingID(), prefs));
1281 void RenderViewHostImpl::OnWebkitPreferencesChanged() {
1282 // This is defensive code to avoid infinite loops due to code run inside
1283 // UpdateWebkitPreferences() accidentally updating more preferences and thus
1284 // calling back into this code. See crbug.com/398751 for one past example.
1285 if (updating_web_preferences_)
1286 return;
1287 updating_web_preferences_ = true;
1288 UpdateWebkitPreferences(ComputeWebkitPrefs());
1289 updating_web_preferences_ = false;
1292 void RenderViewHostImpl::ClearFocusedElement() {
1293 is_focused_element_editable_ = false;
1294 Send(new ViewMsg_ClearFocusedElement(GetRoutingID()));
1297 bool RenderViewHostImpl::IsFocusedElementEditable() {
1298 return is_focused_element_editable_;
1301 void RenderViewHostImpl::Zoom(PageZoom zoom) {
1302 Send(new ViewMsg_Zoom(GetRoutingID(), zoom));
1305 void RenderViewHostImpl::DisableScrollbarsForThreshold(const gfx::Size& size) {
1306 Send(new ViewMsg_DisableScrollbarsForSmallWindows(GetRoutingID(), size));
1309 void RenderViewHostImpl::EnablePreferredSizeMode() {
1310 Send(new ViewMsg_EnablePreferredSizeChangedMode(GetRoutingID()));
1313 void RenderViewHostImpl::EnableAutoResize(const gfx::Size& min_size,
1314 const gfx::Size& max_size) {
1315 SetAutoResize(true, min_size, max_size);
1316 Send(new ViewMsg_EnableAutoResize(GetRoutingID(), min_size, max_size));
1319 void RenderViewHostImpl::DisableAutoResize(const gfx::Size& new_size) {
1320 SetAutoResize(false, gfx::Size(), gfx::Size());
1321 Send(new ViewMsg_DisableAutoResize(GetRoutingID(), new_size));
1322 if (!new_size.IsEmpty())
1323 GetView()->SetSize(new_size);
1326 void RenderViewHostImpl::CopyImageAt(int x, int y) {
1327 Send(new ViewMsg_CopyImageAt(GetRoutingID(), x, y));
1330 void RenderViewHostImpl::SaveImageAt(int x, int y) {
1331 Send(new ViewMsg_SaveImageAt(GetRoutingID(), x, y));
1334 void RenderViewHostImpl::ExecuteMediaPlayerActionAtLocation(
1335 const gfx::Point& location, const blink::WebMediaPlayerAction& action) {
1336 Send(new ViewMsg_MediaPlayerActionAt(GetRoutingID(), location, action));
1339 void RenderViewHostImpl::ExecutePluginActionAtLocation(
1340 const gfx::Point& location, const blink::WebPluginAction& action) {
1341 Send(new ViewMsg_PluginActionAt(GetRoutingID(), location, action));
1344 void RenderViewHostImpl::NotifyMoveOrResizeStarted() {
1345 Send(new ViewMsg_MoveOrResizeStarted(GetRoutingID()));
1348 void RenderViewHostImpl::OnDidZoomURL(double zoom_level,
1349 const GURL& url) {
1350 HostZoomMapImpl* host_zoom_map =
1351 static_cast<HostZoomMapImpl*>(HostZoomMap::Get(GetSiteInstance()));
1353 host_zoom_map->SetZoomLevelForView(GetProcess()->GetID(),
1354 GetRoutingID(),
1355 zoom_level,
1356 net::GetHostOrSpecFromURL(url));
1359 void RenderViewHostImpl::OnPageScaleFactorIsOneChanged(bool is_one) {
1360 if (!GetSiteInstance())
1361 return;
1362 HostZoomMapImpl* host_zoom_map =
1363 static_cast<HostZoomMapImpl*>(HostZoomMap::Get(GetSiteInstance()));
1364 if (!host_zoom_map)
1365 return;
1366 if (!GetProcess())
1367 return;
1368 host_zoom_map->SetPageScaleFactorIsOneForView(GetProcess()->GetID(),
1369 GetRoutingID(), is_one);
1372 void RenderViewHostImpl::OnRunFileChooser(const FileChooserParams& params) {
1373 // Do not allow messages with absolute paths in them as this can permit a
1374 // renderer to coerce the browser to perform I/O on a renderer controlled
1375 // path.
1376 if (params.default_file_name != params.default_file_name.BaseName()) {
1377 bad_message::ReceivedBadMessage(GetProcess(),
1378 bad_message::RVH_FILE_CHOOSER_PATH);
1379 return;
1382 delegate_->RunFileChooser(this, params);
1385 void RenderViewHostImpl::OnFocusedNodeTouched(bool editable) {
1386 #if defined(OS_WIN)
1387 if (editable) {
1388 virtual_keyboard_requested_ = base::win::DisplayVirtualKeyboard();
1389 delegate_->SetIsVirtualKeyboardRequested(true);
1390 } else {
1391 virtual_keyboard_requested_ = false;
1392 delegate_->SetIsVirtualKeyboardRequested(false);
1393 base::win::DismissVirtualKeyboard();
1395 #endif
1398 bool RenderViewHostImpl::CanAccessFilesOfPageState(
1399 const PageState& state) const {
1400 ChildProcessSecurityPolicyImpl* policy =
1401 ChildProcessSecurityPolicyImpl::GetInstance();
1403 const std::vector<base::FilePath>& file_paths = state.GetReferencedFiles();
1404 for (const auto& file : file_paths) {
1405 if (!policy->CanReadFile(GetProcess()->GetID(), file))
1406 return false;
1408 return true;
1411 void RenderViewHostImpl::GrantFileAccessFromPageState(const PageState& state) {
1412 ChildProcessSecurityPolicyImpl* policy =
1413 ChildProcessSecurityPolicyImpl::GetInstance();
1415 const std::vector<base::FilePath>& file_paths = state.GetReferencedFiles();
1416 for (const auto& file : file_paths) {
1417 if (!policy->CanReadFile(GetProcess()->GetID(), file))
1418 policy->GrantReadFile(GetProcess()->GetID(), file);
1422 void RenderViewHostImpl::AttachToFrameTree() {
1423 FrameTree* frame_tree = delegate_->GetFrameTree();
1425 frame_tree->ResetForMainFrameSwap();
1428 void RenderViewHostImpl::SelectWordAroundCaret() {
1429 Send(new ViewMsg_SelectWordAroundCaret(GetRoutingID()));
1432 } // namespace content