Add ICU message format support
[chromium-blink-merge.git] / content / browser / renderer_host / render_view_host_impl.cc
blob3363c5145d5073b0496c15a23a5933a3ec549962
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 nav_entry_id_(0),
218 is_active_(!swapped_out),
219 is_swapped_out_(swapped_out),
220 main_frame_routing_id_(main_frame_routing_id),
221 is_waiting_for_close_ack_(false),
222 sudden_termination_allowed_(false),
223 render_view_termination_status_(base::TERMINATION_STATUS_STILL_RUNNING),
224 virtual_keyboard_requested_(false),
225 is_focused_element_editable_(false),
226 updating_web_preferences_(false),
227 weak_factory_(this) {
228 DCHECK(instance_.get());
229 CHECK(delegate_); // http://crbug.com/82827
231 GetProcess()->AddObserver(this);
232 GetProcess()->EnableSendQueue();
234 if (ResourceDispatcherHostImpl::Get()) {
235 bool has_active_audio = false;
236 if (has_initialized_audio_host) {
237 scoped_refptr<AudioRendererHost> arh =
238 static_cast<RenderProcessHostImpl*>(GetProcess())
239 ->audio_renderer_host();
240 if (arh.get())
241 has_active_audio =
242 arh->RenderFrameHasActiveAudio(main_frame_routing_id_);
244 BrowserThread::PostTask(
245 BrowserThread::IO,
246 FROM_HERE,
247 base::Bind(&ResourceDispatcherHostImpl::OnRenderViewHostCreated,
248 base::Unretained(ResourceDispatcherHostImpl::Get()),
249 GetProcess()->GetID(),
250 GetRoutingID(),
251 !is_hidden(),
252 has_active_audio));
256 RenderViewHostImpl::~RenderViewHostImpl() {
257 if (ResourceDispatcherHostImpl::Get()) {
258 BrowserThread::PostTask(
259 BrowserThread::IO, FROM_HERE,
260 base::Bind(&ResourceDispatcherHostImpl::OnRenderViewHostDeleted,
261 base::Unretained(ResourceDispatcherHostImpl::Get()),
262 GetProcess()->GetID(), GetRoutingID()));
265 delegate_->RenderViewDeleted(this);
266 GetProcess()->RemoveObserver(this);
269 RenderViewHostDelegate* RenderViewHostImpl::GetDelegate() const {
270 return delegate_;
273 SiteInstanceImpl* RenderViewHostImpl::GetSiteInstance() const {
274 return instance_.get();
277 bool RenderViewHostImpl::CreateRenderView(
278 int opener_frame_route_id,
279 int proxy_route_id,
280 int32 max_page_id,
281 const FrameReplicationState& replicated_frame_state,
282 bool window_was_created_with_opener) {
283 TRACE_EVENT0("renderer_host,navigation",
284 "RenderViewHostImpl::CreateRenderView");
285 DCHECK(!IsRenderViewLive()) << "Creating view twice";
287 // The process may (if we're sharing a process with another host that already
288 // initialized it) or may not (we have our own process or the old process
289 // crashed) have been initialized. Calling Init multiple times will be
290 // ignored, so this is safe.
291 if (!GetProcess()->Init())
292 return false;
293 DCHECK(GetProcess()->HasConnection());
294 DCHECK(GetProcess()->GetBrowserContext());
296 set_renderer_initialized(true);
298 GpuSurfaceTracker::Get()->SetSurfaceHandle(
299 surface_id(), GetCompositingSurface());
301 // Ensure the RenderView starts with a next_page_id larger than any existing
302 // page ID it might be asked to render.
303 int32 next_page_id = 1;
304 if (max_page_id > -1)
305 next_page_id = max_page_id + 1;
307 ViewMsg_New_Params params;
308 params.renderer_preferences =
309 delegate_->GetRendererPrefs(GetProcess()->GetBrowserContext());
310 #if defined(OS_WIN)
311 GetWindowsSpecificPrefs(&params.renderer_preferences);
312 #endif
313 params.web_preferences = GetWebkitPreferences();
314 params.view_id = GetRoutingID();
315 params.main_frame_routing_id = main_frame_routing_id_;
316 params.surface_id = surface_id();
317 params.session_storage_namespace_id =
318 delegate_->GetSessionStorageNamespace(instance_.get())->id();
319 // Ensure the RenderView sets its opener correctly.
320 params.opener_frame_route_id = opener_frame_route_id;
321 params.swapped_out = !is_active_;
322 params.replicated_frame_state = replicated_frame_state;
323 params.proxy_routing_id = proxy_route_id;
324 params.hidden = is_hidden();
325 params.never_visible = delegate_->IsNeverVisible();
326 params.window_was_created_with_opener = window_was_created_with_opener;
327 params.next_page_id = next_page_id;
328 params.enable_auto_resize = auto_resize_enabled();
329 params.min_size = min_size_for_auto_resize();
330 params.max_size = max_size_for_auto_resize();
331 GetResizeParams(&params.initial_size);
333 if (!Send(new ViewMsg_New(params)))
334 return false;
335 SetInitialRenderSizeParams(params.initial_size);
337 // If the RWHV has not yet been set, the surface ID namespace will get
338 // passed down by the call to SetView().
339 if (view_) {
340 Send(new ViewMsg_SetSurfaceIdNamespace(GetRoutingID(),
341 view_->GetSurfaceIdNamespace()));
344 // If it's enabled, tell the renderer to set up the Javascript bindings for
345 // sending messages back to the browser.
346 if (GetProcess()->IsForGuestsOnly())
347 DCHECK_EQ(0, enabled_bindings_);
348 Send(new ViewMsg_AllowBindings(GetRoutingID(), enabled_bindings_));
349 // Let our delegate know that we created a RenderView.
350 delegate_->RenderViewCreated(this);
352 // Since this method can create the main RenderFrame in the renderer process,
353 // set the proper state on its corresponding RenderFrameHost.
354 if (main_frame_routing_id_ != MSG_ROUTING_NONE) {
355 RenderFrameHostImpl::FromID(GetProcess()->GetID(), main_frame_routing_id_)
356 ->SetRenderFrameCreated(true);
359 return true;
362 bool RenderViewHostImpl::IsRenderViewLive() const {
363 return GetProcess()->HasConnection() && renderer_initialized();
366 void RenderViewHostImpl::SyncRendererPrefs() {
367 RendererPreferences renderer_preferences =
368 delegate_->GetRendererPrefs(GetProcess()->GetBrowserContext());
369 #if defined(OS_WIN)
370 GetWindowsSpecificPrefs(&renderer_preferences);
371 #endif
372 Send(new ViewMsg_SetRendererPrefs(GetRoutingID(), renderer_preferences));
375 WebPreferences RenderViewHostImpl::ComputeWebkitPrefs() {
376 TRACE_EVENT0("browser", "RenderViewHostImpl::GetWebkitPrefs");
377 WebPreferences prefs;
379 const base::CommandLine& command_line =
380 *base::CommandLine::ForCurrentProcess();
382 prefs.web_security_enabled =
383 !command_line.HasSwitch(switches::kDisableWebSecurity);
384 prefs.java_enabled =
385 !command_line.HasSwitch(switches::kDisableJava);
387 prefs.remote_fonts_enabled =
388 !command_line.HasSwitch(switches::kDisableRemoteFonts);
389 prefs.application_cache_enabled = true;
390 prefs.xss_auditor_enabled =
391 !command_line.HasSwitch(switches::kDisableXSSAuditor);
392 prefs.local_storage_enabled =
393 !command_line.HasSwitch(switches::kDisableLocalStorage);
394 prefs.databases_enabled =
395 !command_line.HasSwitch(switches::kDisableDatabases);
396 #if defined(OS_ANDROID)
397 // WebAudio is enabled by default on x86 and ARM.
398 prefs.webaudio_enabled =
399 !command_line.HasSwitch(switches::kDisableWebAudio);
400 #endif
402 prefs.experimental_webgl_enabled =
403 GpuProcessHost::gpu_enabled() &&
404 !command_line.HasSwitch(switches::kDisable3DAPIs) &&
405 !command_line.HasSwitch(switches::kDisableExperimentalWebGL);
407 prefs.pepper_3d_enabled =
408 !command_line.HasSwitch(switches::kDisablePepper3d);
410 prefs.flash_3d_enabled =
411 GpuProcessHost::gpu_enabled() &&
412 !command_line.HasSwitch(switches::kDisableFlash3d);
413 prefs.flash_stage3d_enabled =
414 GpuProcessHost::gpu_enabled() &&
415 !command_line.HasSwitch(switches::kDisableFlashStage3d);
416 prefs.flash_stage3d_baseline_enabled =
417 GpuProcessHost::gpu_enabled() &&
418 !command_line.HasSwitch(switches::kDisableFlashStage3d);
420 prefs.allow_file_access_from_file_urls =
421 command_line.HasSwitch(switches::kAllowFileAccessFromFiles);
423 prefs.accelerated_2d_canvas_enabled =
424 GpuProcessHost::gpu_enabled() &&
425 !command_line.HasSwitch(switches::kDisableAccelerated2dCanvas);
426 prefs.antialiased_2d_canvas_disabled =
427 command_line.HasSwitch(switches::kDisable2dCanvasAntialiasing);
428 prefs.antialiased_clips_2d_canvas_enabled =
429 command_line.HasSwitch(switches::kEnable2dCanvasClipAntialiasing);
430 prefs.accelerated_2d_canvas_msaa_sample_count =
431 atoi(command_line.GetSwitchValueASCII(
432 switches::kAcceleratedCanvas2dMSAASampleCount).c_str());
433 prefs.text_blobs_enabled =
434 !command_line.HasSwitch(switches::kDisableTextBlobs);
436 prefs.pinch_overlay_scrollbar_thickness = 10;
437 prefs.use_solid_color_scrollbars = ui::IsOverlayScrollbarEnabled();
438 prefs.invert_viewport_scroll_order =
439 command_line.HasSwitch(switches::kInvertViewportScrollOrder);
441 #if defined(OS_ANDROID)
442 // On Android, user gestures are normally required, unless that requirement
443 // is disabled with a command-line switch or the equivalent field trial is
444 // is set to "Enabled".
445 const std::string autoplay_group_name = base::FieldTrialList::FindFullName(
446 "MediaElementAutoplay");
447 prefs.user_gesture_required_for_media_playback = !command_line.HasSwitch(
448 switches::kDisableGestureRequirementForMediaPlayback) &&
449 (autoplay_group_name.empty() || autoplay_group_name != "Enabled");
450 #endif
452 prefs.touch_enabled = ui::AreTouchEventsEnabled();
453 prefs.device_supports_touch = prefs.touch_enabled &&
454 ui::IsTouchDevicePresent();
455 prefs.available_pointer_types = ui::GetAvailablePointerTypes();
456 prefs.primary_pointer_type = ui::GetPrimaryPointerType();
457 prefs.available_hover_types = ui::GetAvailableHoverTypes();
458 prefs.primary_hover_type = ui::GetPrimaryHoverType();
460 #if defined(OS_ANDROID)
461 prefs.device_supports_mouse = false;
462 #endif
464 prefs.pointer_events_max_touch_points = ui::MaxTouchPoints();
466 prefs.touch_adjustment_enabled =
467 !command_line.HasSwitch(switches::kDisableTouchAdjustment);
469 const std::string slimming_group =
470 base::FieldTrialList::FindFullName("SlimmingPaint");
471 prefs.slimming_paint_enabled =
472 (command_line.HasSwitch(switches::kEnableSlimmingPaint) ||
473 !command_line.HasSwitch(switches::kDisableSlimmingPaint)) &&
474 (slimming_group != "DisableSlimmingPaint");
475 #if defined(OS_MACOSX) || defined(OS_CHROMEOS)
476 bool default_enable_scroll_animator = true;
477 #else
478 bool default_enable_scroll_animator = false;
479 #endif
480 prefs.enable_scroll_animator = default_enable_scroll_animator;
481 if (command_line.HasSwitch(switches::kEnableSmoothScrolling))
482 prefs.enable_scroll_animator = true;
483 if (command_line.HasSwitch(switches::kDisableSmoothScrolling))
484 prefs.enable_scroll_animator = false;
486 // Certain GPU features might have been blacklisted.
487 GpuDataManagerImpl::GetInstance()->UpdateRendererWebPrefs(&prefs);
489 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
490 GetProcess()->GetID())) {
491 prefs.loads_images_automatically = true;
492 prefs.javascript_enabled = true;
495 prefs.connection_type = net::NetworkChangeNotifier::GetConnectionType();
496 prefs.is_online =
497 prefs.connection_type != net::NetworkChangeNotifier::CONNECTION_NONE;
499 prefs.number_of_cpu_cores = base::SysInfo::NumberOfProcessors();
501 prefs.viewport_meta_enabled =
502 command_line.HasSwitch(switches::kEnableViewportMeta);
504 prefs.viewport_enabled =
505 command_line.HasSwitch(switches::kEnableViewport) ||
506 prefs.viewport_meta_enabled;
508 prefs.main_frame_resizes_are_orientation_changes =
509 command_line.HasSwitch(switches::kMainFrameResizesAreOrientationChanges);
511 prefs.image_color_profiles_enabled =
512 command_line.HasSwitch(switches::kEnableImageColorProfiles);
514 prefs.spatial_navigation_enabled = command_line.HasSwitch(
515 switches::kEnableSpatialNavigation);
517 prefs.disable_reading_from_canvas = command_line.HasSwitch(
518 switches::kDisableReadingFromCanvas);
520 prefs.strict_mixed_content_checking = command_line.HasSwitch(
521 switches::kEnableStrictMixedContentChecking);
523 prefs.strict_powerful_feature_restrictions = command_line.HasSwitch(
524 switches::kEnableStrictPowerfulFeatureRestrictions);
526 const std::string blockable_mixed_content_group =
527 base::FieldTrialList::FindFullName("BlockableMixedContent");
528 prefs.strictly_block_blockable_mixed_content =
529 blockable_mixed_content_group == "StrictlyBlockBlockableMixedContent";
531 prefs.v8_cache_options = GetV8CacheOptions();
533 GetContentClient()->browser()->OverrideWebkitPrefs(this, &prefs);
534 return prefs;
537 void RenderViewHostImpl::SuppressDialogsUntilSwapOut() {
538 Send(new ViewMsg_SuppressDialogsUntilSwapOut(GetRoutingID()));
541 void RenderViewHostImpl::ClosePage() {
542 is_waiting_for_close_ack_ = true;
543 StartHangMonitorTimeout(TimeDelta::FromMilliseconds(kUnloadTimeoutMS));
545 if (IsRenderViewLive()) {
546 // Since we are sending an IPC message to the renderer, increase the event
547 // count to prevent the hang monitor timeout from being stopped by input
548 // event acknowledgements.
549 increment_in_flight_event_count();
551 // TODO(creis): Should this be moved to Shutdown? It may not be called for
552 // RenderViewHosts that have been swapped out.
553 NotificationService::current()->Notify(
554 NOTIFICATION_RENDER_VIEW_HOST_WILL_CLOSE_RENDER_VIEW,
555 Source<RenderViewHost>(this),
556 NotificationService::NoDetails());
558 Send(new ViewMsg_ClosePage(GetRoutingID()));
559 } else {
560 // This RenderViewHost doesn't have a live renderer, so just skip the unload
561 // event and close the page.
562 ClosePageIgnoringUnloadEvents();
566 void RenderViewHostImpl::ClosePageIgnoringUnloadEvents() {
567 StopHangMonitorTimeout();
568 is_waiting_for_close_ack_ = false;
570 sudden_termination_allowed_ = true;
571 delegate_->Close(this);
574 #if defined(OS_ANDROID)
575 void RenderViewHostImpl::ActivateNearestFindResult(int request_id,
576 float x,
577 float y) {
578 Send(new InputMsg_ActivateNearestFindResult(GetRoutingID(),
579 request_id, x, y));
582 void RenderViewHostImpl::RequestFindMatchRects(int current_version) {
583 Send(new ViewMsg_FindMatchRects(GetRoutingID(), current_version));
585 #endif
587 void RenderViewHostImpl::RenderProcessExited(RenderProcessHost* host,
588 base::TerminationStatus status,
589 int exit_code) {
590 if (!renderer_initialized())
591 return;
593 RenderWidgetHostImpl::RendererExited(status, exit_code);
594 delegate_->RenderViewTerminated(this, status, exit_code);
597 void RenderViewHostImpl::DragTargetDragEnter(
598 const DropData& drop_data,
599 const gfx::Point& client_pt,
600 const gfx::Point& screen_pt,
601 WebDragOperationsMask operations_allowed,
602 int key_modifiers) {
603 const int renderer_id = GetProcess()->GetID();
604 ChildProcessSecurityPolicyImpl* policy =
605 ChildProcessSecurityPolicyImpl::GetInstance();
607 #if defined(OS_CHROMEOS)
608 // The externalfile:// scheme is used in Chrome OS to open external files in a
609 // browser tab.
610 if (drop_data.url.SchemeIs(content::kExternalFileScheme))
611 policy->GrantRequestURL(renderer_id, drop_data.url);
612 #endif
614 // The URL could have been cobbled together from any highlighted text string,
615 // and can't be interpreted as a capability.
616 DropData filtered_data(drop_data);
617 GetProcess()->FilterURL(true, &filtered_data.url);
618 if (drop_data.did_originate_from_renderer) {
619 filtered_data.filenames.clear();
622 // The filenames vector, on the other hand, does represent a capability to
623 // access the given files.
624 storage::IsolatedContext::FileInfoSet files;
625 for (std::vector<ui::FileInfo>::iterator iter(
626 filtered_data.filenames.begin());
627 iter != filtered_data.filenames.end();
628 ++iter) {
629 // A dragged file may wind up as the value of an input element, or it
630 // may be used as the target of a navigation instead. We don't know
631 // which will happen at this point, so generously grant both access
632 // and request permissions to the specific file to cover both cases.
633 // We do not give it the permission to request all file:// URLs.
635 // Make sure we have the same display_name as the one we register.
636 if (iter->display_name.empty()) {
637 std::string name;
638 files.AddPath(iter->path, &name);
639 iter->display_name = base::FilePath::FromUTF8Unsafe(name);
640 } else {
641 files.AddPathWithName(iter->path, iter->display_name.AsUTF8Unsafe());
644 policy->GrantRequestSpecificFileURL(renderer_id,
645 net::FilePathToFileURL(iter->path));
647 // If the renderer already has permission to read these paths, we don't need
648 // to re-grant them. This prevents problems with DnD for files in the CrOS
649 // file manager--the file manager already had read/write access to those
650 // directories, but dragging a file would cause the read/write access to be
651 // overwritten with read-only access, making them impossible to delete or
652 // rename until the renderer was killed.
653 if (!policy->CanReadFile(renderer_id, iter->path))
654 policy->GrantReadFile(renderer_id, iter->path);
657 storage::IsolatedContext* isolated_context =
658 storage::IsolatedContext::GetInstance();
659 DCHECK(isolated_context);
660 std::string filesystem_id = isolated_context->RegisterDraggedFileSystem(
661 files);
662 if (!filesystem_id.empty()) {
663 // Grant the permission iff the ID is valid.
664 policy->GrantReadFileSystem(renderer_id, filesystem_id);
666 filtered_data.filesystem_id = base::UTF8ToUTF16(filesystem_id);
668 storage::FileSystemContext* file_system_context =
669 BrowserContext::GetStoragePartition(GetProcess()->GetBrowserContext(),
670 GetSiteInstance())
671 ->GetFileSystemContext();
672 for (size_t i = 0; i < filtered_data.file_system_files.size(); ++i) {
673 storage::FileSystemURL file_system_url =
674 file_system_context->CrackURL(filtered_data.file_system_files[i].url);
676 std::string register_name;
677 std::string filesystem_id = isolated_context->RegisterFileSystemForPath(
678 file_system_url.type(), file_system_url.filesystem_id(),
679 file_system_url.path(), &register_name);
680 policy->GrantReadFileSystem(renderer_id, filesystem_id);
682 // Note: We are using the origin URL provided by the sender here. It may be
683 // different from the receiver's.
684 filtered_data.file_system_files[i].url =
685 GURL(storage::GetIsolatedFileSystemRootURIString(
686 file_system_url.origin(), filesystem_id, std::string())
687 .append(register_name));
690 Send(new DragMsg_TargetDragEnter(GetRoutingID(), filtered_data, client_pt,
691 screen_pt, operations_allowed,
692 key_modifiers));
695 void RenderViewHostImpl::DragTargetDragOver(
696 const gfx::Point& client_pt,
697 const gfx::Point& screen_pt,
698 WebDragOperationsMask operations_allowed,
699 int key_modifiers) {
700 Send(new DragMsg_TargetDragOver(GetRoutingID(), client_pt, screen_pt,
701 operations_allowed, key_modifiers));
704 void RenderViewHostImpl::DragTargetDragLeave() {
705 Send(new DragMsg_TargetDragLeave(GetRoutingID()));
708 void RenderViewHostImpl::DragTargetDrop(
709 const gfx::Point& client_pt,
710 const gfx::Point& screen_pt,
711 int key_modifiers) {
712 Send(new DragMsg_TargetDrop(GetRoutingID(), client_pt, screen_pt,
713 key_modifiers));
716 void RenderViewHostImpl::DragSourceEndedAt(
717 int client_x, int client_y, int screen_x, int screen_y,
718 WebDragOperation operation) {
719 Send(new DragMsg_SourceEnded(GetRoutingID(),
720 gfx::Point(client_x, client_y),
721 gfx::Point(screen_x, screen_y),
722 operation));
725 void RenderViewHostImpl::DragSourceSystemDragEnded() {
726 Send(new DragMsg_SourceSystemDragEnded(GetRoutingID()));
729 RenderFrameHost* RenderViewHostImpl::GetMainFrame() {
730 return RenderFrameHost::FromID(GetProcess()->GetID(), main_frame_routing_id_);
733 void RenderViewHostImpl::AllowBindings(int bindings_flags) {
734 // Never grant any bindings to browser plugin guests.
735 if (GetProcess()->IsForGuestsOnly()) {
736 NOTREACHED() << "Never grant bindings to a guest process.";
737 return;
740 // Ensure we aren't granting WebUI bindings to a process that has already
741 // been used for non-privileged views.
742 if (bindings_flags & BINDINGS_POLICY_WEB_UI &&
743 GetProcess()->HasConnection() &&
744 !ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
745 GetProcess()->GetID())) {
746 // This process has no bindings yet. Make sure it does not have more
747 // than this single active view.
748 // --single-process only has one renderer.
749 if (GetProcess()->GetActiveViewCount() > 1 &&
750 !base::CommandLine::ForCurrentProcess()->HasSwitch(
751 switches::kSingleProcess))
752 return;
755 if (bindings_flags & BINDINGS_POLICY_WEB_UI) {
756 ChildProcessSecurityPolicyImpl::GetInstance()->GrantWebUIBindings(
757 GetProcess()->GetID());
760 enabled_bindings_ |= bindings_flags;
761 if (renderer_initialized())
762 Send(new ViewMsg_AllowBindings(GetRoutingID(), enabled_bindings_));
765 int RenderViewHostImpl::GetEnabledBindings() const {
766 return enabled_bindings_;
769 void RenderViewHostImpl::SetWebUIProperty(const std::string& name,
770 const std::string& value) {
771 // This is a sanity check before telling the renderer to enable the property.
772 // It could lie and send the corresponding IPC messages anyway, but we will
773 // not act on them if enabled_bindings_ doesn't agree. If we get here without
774 // WebUI bindings, kill the renderer process.
775 if (enabled_bindings_ & BINDINGS_POLICY_WEB_UI) {
776 Send(new ViewMsg_SetWebUIProperty(GetRoutingID(), name, value));
777 } else {
778 RecordAction(
779 base::UserMetricsAction("BindingsMismatchTerminate_RVH_WebUI"));
780 GetProcess()->Shutdown(content::RESULT_CODE_KILLED, false);
784 void RenderViewHostImpl::GotFocus() {
785 RenderWidgetHostImpl::GotFocus(); // Notifies the renderer it got focus.
787 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
788 if (view)
789 view->GotFocus();
792 void RenderViewHostImpl::LostCapture() {
793 RenderWidgetHostImpl::LostCapture();
794 delegate_->LostCapture();
797 void RenderViewHostImpl::LostMouseLock() {
798 RenderWidgetHostImpl::LostMouseLock();
799 delegate_->LostMouseLock();
802 void RenderViewHostImpl::SetInitialFocus(bool reverse) {
803 Send(new ViewMsg_SetInitialFocus(GetRoutingID(), reverse));
806 void RenderViewHostImpl::FilesSelectedInChooser(
807 const std::vector<content::FileChooserFileInfo>& files,
808 FileChooserParams::Mode permissions) {
809 storage::FileSystemContext* const file_system_context =
810 BrowserContext::GetStoragePartition(GetProcess()->GetBrowserContext(),
811 GetSiteInstance())
812 ->GetFileSystemContext();
813 // Grant the security access requested to the given files.
814 for (size_t i = 0; i < files.size(); ++i) {
815 const content::FileChooserFileInfo& file = files[i];
816 if (permissions == FileChooserParams::Save) {
817 ChildProcessSecurityPolicyImpl::GetInstance()->GrantCreateReadWriteFile(
818 GetProcess()->GetID(), file.file_path);
819 } else {
820 ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
821 GetProcess()->GetID(), file.file_path);
823 if (file.file_system_url.is_valid()) {
824 ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFileSystem(
825 GetProcess()->GetID(),
826 file_system_context->CrackURL(file.file_system_url)
827 .mount_filesystem_id());
830 Send(new ViewMsg_RunFileChooserResponse(GetRoutingID(), files));
833 void RenderViewHostImpl::DirectoryEnumerationFinished(
834 int request_id,
835 const std::vector<base::FilePath>& files) {
836 // Grant the security access requested to the given files.
837 for (std::vector<base::FilePath>::const_iterator file = files.begin();
838 file != files.end(); ++file) {
839 ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
840 GetProcess()->GetID(), *file);
842 Send(new ViewMsg_EnumerateDirectoryResponse(GetRoutingID(),
843 request_id,
844 files));
847 void RenderViewHostImpl::SetIsLoading(bool is_loading) {
848 if (ResourceDispatcherHostImpl::Get()) {
849 BrowserThread::PostTask(
850 BrowserThread::IO,
851 FROM_HERE,
852 base::Bind(&ResourceDispatcherHostImpl::OnRenderViewHostSetIsLoading,
853 base::Unretained(ResourceDispatcherHostImpl::Get()),
854 GetProcess()->GetID(),
855 GetRoutingID(),
856 is_loading));
858 RenderWidgetHostImpl::SetIsLoading(is_loading);
861 void RenderViewHostImpl::LoadStateChanged(
862 const GURL& url,
863 const net::LoadStateWithParam& load_state,
864 uint64 upload_position,
865 uint64 upload_size) {
866 delegate_->LoadStateChanged(url, load_state, upload_position, upload_size);
869 bool RenderViewHostImpl::SuddenTerminationAllowed() const {
870 return sudden_termination_allowed_ ||
871 GetProcess()->SuddenTerminationAllowed();
874 ///////////////////////////////////////////////////////////////////////////////
875 // RenderViewHostImpl, IPC message handlers:
877 bool RenderViewHostImpl::OnMessageReceived(const IPC::Message& msg) {
878 if (!BrowserMessageFilter::CheckCanDispatchOnUI(msg, this))
879 return true;
881 // Filter out most IPC messages if this renderer is swapped out.
882 // We still want to handle certain ACKs to keep our state consistent.
883 if (is_swapped_out_) {
884 if (!SwappedOutMessages::CanHandleWhileSwappedOut(msg)) {
885 // If this is a synchronous message and we decided not to handle it,
886 // we must send an error reply, or else the renderer will be stuck
887 // and won't respond to future requests.
888 if (msg.is_sync()) {
889 IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
890 reply->set_reply_error();
891 Send(reply);
893 // Don't continue looking for someone to handle it.
894 return true;
898 if (delegate_->OnMessageReceived(this, msg))
899 return true;
901 bool handled = true;
902 IPC_BEGIN_MESSAGE_MAP(RenderViewHostImpl, msg)
903 IPC_MESSAGE_HANDLER(FrameHostMsg_RenderProcessGone, OnRenderProcessGone)
904 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowView, OnShowView)
905 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowWidget, OnShowWidget)
906 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowFullscreenWidget,
907 OnShowFullscreenWidget)
908 IPC_MESSAGE_HANDLER(ViewHostMsg_RenderViewReady, OnRenderViewReady)
909 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateState, OnUpdateState)
910 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateTargetURL, OnUpdateTargetURL)
911 IPC_MESSAGE_HANDLER(ViewHostMsg_Close, OnClose)
912 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestMove, OnRequestMove)
913 IPC_MESSAGE_HANDLER(ViewHostMsg_DocumentAvailableInMainFrame,
914 OnDocumentAvailableInMainFrame)
915 IPC_MESSAGE_HANDLER(ViewHostMsg_DidContentsPreferredSizeChange,
916 OnDidContentsPreferredSizeChange)
917 IPC_MESSAGE_HANDLER(ViewHostMsg_RouteCloseEvent,
918 OnRouteCloseEvent)
919 IPC_MESSAGE_HANDLER(DragHostMsg_StartDragging, OnStartDragging)
920 IPC_MESSAGE_HANDLER(DragHostMsg_UpdateDragCursor, OnUpdateDragCursor)
921 IPC_MESSAGE_HANDLER(ViewHostMsg_TakeFocus, OnTakeFocus)
922 IPC_MESSAGE_HANDLER(ViewHostMsg_FocusedNodeChanged, OnFocusedNodeChanged)
923 IPC_MESSAGE_HANDLER(ViewHostMsg_ClosePage_ACK, OnClosePageACK)
924 IPC_MESSAGE_HANDLER(ViewHostMsg_DidZoomURL, OnDidZoomURL)
925 IPC_MESSAGE_HANDLER(ViewHostMsg_PageScaleFactorIsOneChanged,
926 OnPageScaleFactorIsOneChanged)
927 IPC_MESSAGE_HANDLER(ViewHostMsg_RunFileChooser, OnRunFileChooser)
928 IPC_MESSAGE_HANDLER(ViewHostMsg_FocusedNodeTouched, OnFocusedNodeTouched)
929 // Have the super handle all other messages.
930 IPC_MESSAGE_UNHANDLED(
931 handled = RenderWidgetHostImpl::OnMessageReceived(msg))
932 IPC_END_MESSAGE_MAP()
934 return handled;
937 void RenderViewHostImpl::Init() {
938 RenderWidgetHostImpl::Init();
941 void RenderViewHostImpl::Shutdown() {
942 // We can't release the SessionStorageNamespace until our peer
943 // in the renderer has wound down.
944 if (GetProcess()->HasConnection()) {
945 RenderProcessHostImpl::ReleaseOnCloseACK(
946 GetProcess(),
947 delegate_->GetSessionStorageNamespaceMap(),
948 GetRoutingID());
951 RenderWidgetHostImpl::Shutdown();
954 void RenderViewHostImpl::WasHidden() {
955 if (ResourceDispatcherHostImpl::Get()) {
956 BrowserThread::PostTask(
957 BrowserThread::IO, FROM_HERE,
958 base::Bind(&ResourceDispatcherHostImpl::OnRenderViewHostWasHidden,
959 base::Unretained(ResourceDispatcherHostImpl::Get()),
960 GetProcess()->GetID(), GetRoutingID()));
963 RenderWidgetHostImpl::WasHidden();
966 void RenderViewHostImpl::WasShown(const ui::LatencyInfo& latency_info) {
967 if (ResourceDispatcherHostImpl::Get()) {
968 BrowserThread::PostTask(
969 BrowserThread::IO, FROM_HERE,
970 base::Bind(&ResourceDispatcherHostImpl::OnRenderViewHostWasShown,
971 base::Unretained(ResourceDispatcherHostImpl::Get()),
972 GetProcess()->GetID(), GetRoutingID()));
975 RenderWidgetHostImpl::WasShown(latency_info);
978 bool RenderViewHostImpl::IsRenderView() const {
979 return true;
982 void RenderViewHostImpl::CreateNewWindow(
983 int route_id,
984 int main_frame_route_id,
985 const ViewHostMsg_CreateWindow_Params& params,
986 SessionStorageNamespace* session_storage_namespace) {
987 ViewHostMsg_CreateWindow_Params validated_params(params);
988 GetProcess()->FilterURL(false, &validated_params.target_url);
989 GetProcess()->FilterURL(false, &validated_params.opener_url);
990 GetProcess()->FilterURL(true, &validated_params.opener_security_origin);
992 delegate_->CreateNewWindow(GetSiteInstance(), route_id, main_frame_route_id,
993 validated_params, session_storage_namespace);
996 void RenderViewHostImpl::CreateNewWidget(int route_id,
997 blink::WebPopupType popup_type) {
998 delegate_->CreateNewWidget(GetProcess()->GetID(), route_id, popup_type);
1001 void RenderViewHostImpl::CreateNewFullscreenWidget(int route_id) {
1002 delegate_->CreateNewFullscreenWidget(GetProcess()->GetID(), route_id);
1005 void RenderViewHostImpl::OnShowView(int route_id,
1006 WindowOpenDisposition disposition,
1007 const gfx::Rect& initial_rect,
1008 bool user_gesture) {
1009 delegate_->ShowCreatedWindow(route_id, disposition, initial_rect,
1010 user_gesture);
1011 Send(new ViewMsg_Move_ACK(route_id));
1014 void RenderViewHostImpl::OnShowWidget(int route_id,
1015 const gfx::Rect& initial_rect) {
1016 if (is_active_)
1017 delegate_->ShowCreatedWidget(route_id, initial_rect);
1018 Send(new ViewMsg_Move_ACK(route_id));
1021 void RenderViewHostImpl::OnShowFullscreenWidget(int route_id) {
1022 if (is_active_)
1023 delegate_->ShowCreatedFullscreenWidget(route_id);
1024 Send(new ViewMsg_Move_ACK(route_id));
1027 void RenderViewHostImpl::OnRenderViewReady() {
1028 render_view_termination_status_ = base::TERMINATION_STATUS_STILL_RUNNING;
1029 SendScreenRects();
1030 WasResized();
1031 delegate_->RenderViewReady(this);
1034 void RenderViewHostImpl::OnRenderProcessGone(int status, int exit_code) {
1035 // Do nothing, otherwise RenderWidgetHostImpl will assume it is not a
1036 // RenderViewHostImpl and destroy itself.
1037 // TODO(nasko): Remove this hack once RenderViewHost and RenderWidgetHost are
1038 // decoupled.
1041 void RenderViewHostImpl::OnUpdateState(int32 page_id, const PageState& state) {
1042 // If the following DCHECK fails, you have encountered a tricky edge-case that
1043 // has evaded reproduction for a very long time. Please report what you were
1044 // doing on http://crbug.com/407376, whether or not you can reproduce the
1045 // failure.
1046 DCHECK_EQ(page_id, page_id_);
1048 // Without this check, the renderer can trick the browser into using
1049 // filenames it can't access in a future session restore.
1050 if (!CanAccessFilesOfPageState(state)) {
1051 bad_message::ReceivedBadMessage(
1052 GetProcess(), bad_message::RVH_CAN_ACCESS_FILES_OF_PAGE_STATE);
1053 return;
1056 delegate_->UpdateState(this, page_id, state);
1059 void RenderViewHostImpl::OnUpdateTargetURL(const GURL& url) {
1060 if (is_active_)
1061 delegate_->UpdateTargetURL(this, url);
1063 // Send a notification back to the renderer that we are ready to
1064 // receive more target urls.
1065 Send(new ViewMsg_UpdateTargetURL_ACK(GetRoutingID()));
1068 void RenderViewHostImpl::OnClose() {
1069 // If the renderer is telling us to close, it has already run the unload
1070 // events, and we can take the fast path.
1071 ClosePageIgnoringUnloadEvents();
1074 void RenderViewHostImpl::OnRequestMove(const gfx::Rect& pos) {
1075 if (is_active_)
1076 delegate_->RequestMove(pos);
1077 Send(new ViewMsg_Move_ACK(GetRoutingID()));
1080 void RenderViewHostImpl::OnDocumentAvailableInMainFrame(
1081 bool uses_temporary_zoom_level) {
1082 delegate_->DocumentAvailableInMainFrame(this);
1084 if (!uses_temporary_zoom_level)
1085 return;
1087 HostZoomMapImpl* host_zoom_map =
1088 static_cast<HostZoomMapImpl*>(HostZoomMap::Get(GetSiteInstance()));
1089 host_zoom_map->SetTemporaryZoomLevel(GetProcess()->GetID(),
1090 GetRoutingID(),
1091 host_zoom_map->GetDefaultZoomLevel());
1094 void RenderViewHostImpl::OnDidContentsPreferredSizeChange(
1095 const gfx::Size& new_size) {
1096 delegate_->UpdatePreferredSize(new_size);
1099 void RenderViewHostImpl::OnRenderAutoResized(const gfx::Size& new_size) {
1100 delegate_->ResizeDueToAutoResize(new_size);
1103 void RenderViewHostImpl::OnRouteCloseEvent() {
1104 // Have the delegate route this to the active RenderViewHost.
1105 delegate_->RouteCloseEvent(this);
1108 void RenderViewHostImpl::OnStartDragging(
1109 const DropData& drop_data,
1110 WebDragOperationsMask drag_operations_mask,
1111 const SkBitmap& bitmap,
1112 const gfx::Vector2d& bitmap_offset_in_dip,
1113 const DragEventSourceInfo& event_info) {
1114 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1115 if (!view)
1116 return;
1118 DropData filtered_data(drop_data);
1119 RenderProcessHost* process = GetProcess();
1120 ChildProcessSecurityPolicyImpl* policy =
1121 ChildProcessSecurityPolicyImpl::GetInstance();
1123 // Allow drag of Javascript URLs to enable bookmarklet drag to bookmark bar.
1124 if (!filtered_data.url.SchemeIs(url::kJavaScriptScheme))
1125 process->FilterURL(true, &filtered_data.url);
1126 process->FilterURL(false, &filtered_data.html_base_url);
1127 // Filter out any paths that the renderer didn't have access to. This prevents
1128 // the following attack on a malicious renderer:
1129 // 1. StartDragging IPC sent with renderer-specified filesystem paths that it
1130 // doesn't have read permissions for.
1131 // 2. We initiate a native DnD operation.
1132 // 3. DnD operation immediately ends since mouse is not held down. DnD events
1133 // still fire though, which causes read permissions to be granted to the
1134 // renderer for any file paths in the drop.
1135 filtered_data.filenames.clear();
1136 for (std::vector<ui::FileInfo>::const_iterator it =
1137 drop_data.filenames.begin();
1138 it != drop_data.filenames.end();
1139 ++it) {
1140 if (policy->CanReadFile(GetProcess()->GetID(), it->path))
1141 filtered_data.filenames.push_back(*it);
1144 storage::FileSystemContext* file_system_context =
1145 BrowserContext::GetStoragePartition(GetProcess()->GetBrowserContext(),
1146 GetSiteInstance())
1147 ->GetFileSystemContext();
1148 filtered_data.file_system_files.clear();
1149 for (size_t i = 0; i < drop_data.file_system_files.size(); ++i) {
1150 storage::FileSystemURL file_system_url =
1151 file_system_context->CrackURL(drop_data.file_system_files[i].url);
1152 if (policy->CanReadFileSystemFile(GetProcess()->GetID(), file_system_url))
1153 filtered_data.file_system_files.push_back(drop_data.file_system_files[i]);
1156 float scale = GetScaleFactorForView(GetView());
1157 gfx::ImageSkia image(gfx::ImageSkiaRep(bitmap, scale));
1158 view->StartDragging(filtered_data, drag_operations_mask, image,
1159 bitmap_offset_in_dip, event_info);
1162 void RenderViewHostImpl::OnUpdateDragCursor(WebDragOperation current_op) {
1163 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1164 if (view)
1165 view->UpdateDragCursor(current_op);
1168 void RenderViewHostImpl::OnTakeFocus(bool reverse) {
1169 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1170 if (view)
1171 view->TakeFocus(reverse);
1174 void RenderViewHostImpl::OnFocusedNodeChanged(
1175 bool is_editable_node,
1176 const gfx::Rect& node_bounds_in_viewport) {
1177 is_focused_element_editable_ = is_editable_node;
1178 if (view_)
1179 view_->FocusedNodeChanged(is_editable_node);
1180 #if defined(OS_WIN)
1181 if (!is_editable_node && virtual_keyboard_requested_) {
1182 virtual_keyboard_requested_ = false;
1183 delegate_->SetIsVirtualKeyboardRequested(false);
1184 BrowserThread::PostDelayedTask(
1185 BrowserThread::UI, FROM_HERE,
1186 base::Bind(base::IgnoreResult(&DismissVirtualKeyboardTask)),
1187 TimeDelta::FromMilliseconds(kVirtualKeyboardDisplayWaitTimeoutMs));
1189 #endif
1191 // Convert node_bounds to screen coordinates.
1192 gfx::Rect view_bounds_in_screen = view_->GetViewBounds();
1193 gfx::Point origin = node_bounds_in_viewport.origin();
1194 origin.Offset(view_bounds_in_screen.x(), view_bounds_in_screen.y());
1195 gfx::Rect node_bounds_in_screen(origin.x(), origin.y(),
1196 node_bounds_in_viewport.width(),
1197 node_bounds_in_viewport.height());
1198 FocusedNodeDetails details = {is_editable_node, node_bounds_in_screen};
1199 NotificationService::current()->Notify(NOTIFICATION_FOCUS_CHANGED_IN_PAGE,
1200 Source<RenderViewHost>(this),
1201 Details<FocusedNodeDetails>(&details));
1204 void RenderViewHostImpl::OnUserGesture() {
1205 delegate_->OnUserGesture();
1208 void RenderViewHostImpl::OnClosePageACK() {
1209 decrement_in_flight_event_count();
1210 ClosePageIgnoringUnloadEvents();
1213 void RenderViewHostImpl::NotifyRendererUnresponsive() {
1214 delegate_->RendererUnresponsive(this);
1217 void RenderViewHostImpl::NotifyRendererResponsive() {
1218 delegate_->RendererResponsive(this);
1221 void RenderViewHostImpl::RequestToLockMouse(bool user_gesture,
1222 bool last_unlocked_by_target) {
1223 delegate_->RequestToLockMouse(user_gesture, last_unlocked_by_target);
1226 bool RenderViewHostImpl::IsFullscreenGranted() const {
1227 return delegate_->IsFullscreenForCurrentTab();
1230 blink::WebDisplayMode RenderViewHostImpl::GetDisplayMode() const {
1231 return delegate_->GetDisplayMode();
1234 void RenderViewHostImpl::OnFocus() {
1235 // Note: We allow focus and blur from swapped out RenderViewHosts, even when
1236 // the active RenderViewHost is in a different BrowsingInstance (e.g., WebUI).
1237 delegate_->Activate();
1240 void RenderViewHostImpl::OnBlur() {
1241 delegate_->Deactivate();
1244 gfx::Rect RenderViewHostImpl::GetRootWindowResizerRect() const {
1245 return delegate_->GetRootWindowResizerRect();
1248 void RenderViewHostImpl::ForwardMouseEvent(
1249 const blink::WebMouseEvent& mouse_event) {
1250 RenderWidgetHostImpl::ForwardMouseEvent(mouse_event);
1251 if (mouse_event.type == WebInputEvent::MouseWheel && ignore_input_events())
1252 delegate_->OnIgnoredUIEvent();
1255 void RenderViewHostImpl::ForwardKeyboardEvent(
1256 const NativeWebKeyboardEvent& key_event) {
1257 if (ignore_input_events()) {
1258 if (key_event.type == WebInputEvent::RawKeyDown)
1259 delegate_->OnIgnoredUIEvent();
1260 return;
1262 RenderWidgetHostImpl::ForwardKeyboardEvent(key_event);
1265 void RenderViewHostImpl::OnTextSurroundingSelectionResponse(
1266 const base::string16& content,
1267 size_t start_offset,
1268 size_t end_offset) {
1269 if (!view_)
1270 return;
1271 view_->OnTextSurroundingSelectionResponse(content, start_offset, end_offset);
1274 WebPreferences RenderViewHostImpl::GetWebkitPreferences() {
1275 if (!web_preferences_.get()) {
1276 OnWebkitPreferencesChanged();
1278 return *web_preferences_;
1281 void RenderViewHostImpl::UpdateWebkitPreferences(const WebPreferences& prefs) {
1282 web_preferences_.reset(new WebPreferences(prefs));
1283 Send(new ViewMsg_UpdateWebPreferences(GetRoutingID(), prefs));
1286 void RenderViewHostImpl::OnWebkitPreferencesChanged() {
1287 // This is defensive code to avoid infinite loops due to code run inside
1288 // UpdateWebkitPreferences() accidentally updating more preferences and thus
1289 // calling back into this code. See crbug.com/398751 for one past example.
1290 if (updating_web_preferences_)
1291 return;
1292 updating_web_preferences_ = true;
1293 UpdateWebkitPreferences(ComputeWebkitPrefs());
1294 updating_web_preferences_ = false;
1297 void RenderViewHostImpl::ClearFocusedElement() {
1298 is_focused_element_editable_ = false;
1299 Send(new ViewMsg_ClearFocusedElement(GetRoutingID()));
1302 bool RenderViewHostImpl::IsFocusedElementEditable() {
1303 return is_focused_element_editable_;
1306 void RenderViewHostImpl::Zoom(PageZoom zoom) {
1307 Send(new ViewMsg_Zoom(GetRoutingID(), zoom));
1310 void RenderViewHostImpl::DisableScrollbarsForThreshold(const gfx::Size& size) {
1311 Send(new ViewMsg_DisableScrollbarsForSmallWindows(GetRoutingID(), size));
1314 void RenderViewHostImpl::EnablePreferredSizeMode() {
1315 Send(new ViewMsg_EnablePreferredSizeChangedMode(GetRoutingID()));
1318 void RenderViewHostImpl::EnableAutoResize(const gfx::Size& min_size,
1319 const gfx::Size& max_size) {
1320 SetAutoResize(true, min_size, max_size);
1321 Send(new ViewMsg_EnableAutoResize(GetRoutingID(), min_size, max_size));
1324 void RenderViewHostImpl::DisableAutoResize(const gfx::Size& new_size) {
1325 SetAutoResize(false, gfx::Size(), gfx::Size());
1326 Send(new ViewMsg_DisableAutoResize(GetRoutingID(), new_size));
1327 if (!new_size.IsEmpty())
1328 GetView()->SetSize(new_size);
1331 void RenderViewHostImpl::CopyImageAt(int x, int y) {
1332 Send(new ViewMsg_CopyImageAt(GetRoutingID(), x, y));
1335 void RenderViewHostImpl::SaveImageAt(int x, int y) {
1336 Send(new ViewMsg_SaveImageAt(GetRoutingID(), x, y));
1339 void RenderViewHostImpl::ExecuteMediaPlayerActionAtLocation(
1340 const gfx::Point& location, const blink::WebMediaPlayerAction& action) {
1341 Send(new ViewMsg_MediaPlayerActionAt(GetRoutingID(), location, action));
1344 void RenderViewHostImpl::ExecutePluginActionAtLocation(
1345 const gfx::Point& location, const blink::WebPluginAction& action) {
1346 Send(new ViewMsg_PluginActionAt(GetRoutingID(), location, action));
1349 void RenderViewHostImpl::NotifyMoveOrResizeStarted() {
1350 Send(new ViewMsg_MoveOrResizeStarted(GetRoutingID()));
1353 void RenderViewHostImpl::OnDidZoomURL(double zoom_level,
1354 const GURL& url) {
1355 HostZoomMapImpl* host_zoom_map =
1356 static_cast<HostZoomMapImpl*>(HostZoomMap::Get(GetSiteInstance()));
1358 host_zoom_map->SetZoomLevelForView(GetProcess()->GetID(),
1359 GetRoutingID(),
1360 zoom_level,
1361 net::GetHostOrSpecFromURL(url));
1364 void RenderViewHostImpl::OnPageScaleFactorIsOneChanged(bool is_one) {
1365 if (!GetSiteInstance())
1366 return;
1367 HostZoomMapImpl* host_zoom_map =
1368 static_cast<HostZoomMapImpl*>(HostZoomMap::Get(GetSiteInstance()));
1369 if (!host_zoom_map)
1370 return;
1371 if (!GetProcess())
1372 return;
1373 host_zoom_map->SetPageScaleFactorIsOneForView(GetProcess()->GetID(),
1374 GetRoutingID(), is_one);
1377 void RenderViewHostImpl::OnRunFileChooser(const FileChooserParams& params) {
1378 // Do not allow messages with absolute paths in them as this can permit a
1379 // renderer to coerce the browser to perform I/O on a renderer controlled
1380 // path.
1381 if (params.default_file_name != params.default_file_name.BaseName()) {
1382 bad_message::ReceivedBadMessage(GetProcess(),
1383 bad_message::RVH_FILE_CHOOSER_PATH);
1384 return;
1387 delegate_->RunFileChooser(this, params);
1390 void RenderViewHostImpl::OnFocusedNodeTouched(bool editable) {
1391 #if defined(OS_WIN)
1392 if (editable) {
1393 virtual_keyboard_requested_ = base::win::DisplayVirtualKeyboard();
1394 delegate_->SetIsVirtualKeyboardRequested(true);
1395 } else {
1396 virtual_keyboard_requested_ = false;
1397 delegate_->SetIsVirtualKeyboardRequested(false);
1398 base::win::DismissVirtualKeyboard();
1400 #endif
1403 bool RenderViewHostImpl::CanAccessFilesOfPageState(
1404 const PageState& state) const {
1405 ChildProcessSecurityPolicyImpl* policy =
1406 ChildProcessSecurityPolicyImpl::GetInstance();
1408 const std::vector<base::FilePath>& file_paths = state.GetReferencedFiles();
1409 for (const auto& file : file_paths) {
1410 if (!policy->CanReadFile(GetProcess()->GetID(), file))
1411 return false;
1413 return true;
1416 void RenderViewHostImpl::GrantFileAccessFromPageState(const PageState& state) {
1417 ChildProcessSecurityPolicyImpl* policy =
1418 ChildProcessSecurityPolicyImpl::GetInstance();
1420 const std::vector<base::FilePath>& file_paths = state.GetReferencedFiles();
1421 for (const auto& file : file_paths) {
1422 if (!policy->CanReadFile(GetProcess()->GetID(), file))
1423 policy->GrantReadFile(GetProcess()->GetID(), file);
1427 void RenderViewHostImpl::SelectWordAroundCaret() {
1428 Send(new ViewMsg_SelectWordAroundCaret(GetRoutingID()));
1431 } // namespace content