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