Add 9 patch scrollbar assets to native theme
[chromium-blink-merge.git] / content / browser / renderer_host / render_view_host_impl.cc
blob0d7e469f1205156ed8f18d0f4e96ac2f68fab84d
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/accessibility/browser_accessibility_manager.h"
27 #include "content/browser/child_process_security_policy_impl.h"
28 #include "content/browser/cross_site_request_manager.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/input/timeout_monitor.h"
39 #include "content/browser/renderer_host/media/audio_renderer_host.h"
40 #include "content/browser/renderer_host/render_process_host_impl.h"
41 #include "content/browser/renderer_host/render_view_host_delegate.h"
42 #include "content/common/accessibility_messages.h"
43 #include "content/common/browser_plugin/browser_plugin_messages.h"
44 #include "content/common/content_switches_internal.h"
45 #include "content/common/desktop_notification_messages.h"
46 #include "content/common/drag_messages.h"
47 #include "content/common/frame_messages.h"
48 #include "content/common/input_messages.h"
49 #include "content/common/inter_process_time_ticks_converter.h"
50 #include "content/common/speech_recognition_messages.h"
51 #include "content/common/swapped_out_messages.h"
52 #include "content/common/view_messages.h"
53 #include "content/port/browser/render_view_host_delegate_view.h"
54 #include "content/port/browser/render_widget_host_view_port.h"
55 #include "content/public/browser/ax_event_notification_details.h"
56 #include "content/public/browser/browser_accessibility_state.h"
57 #include "content/public/browser/browser_context.h"
58 #include "content/public/browser/browser_message_filter.h"
59 #include "content/public/browser/content_browser_client.h"
60 #include "content/public/browser/native_web_keyboard_event.h"
61 #include "content/public/browser/notification_details.h"
62 #include "content/public/browser/notification_service.h"
63 #include "content/public/browser/notification_types.h"
64 #include "content/public/browser/render_frame_host.h"
65 #include "content/public/browser/render_widget_host_iterator.h"
66 #include "content/public/browser/user_metrics.h"
67 #include "content/public/common/bindings_policy.h"
68 #include "content/public/common/content_constants.h"
69 #include "content/public/common/content_switches.h"
70 #include "content/public/common/context_menu_params.h"
71 #include "content/public/common/drop_data.h"
72 #include "content/public/common/result_codes.h"
73 #include "content/public/common/url_constants.h"
74 #include "content/public/common/url_utils.h"
75 #include "net/base/net_util.h"
76 #include "net/base/network_change_notifier.h"
77 #include "net/url_request/url_request_context_getter.h"
78 #include "third_party/skia/include/core/SkBitmap.h"
79 #include "ui/accessibility/ax_tree.h"
80 #include "ui/base/touch/touch_device.h"
81 #include "ui/base/touch/touch_enabled.h"
82 #include "ui/base/ui_base_switches.h"
83 #include "ui/gfx/image/image_skia.h"
84 #include "ui/gfx/native_widget_types.h"
85 #include "ui/native_theme/native_theme_switches.h"
86 #include "ui/shell_dialogs/selected_file_info.h"
87 #include "webkit/browser/fileapi/isolated_context.h"
89 #if defined(OS_MACOSX)
90 #include "content/browser/renderer_host/popup_menu_helper_mac.h"
91 #elif defined(OS_ANDROID)
92 #include "content/browser/media/android/browser_media_player_manager.h"
93 #elif defined(OS_WIN)
94 #include "base/win/win_util.h"
95 #endif
97 using base::TimeDelta;
98 using blink::WebConsoleMessage;
99 using blink::WebDragOperation;
100 using blink::WebDragOperationNone;
101 using blink::WebDragOperationsMask;
102 using blink::WebInputEvent;
103 using blink::WebMediaPlayerAction;
104 using blink::WebPluginAction;
106 namespace content {
107 namespace {
109 // Translate a WebKit text direction into a base::i18n one.
110 base::i18n::TextDirection WebTextDirectionToChromeTextDirection(
111 blink::WebTextDirection dir) {
112 switch (dir) {
113 case blink::WebTextDirectionLeftToRight:
114 return base::i18n::LEFT_TO_RIGHT;
115 case blink::WebTextDirectionRightToLeft:
116 return base::i18n::RIGHT_TO_LEFT;
117 default:
118 NOTREACHED();
119 return base::i18n::UNKNOWN_DIRECTION;
123 #if defined(OS_WIN)
125 const int kVirtualKeyboardDisplayWaitTimeoutMs = 100;
126 const int kMaxVirtualKeyboardDisplayRetries = 5;
128 void DismissVirtualKeyboardTask() {
129 static int virtual_keyboard_display_retries = 0;
130 // If the virtual keyboard is not yet visible, then we execute the task again
131 // waiting for it to show up.
132 if (!base::win::DismissVirtualKeyboard()) {
133 if (virtual_keyboard_display_retries < kMaxVirtualKeyboardDisplayRetries) {
134 BrowserThread::PostDelayedTask(
135 BrowserThread::UI, FROM_HERE,
136 base::Bind(base::IgnoreResult(&DismissVirtualKeyboardTask)),
137 TimeDelta::FromMilliseconds(kVirtualKeyboardDisplayWaitTimeoutMs));
138 ++virtual_keyboard_display_retries;
139 } else {
140 virtual_keyboard_display_retries = 0;
144 #endif
146 } // namespace
148 // static
149 const int RenderViewHostImpl::kUnloadTimeoutMS = 1000;
151 ///////////////////////////////////////////////////////////////////////////////
152 // RenderViewHost, public:
154 // static
155 bool RenderViewHostImpl::IsRVHStateActive(RenderViewHostImplState rvh_state) {
156 if (rvh_state == STATE_DEFAULT ||
157 rvh_state == STATE_WAITING_FOR_UNLOAD_ACK ||
158 rvh_state == STATE_WAITING_FOR_COMMIT ||
159 rvh_state == STATE_WAITING_FOR_CLOSE)
160 return true;
161 return false;
164 // static
165 RenderViewHost* RenderViewHost::FromID(int render_process_id,
166 int render_view_id) {
167 return RenderViewHostImpl::FromID(render_process_id, render_view_id);
170 // static
171 RenderViewHost* RenderViewHost::From(RenderWidgetHost* rwh) {
172 DCHECK(rwh->IsRenderView());
173 return static_cast<RenderViewHostImpl*>(RenderWidgetHostImpl::From(rwh));
176 ///////////////////////////////////////////////////////////////////////////////
177 // RenderViewHostImpl, public:
179 // static
180 RenderViewHostImpl* RenderViewHostImpl::FromID(int render_process_id,
181 int render_view_id) {
182 RenderWidgetHost* widget =
183 RenderWidgetHost::FromID(render_process_id, render_view_id);
184 if (!widget || !widget->IsRenderView())
185 return NULL;
186 return static_cast<RenderViewHostImpl*>(RenderWidgetHostImpl::From(widget));
189 RenderViewHostImpl::RenderViewHostImpl(
190 SiteInstance* instance,
191 RenderViewHostDelegate* delegate,
192 RenderWidgetHostDelegate* widget_delegate,
193 int routing_id,
194 int main_frame_routing_id,
195 bool swapped_out,
196 bool hidden)
197 : RenderWidgetHostImpl(widget_delegate,
198 instance->GetProcess(),
199 routing_id,
200 hidden),
201 frames_ref_count_(0),
202 delegate_(delegate),
203 instance_(static_cast<SiteInstanceImpl*>(instance)),
204 waiting_for_drag_context_response_(false),
205 enabled_bindings_(0),
206 navigations_suspended_(false),
207 has_accessed_initial_document_(false),
208 main_frame_routing_id_(main_frame_routing_id),
209 run_modal_reply_msg_(NULL),
210 run_modal_opener_id_(MSG_ROUTING_NONE),
211 is_waiting_for_beforeunload_ack_(false),
212 unload_ack_is_for_cross_site_transition_(false),
213 are_javascript_messages_suppressed_(false),
214 sudden_termination_allowed_(false),
215 render_view_termination_status_(base::TERMINATION_STATUS_STILL_RUNNING),
216 virtual_keyboard_requested_(false),
217 weak_factory_(this) {
218 DCHECK(instance_.get());
219 CHECK(delegate_); // http://crbug.com/82827
221 GetProcess()->EnableSendQueue();
223 if (swapped_out) {
224 rvh_state_ = STATE_SWAPPED_OUT;
225 } else {
226 rvh_state_ = STATE_DEFAULT;
227 instance_->increment_active_view_count();
230 if (ResourceDispatcherHostImpl::Get()) {
231 BrowserThread::PostTask(
232 BrowserThread::IO, FROM_HERE,
233 base::Bind(&ResourceDispatcherHostImpl::OnRenderViewHostCreated,
234 base::Unretained(ResourceDispatcherHostImpl::Get()),
235 GetProcess()->GetID(), GetRoutingID()));
238 #if defined(OS_ANDROID)
239 media_player_manager_.reset(BrowserMediaPlayerManager::Create(this));
240 #endif
242 unload_event_monitor_timeout_.reset(new TimeoutMonitor(base::Bind(
243 &RenderViewHostImpl::OnSwappedOut, weak_factory_.GetWeakPtr(), true)));
246 RenderViewHostImpl::~RenderViewHostImpl() {
247 if (ResourceDispatcherHostImpl::Get()) {
248 BrowserThread::PostTask(
249 BrowserThread::IO, FROM_HERE,
250 base::Bind(&ResourceDispatcherHostImpl::OnRenderViewHostDeleted,
251 base::Unretained(ResourceDispatcherHostImpl::Get()),
252 GetProcess()->GetID(), GetRoutingID()));
255 delegate_->RenderViewDeleted(this);
257 // Be sure to clean up any leftover state from cross-site requests.
258 CrossSiteRequestManager::GetInstance()->SetHasPendingCrossSiteRequest(
259 GetProcess()->GetID(), GetRoutingID(), false);
261 // If this was swapped out, it already decremented the active view
262 // count of the SiteInstance it belongs to.
263 if (IsRVHStateActive(rvh_state_))
264 instance_->decrement_active_view_count();
267 RenderViewHostDelegate* RenderViewHostImpl::GetDelegate() const {
268 return delegate_;
271 SiteInstance* RenderViewHostImpl::GetSiteInstance() const {
272 return instance_.get();
275 bool RenderViewHostImpl::CreateRenderView(
276 const base::string16& frame_name,
277 int opener_route_id,
278 int32 max_page_id) {
279 TRACE_EVENT0("renderer_host", "RenderViewHostImpl::CreateRenderView");
280 DCHECK(!IsRenderViewLive()) << "Creating view twice";
282 // The process may (if we're sharing a process with another host that already
283 // initialized it) or may not (we have our own process or the old process
284 // crashed) have been initialized. Calling Init multiple times will be
285 // ignored, so this is safe.
286 if (!GetProcess()->Init())
287 return false;
288 DCHECK(GetProcess()->HasConnection());
289 DCHECK(GetProcess()->GetBrowserContext());
291 renderer_initialized_ = true;
293 GpuSurfaceTracker::Get()->SetSurfaceHandle(
294 surface_id(), GetCompositingSurface());
296 // Ensure the RenderView starts with a next_page_id larger than any existing
297 // page ID it might be asked to render.
298 int32 next_page_id = 1;
299 if (max_page_id > -1)
300 next_page_id = max_page_id + 1;
302 ViewMsg_New_Params params;
303 params.renderer_preferences =
304 delegate_->GetRendererPrefs(GetProcess()->GetBrowserContext());
305 params.web_preferences = delegate_->GetWebkitPrefs();
306 params.view_id = GetRoutingID();
307 params.main_frame_routing_id = main_frame_routing_id_;
308 params.surface_id = surface_id();
309 params.session_storage_namespace_id =
310 delegate_->GetSessionStorageNamespace(instance_)->id();
311 params.frame_name = frame_name;
312 // Ensure the RenderView sets its opener correctly.
313 params.opener_route_id = opener_route_id;
314 params.swapped_out = !IsRVHStateActive(rvh_state_);
315 params.hidden = is_hidden();
316 params.next_page_id = next_page_id;
317 GetWebScreenInfo(&params.screen_info);
318 params.accessibility_mode = accessibility_mode();
320 Send(new ViewMsg_New(params));
322 // If it's enabled, tell the renderer to set up the Javascript bindings for
323 // sending messages back to the browser.
324 if (GetProcess()->IsGuest())
325 DCHECK_EQ(0, enabled_bindings_);
326 Send(new ViewMsg_AllowBindings(GetRoutingID(), enabled_bindings_));
327 // Let our delegate know that we created a RenderView.
328 delegate_->RenderViewCreated(this);
330 return true;
333 bool RenderViewHostImpl::IsRenderViewLive() const {
334 return GetProcess()->HasConnection() && renderer_initialized_;
337 void RenderViewHostImpl::SyncRendererPrefs() {
338 Send(new ViewMsg_SetRendererPrefs(GetRoutingID(),
339 delegate_->GetRendererPrefs(
340 GetProcess()->GetBrowserContext())));
343 WebPreferences RenderViewHostImpl::GetWebkitPrefs(const GURL& url) {
344 TRACE_EVENT0("browser", "RenderViewHostImpl::GetWebkitPrefs");
345 WebPreferences prefs;
347 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
349 prefs.javascript_enabled =
350 !command_line.HasSwitch(switches::kDisableJavaScript);
351 prefs.web_security_enabled =
352 !command_line.HasSwitch(switches::kDisableWebSecurity);
353 prefs.plugins_enabled =
354 !command_line.HasSwitch(switches::kDisablePlugins);
355 prefs.java_enabled =
356 !command_line.HasSwitch(switches::kDisableJava);
358 prefs.remote_fonts_enabled =
359 !command_line.HasSwitch(switches::kDisableRemoteFonts);
360 prefs.xslt_enabled =
361 !command_line.HasSwitch(switches::kDisableXSLT);
362 prefs.xss_auditor_enabled =
363 !command_line.HasSwitch(switches::kDisableXSSAuditor);
364 prefs.application_cache_enabled =
365 !command_line.HasSwitch(switches::kDisableApplicationCache);
367 prefs.local_storage_enabled =
368 !command_line.HasSwitch(switches::kDisableLocalStorage);
369 prefs.databases_enabled =
370 !command_line.HasSwitch(switches::kDisableDatabases);
371 #if defined(OS_ANDROID) && defined(ARCH_CPU_X86)
372 prefs.webaudio_enabled =
373 command_line.HasSwitch(switches::kEnableWebAudio);
374 #else
375 prefs.webaudio_enabled =
376 !command_line.HasSwitch(switches::kDisableWebAudio);
377 #endif
379 prefs.experimental_webgl_enabled =
380 GpuProcessHost::gpu_enabled() &&
381 !command_line.HasSwitch(switches::kDisable3DAPIs) &&
382 !command_line.HasSwitch(switches::kDisableExperimentalWebGL);
384 prefs.pepper_3d_enabled =
385 !command_line.HasSwitch(switches::kDisablePepper3d);
387 prefs.flash_3d_enabled =
388 GpuProcessHost::gpu_enabled() &&
389 !command_line.HasSwitch(switches::kDisableFlash3d);
390 prefs.flash_stage3d_enabled =
391 GpuProcessHost::gpu_enabled() &&
392 !command_line.HasSwitch(switches::kDisableFlashStage3d);
393 prefs.flash_stage3d_baseline_enabled =
394 GpuProcessHost::gpu_enabled() &&
395 !command_line.HasSwitch(switches::kDisableFlashStage3d);
397 prefs.gl_multisampling_enabled =
398 !command_line.HasSwitch(switches::kDisableGLMultisampling);
399 prefs.privileged_webgl_extensions_enabled =
400 command_line.HasSwitch(switches::kEnablePrivilegedWebGLExtensions);
401 prefs.site_specific_quirks_enabled =
402 !command_line.HasSwitch(switches::kDisableSiteSpecificQuirks);
403 prefs.allow_file_access_from_file_urls =
404 command_line.HasSwitch(switches::kAllowFileAccessFromFiles);
406 prefs.layer_squashing_enabled = false;
407 if (command_line.HasSwitch(switches::kEnableLayerSquashing))
408 prefs.layer_squashing_enabled = true;
409 if (command_line.HasSwitch(switches::kDisableLayerSquashing))
410 prefs.layer_squashing_enabled = false;
412 prefs.show_paint_rects =
413 command_line.HasSwitch(switches::kShowPaintRects);
414 prefs.accelerated_compositing_enabled =
415 GpuProcessHost::gpu_enabled() &&
416 !command_line.HasSwitch(switches::kDisableAcceleratedCompositing);
417 prefs.force_compositing_mode =
418 content::IsForceCompositingModeEnabled() &&
419 !command_line.HasSwitch(switches::kDisableForceCompositingMode);
420 prefs.accelerated_2d_canvas_enabled =
421 GpuProcessHost::gpu_enabled() &&
422 !command_line.HasSwitch(switches::kDisableAccelerated2dCanvas);
423 prefs.antialiased_2d_canvas_disabled =
424 command_line.HasSwitch(switches::kDisable2dCanvasAntialiasing);
425 prefs.accelerated_2d_canvas_msaa_sample_count =
426 atoi(command_line.GetSwitchValueASCII(
427 switches::kAcceleratedCanvas2dMSAASampleCount).c_str());
428 prefs.accelerated_filters_enabled =
429 GpuProcessHost::gpu_enabled() &&
430 command_line.HasSwitch(switches::kEnableAcceleratedFilters);
431 prefs.deferred_filters_enabled =
432 command_line.HasSwitch(switches::kEnableDeferredFilters);
433 prefs.accelerated_compositing_for_3d_transforms_enabled =
434 prefs.accelerated_compositing_for_animation_enabled =
435 !command_line.HasSwitch(switches::kDisableAcceleratedLayers);
436 prefs.accelerated_compositing_for_plugins_enabled = true;
437 prefs.accelerated_compositing_for_video_enabled =
438 !command_line.HasSwitch(switches::kDisableAcceleratedVideo);
439 prefs.lazy_layout_enabled =
440 command_line.HasSwitch(switches::kEnableExperimentalWebPlatformFeatures);
441 prefs.region_based_columns_enabled =
442 command_line.HasSwitch(switches::kEnableRegionBasedColumns);
443 prefs.threaded_html_parser =
444 !command_line.HasSwitch(switches::kDisableThreadedHTMLParser);
445 prefs.experimental_websocket_enabled =
446 command_line.HasSwitch(switches::kEnableExperimentalWebSocket);
447 if (command_line.HasSwitch(cc::switches::kEnablePinchVirtualViewport)) {
448 prefs.pinch_virtual_viewport_enabled = true;
449 prefs.pinch_overlay_scrollbar_thickness = 10;
451 prefs.use_solid_color_scrollbars = ui::IsOverlayScrollbarEnabled();
453 #if defined(OS_ANDROID)
454 prefs.user_gesture_required_for_media_playback = !command_line.HasSwitch(
455 switches::kDisableGestureRequirementForMediaPlayback);
456 prefs.user_gesture_required_for_media_fullscreen = !command_line.HasSwitch(
457 switches::kDisableGestureRequirementForMediaFullscreen);
458 #endif
460 prefs.touch_enabled = ui::AreTouchEventsEnabled();
461 prefs.device_supports_touch = prefs.touch_enabled &&
462 ui::IsTouchDevicePresent();
463 #if defined(OS_ANDROID)
464 prefs.device_supports_mouse = false;
465 #endif
467 prefs.pointer_events_max_touch_points = ui::MaxTouchPoints();
469 prefs.touch_adjustment_enabled =
470 !command_line.HasSwitch(switches::kDisableTouchAdjustment);
471 prefs.compositor_touch_hit_testing =
472 !command_line.HasSwitch(
473 cc::switches::kDisableCompositorTouchHitTesting) &&
474 !command_line.HasSwitch(switches::kEnableBleedingEdgeRenderingFastPaths);
477 #if defined(OS_MACOSX) || defined(OS_CHROMEOS)
478 bool default_enable_scroll_animator = true;
479 #else
480 bool default_enable_scroll_animator = false;
481 #endif
482 prefs.enable_scroll_animator = default_enable_scroll_animator;
483 if (command_line.HasSwitch(switches::kEnableSmoothScrolling))
484 prefs.enable_scroll_animator = true;
485 if (command_line.HasSwitch(switches::kDisableSmoothScrolling))
486 prefs.enable_scroll_animator = false;
488 prefs.visual_word_movement_enabled =
489 command_line.HasSwitch(switches::kEnableVisualWordMovement);
491 // Certain GPU features might have been blacklisted.
492 GpuDataManagerImpl::GetInstance()->UpdateRendererWebPrefs(&prefs);
494 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
495 GetProcess()->GetID())) {
496 prefs.loads_images_automatically = true;
497 prefs.javascript_enabled = true;
500 prefs.is_online = !net::NetworkChangeNotifier::IsOffline();
502 prefs.fixed_position_creates_stacking_context = !command_line.HasSwitch(
503 switches::kDisableFixedPositionCreatesStackingContext);
505 prefs.gesture_tap_highlight_enabled = !command_line.HasSwitch(
506 switches::kDisableGestureTapHighlight);
508 prefs.number_of_cpu_cores = base::SysInfo::NumberOfProcessors();
510 prefs.viewport_meta_enabled =
511 command_line.HasSwitch(switches::kEnableViewportMeta);
513 prefs.viewport_enabled =
514 command_line.HasSwitch(switches::kEnableViewport) ||
515 prefs.viewport_meta_enabled;
517 prefs.main_frame_resizes_are_orientation_changes =
518 command_line.HasSwitch(switches::kMainFrameResizesAreOrientationChanges);
520 prefs.deferred_image_decoding_enabled =
521 command_line.HasSwitch(switches::kEnableDeferredImageDecoding) ||
522 content::IsImplSidePaintingEnabled();
524 prefs.spatial_navigation_enabled = command_line.HasSwitch(
525 switches::kEnableSpatialNavigation);
527 GetContentClient()->browser()->OverrideWebkitPrefs(this, url, &prefs);
529 // Disable compositing in guests until we have compositing path implemented
530 // for guests.
531 bool guest_compositing_enabled = !command_line.HasSwitch(
532 switches::kDisableBrowserPluginCompositing);
533 if (GetProcess()->IsGuest() && !guest_compositing_enabled) {
534 prefs.force_compositing_mode = false;
535 prefs.accelerated_compositing_enabled = false;
538 return prefs;
541 void RenderViewHostImpl::Navigate(const FrameMsg_Navigate_Params& params) {
542 TRACE_EVENT0("renderer_host", "RenderViewHostImpl::Navigate");
543 delegate_->GetFrameTree()->GetMainFrame()->Navigate(params);
546 void RenderViewHostImpl::NavigateToURL(const GURL& url) {
547 delegate_->GetFrameTree()->GetMainFrame()->NavigateToURL(url);
550 void RenderViewHostImpl::SetNavigationsSuspended(
551 bool suspend,
552 const base::TimeTicks& proceed_time) {
553 // This should only be called to toggle the state.
554 DCHECK(navigations_suspended_ != suspend);
556 navigations_suspended_ = suspend;
557 if (!suspend && suspended_nav_params_) {
558 // There's navigation message params waiting to be sent. Now that we're not
559 // suspended anymore, resume navigation by sending them. If we were swapped
560 // out, we should also stop filtering out the IPC messages now.
561 SetState(STATE_DEFAULT);
563 DCHECK(!proceed_time.is_null());
564 suspended_nav_params_->browser_navigation_start = proceed_time;
565 Send(new FrameMsg_Navigate(
566 main_frame_routing_id_, *suspended_nav_params_.get()));
567 suspended_nav_params_.reset();
571 void RenderViewHostImpl::CancelSuspendedNavigations() {
572 // Clear any state if a pending navigation is canceled or pre-empted.
573 if (suspended_nav_params_)
574 suspended_nav_params_.reset();
575 navigations_suspended_ = false;
578 void RenderViewHostImpl::SuppressDialogsUntilSwapOut() {
579 Send(new ViewMsg_SuppressDialogsUntilSwapOut(GetRoutingID()));
582 void RenderViewHostImpl::SwapOut() {
583 SetState(STATE_WAITING_FOR_UNLOAD_ACK);
584 unload_event_monitor_timeout_->Start(
585 base::TimeDelta::FromMilliseconds(kUnloadTimeoutMS));
587 if (IsRenderViewLive()) {
588 Send(new ViewMsg_SwapOut(GetRoutingID()));
590 delegate_->SwappedOut(this);
593 void RenderViewHostImpl::OnSwapOutACK() {
594 OnSwappedOut(false);
597 void RenderViewHostImpl::OnSwappedOut(bool timed_out) {
598 // Ignore spurious swap out ack.
599 if (!IsWaitingForUnloadACK())
600 return;
601 unload_event_monitor_timeout_->Stop();
602 if (timed_out) {
603 base::ProcessHandle process_handle = GetProcess()->GetHandle();
604 int views = 0;
606 // Count the number of active widget hosts for the process, which
607 // is equivalent to views using the process as of this writing.
608 scoped_ptr<RenderWidgetHostIterator> widgets(
609 RenderWidgetHost::GetRenderWidgetHosts());
610 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
611 if (widget->GetProcess()->GetID() == GetProcess()->GetID())
612 ++views;
615 if (!RenderProcessHost::run_renderer_in_process() &&
616 process_handle && views <= 1) {
617 // The process can safely be terminated, only if WebContents sets
618 // SuddenTerminationAllowed, which indicates that the timer has expired.
619 // This is not the case if we load data URLs or about:blank. The reason
620 // is that those have no network requests and this code is hit without
621 // setting the unresponsiveness timer. This allows a corner case where a
622 // navigation to a data URL will leave a process running, if the
623 // beforeunload handler completes fine, but the unload handler hangs.
624 // At this time, the complexity to solve this edge case is not worthwhile.
625 if (SuddenTerminationAllowed()) {
626 // We should kill the process, but for now, just log the data so we can
627 // diagnose the kill rate and investigate if separate timer is needed.
628 // http://crbug.com/104346.
630 // Log a histogram point to help us diagnose how many of those kills
631 // we have performed. 1 is the enum value for RendererType Normal for
632 // the histogram.
633 UMA_HISTOGRAM_PERCENTAGE(
634 "BrowserRenderProcessHost.ChildKillsUnresponsive", 1);
639 switch (rvh_state_) {
640 case STATE_WAITING_FOR_UNLOAD_ACK:
641 SetState(STATE_WAITING_FOR_COMMIT);
642 break;
643 case STATE_PENDING_SWAP_OUT:
644 SetState(STATE_SWAPPED_OUT);
645 break;
646 case STATE_PENDING_SHUTDOWN:
647 DCHECK(!pending_shutdown_on_swap_out_.is_null());
648 pending_shutdown_on_swap_out_.Run();
649 break;
650 default:
651 NOTREACHED();
655 void RenderViewHostImpl::WasSwappedOut(
656 const base::Closure& pending_delete_on_swap_out) {
657 Send(new ViewMsg_WasSwappedOut(GetRoutingID()));
658 if (rvh_state_ == STATE_WAITING_FOR_UNLOAD_ACK) {
659 SetState(STATE_PENDING_SWAP_OUT);
660 if (!instance_->active_view_count())
661 SetPendingShutdown(pending_delete_on_swap_out);
662 } else if (rvh_state_ == STATE_WAITING_FOR_COMMIT) {
663 SetState(STATE_SWAPPED_OUT);
664 } else if (rvh_state_ == STATE_DEFAULT) {
665 // When the RenderView is not live, the RenderFrameHostManager will call
666 // CommitPending directly, without calling SwapOut on the old RVH. This will
667 // cause WasSwappedOut to be called directly on the live old RVH.
668 DCHECK(!IsRenderViewLive());
669 SetState(STATE_SWAPPED_OUT);
670 } else {
671 NOTREACHED();
675 void RenderViewHostImpl::SetPendingShutdown(const base::Closure& on_swap_out) {
676 pending_shutdown_on_swap_out_ = on_swap_out;
677 SetState(STATE_PENDING_SHUTDOWN);
680 void RenderViewHostImpl::ClosePage() {
681 SetState(STATE_WAITING_FOR_CLOSE);
682 StartHangMonitorTimeout(TimeDelta::FromMilliseconds(kUnloadTimeoutMS));
684 if (IsRenderViewLive()) {
685 // Since we are sending an IPC message to the renderer, increase the event
686 // count to prevent the hang monitor timeout from being stopped by input
687 // event acknowledgements.
688 increment_in_flight_event_count();
690 // TODO(creis): Should this be moved to Shutdown? It may not be called for
691 // RenderViewHosts that have been swapped out.
692 NotificationService::current()->Notify(
693 NOTIFICATION_RENDER_VIEW_HOST_WILL_CLOSE_RENDER_VIEW,
694 Source<RenderViewHost>(this),
695 NotificationService::NoDetails());
697 Send(new ViewMsg_ClosePage(GetRoutingID()));
698 } else {
699 // This RenderViewHost doesn't have a live renderer, so just skip the unload
700 // event and close the page.
701 ClosePageIgnoringUnloadEvents();
705 void RenderViewHostImpl::ClosePageIgnoringUnloadEvents() {
706 StopHangMonitorTimeout();
707 is_waiting_for_beforeunload_ack_ = false;
709 sudden_termination_allowed_ = true;
710 delegate_->Close(this);
713 bool RenderViewHostImpl::HasPendingCrossSiteRequest() {
714 return CrossSiteRequestManager::GetInstance()->HasPendingCrossSiteRequest(
715 GetProcess()->GetID(), GetRoutingID());
718 void RenderViewHostImpl::SetHasPendingCrossSiteRequest(
719 bool has_pending_request) {
720 CrossSiteRequestManager::GetInstance()->SetHasPendingCrossSiteRequest(
721 GetProcess()->GetID(), GetRoutingID(), has_pending_request);
724 #if defined(OS_ANDROID)
725 void RenderViewHostImpl::ActivateNearestFindResult(int request_id,
726 float x,
727 float y) {
728 Send(new InputMsg_ActivateNearestFindResult(GetRoutingID(),
729 request_id, x, y));
732 void RenderViewHostImpl::RequestFindMatchRects(int current_version) {
733 Send(new ViewMsg_FindMatchRects(GetRoutingID(), current_version));
736 void RenderViewHostImpl::DisableFullscreenEncryptedMediaPlayback() {
737 media_player_manager_->DisableFullscreenEncryptedMediaPlayback();
739 #endif
741 void RenderViewHostImpl::DragTargetDragEnter(
742 const DropData& drop_data,
743 const gfx::Point& client_pt,
744 const gfx::Point& screen_pt,
745 WebDragOperationsMask operations_allowed,
746 int key_modifiers) {
747 const int renderer_id = GetProcess()->GetID();
748 ChildProcessSecurityPolicyImpl* policy =
749 ChildProcessSecurityPolicyImpl::GetInstance();
751 // The URL could have been cobbled together from any highlighted text string,
752 // and can't be interpreted as a capability.
753 DropData filtered_data(drop_data);
754 GetProcess()->FilterURL(true, &filtered_data.url);
756 // The filenames vector, on the other hand, does represent a capability to
757 // access the given files.
758 fileapi::IsolatedContext::FileInfoSet files;
759 for (std::vector<DropData::FileInfo>::iterator iter(
760 filtered_data.filenames.begin());
761 iter != filtered_data.filenames.end(); ++iter) {
762 // A dragged file may wind up as the value of an input element, or it
763 // may be used as the target of a navigation instead. We don't know
764 // which will happen at this point, so generously grant both access
765 // and request permissions to the specific file to cover both cases.
766 // We do not give it the permission to request all file:// URLs.
767 base::FilePath path =
768 base::FilePath::FromUTF8Unsafe(base::UTF16ToUTF8(iter->path));
770 // Make sure we have the same display_name as the one we register.
771 if (iter->display_name.empty()) {
772 std::string name;
773 files.AddPath(path, &name);
774 iter->display_name = base::UTF8ToUTF16(name);
775 } else {
776 files.AddPathWithName(path, base::UTF16ToUTF8(iter->display_name));
779 policy->GrantRequestSpecificFileURL(renderer_id,
780 net::FilePathToFileURL(path));
782 // If the renderer already has permission to read these paths, we don't need
783 // to re-grant them. This prevents problems with DnD for files in the CrOS
784 // file manager--the file manager already had read/write access to those
785 // directories, but dragging a file would cause the read/write access to be
786 // overwritten with read-only access, making them impossible to delete or
787 // rename until the renderer was killed.
788 if (!policy->CanReadFile(renderer_id, path))
789 policy->GrantReadFile(renderer_id, path);
792 fileapi::IsolatedContext* isolated_context =
793 fileapi::IsolatedContext::GetInstance();
794 DCHECK(isolated_context);
795 std::string filesystem_id = isolated_context->RegisterDraggedFileSystem(
796 files);
797 if (!filesystem_id.empty()) {
798 // Grant the permission iff the ID is valid.
799 policy->GrantReadFileSystem(renderer_id, filesystem_id);
801 filtered_data.filesystem_id = base::UTF8ToUTF16(filesystem_id);
803 Send(new DragMsg_TargetDragEnter(GetRoutingID(), filtered_data, client_pt,
804 screen_pt, operations_allowed,
805 key_modifiers));
808 void RenderViewHostImpl::DragTargetDragOver(
809 const gfx::Point& client_pt,
810 const gfx::Point& screen_pt,
811 WebDragOperationsMask operations_allowed,
812 int key_modifiers) {
813 Send(new DragMsg_TargetDragOver(GetRoutingID(), client_pt, screen_pt,
814 operations_allowed, key_modifiers));
817 void RenderViewHostImpl::DragTargetDragLeave() {
818 Send(new DragMsg_TargetDragLeave(GetRoutingID()));
821 void RenderViewHostImpl::DragTargetDrop(
822 const gfx::Point& client_pt,
823 const gfx::Point& screen_pt,
824 int key_modifiers) {
825 Send(new DragMsg_TargetDrop(GetRoutingID(), client_pt, screen_pt,
826 key_modifiers));
829 void RenderViewHostImpl::DesktopNotificationPermissionRequestDone(
830 int callback_context) {
831 Send(new DesktopNotificationMsg_PermissionRequestDone(
832 GetRoutingID(), callback_context));
835 void RenderViewHostImpl::DesktopNotificationPostDisplay(int callback_context) {
836 Send(new DesktopNotificationMsg_PostDisplay(GetRoutingID(),
837 callback_context));
840 void RenderViewHostImpl::DesktopNotificationPostError(
841 int notification_id,
842 const base::string16& message) {
843 Send(new DesktopNotificationMsg_PostError(
844 GetRoutingID(), notification_id, message));
847 void RenderViewHostImpl::DesktopNotificationPostClose(int notification_id,
848 bool by_user) {
849 Send(new DesktopNotificationMsg_PostClose(
850 GetRoutingID(), notification_id, by_user));
853 void RenderViewHostImpl::DesktopNotificationPostClick(int notification_id) {
854 Send(new DesktopNotificationMsg_PostClick(GetRoutingID(), notification_id));
857 void RenderViewHostImpl::ExecuteJavascriptInWebFrame(
858 const base::string16& frame_xpath,
859 const base::string16& jscript) {
860 Send(new ViewMsg_ScriptEvalRequest(GetRoutingID(), frame_xpath, jscript,
861 0, false));
864 void RenderViewHostImpl::ExecuteJavascriptInWebFrameCallbackResult(
865 const base::string16& frame_xpath,
866 const base::string16& jscript,
867 const JavascriptResultCallback& callback) {
868 static int next_id = 1;
869 int key = next_id++;
870 Send(new ViewMsg_ScriptEvalRequest(GetRoutingID(), frame_xpath, jscript,
871 key, true));
872 javascript_callbacks_.insert(std::make_pair(key, callback));
875 void RenderViewHostImpl::JavaScriptDialogClosed(
876 IPC::Message* reply_msg,
877 bool success,
878 const base::string16& user_input) {
879 GetProcess()->SetIgnoreInputEvents(false);
880 bool is_waiting = is_waiting_for_beforeunload_ack_ || IsWaitingForUnloadACK();
882 // If we are executing as part of (before)unload event handling, we don't
883 // want to use the regular hung_renderer_delay_ms_ if the user has agreed to
884 // leave the current page. In this case, use the regular timeout value used
885 // during the (before)unload handling.
886 if (is_waiting) {
887 StartHangMonitorTimeout(TimeDelta::FromMilliseconds(
888 success ? kUnloadTimeoutMS : hung_renderer_delay_ms_));
891 ViewHostMsg_RunJavaScriptMessage::WriteReplyParams(reply_msg,
892 success, user_input);
893 Send(reply_msg);
895 // If we are waiting for an unload or beforeunload ack and the user has
896 // suppressed messages, kill the tab immediately; a page that's spamming
897 // alerts in onbeforeunload is presumably malicious, so there's no point in
898 // continuing to run its script and dragging out the process.
899 // This must be done after sending the reply since RenderView can't close
900 // correctly while waiting for a response.
901 if (is_waiting && are_javascript_messages_suppressed_)
902 delegate_->RendererUnresponsive(
903 this, is_waiting_for_beforeunload_ack_, IsWaitingForUnloadACK());
906 void RenderViewHostImpl::DragSourceEndedAt(
907 int client_x, int client_y, int screen_x, int screen_y,
908 WebDragOperation operation) {
909 Send(new DragMsg_SourceEndedOrMoved(
910 GetRoutingID(),
911 gfx::Point(client_x, client_y),
912 gfx::Point(screen_x, screen_y),
913 true, operation));
916 void RenderViewHostImpl::DragSourceMovedTo(
917 int client_x, int client_y, int screen_x, int screen_y) {
918 Send(new DragMsg_SourceEndedOrMoved(
919 GetRoutingID(),
920 gfx::Point(client_x, client_y),
921 gfx::Point(screen_x, screen_y),
922 false, WebDragOperationNone));
925 void RenderViewHostImpl::DragSourceSystemDragEnded() {
926 Send(new DragMsg_SourceSystemDragEnded(GetRoutingID()));
929 RenderFrameHost* RenderViewHostImpl::GetMainFrame() {
930 return RenderFrameHost::FromID(GetProcess()->GetID(), main_frame_routing_id_);
933 void RenderViewHostImpl::AllowBindings(int bindings_flags) {
934 // Never grant any bindings to browser plugin guests.
935 if (GetProcess()->IsGuest()) {
936 NOTREACHED() << "Never grant bindings to a guest process.";
937 return;
940 // Ensure we aren't granting WebUI bindings to a process that has already
941 // been used for non-privileged views.
942 if (bindings_flags & BINDINGS_POLICY_WEB_UI &&
943 GetProcess()->HasConnection() &&
944 !ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
945 GetProcess()->GetID())) {
946 // This process has no bindings yet. Make sure it does not have more
947 // than this single active view.
948 RenderProcessHostImpl* process =
949 static_cast<RenderProcessHostImpl*>(GetProcess());
950 if (process->GetActiveViewCount() > 1)
951 return;
954 if (bindings_flags & BINDINGS_POLICY_WEB_UI) {
955 ChildProcessSecurityPolicyImpl::GetInstance()->GrantWebUIBindings(
956 GetProcess()->GetID());
959 enabled_bindings_ |= bindings_flags;
960 if (renderer_initialized_)
961 Send(new ViewMsg_AllowBindings(GetRoutingID(), enabled_bindings_));
964 int RenderViewHostImpl::GetEnabledBindings() const {
965 return enabled_bindings_;
968 void RenderViewHostImpl::SetWebUIProperty(const std::string& name,
969 const std::string& value) {
970 // This is a sanity check before telling the renderer to enable the property.
971 // It could lie and send the corresponding IPC messages anyway, but we will
972 // not act on them if enabled_bindings_ doesn't agree. If we get here without
973 // WebUI bindings, kill the renderer process.
974 if (enabled_bindings_ & BINDINGS_POLICY_WEB_UI) {
975 Send(new ViewMsg_SetWebUIProperty(GetRoutingID(), name, value));
976 } else {
977 RecordAction(
978 base::UserMetricsAction("BindingsMismatchTerminate_RVH_WebUI"));
979 base::KillProcess(
980 GetProcess()->GetHandle(), content::RESULT_CODE_KILLED, false);
984 void RenderViewHostImpl::GotFocus() {
985 RenderWidgetHostImpl::GotFocus(); // Notifies the renderer it got focus.
987 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
988 if (view)
989 view->GotFocus();
992 void RenderViewHostImpl::LostCapture() {
993 RenderWidgetHostImpl::LostCapture();
994 delegate_->LostCapture();
997 void RenderViewHostImpl::LostMouseLock() {
998 RenderWidgetHostImpl::LostMouseLock();
999 delegate_->LostMouseLock();
1002 void RenderViewHostImpl::SetInitialFocus(bool reverse) {
1003 Send(new ViewMsg_SetInitialFocus(GetRoutingID(), reverse));
1006 void RenderViewHostImpl::FilesSelectedInChooser(
1007 const std::vector<ui::SelectedFileInfo>& files,
1008 FileChooserParams::Mode permissions) {
1009 // Grant the security access requested to the given files.
1010 for (size_t i = 0; i < files.size(); ++i) {
1011 const ui::SelectedFileInfo& file = files[i];
1012 if (permissions == FileChooserParams::Save) {
1013 ChildProcessSecurityPolicyImpl::GetInstance()->GrantCreateReadWriteFile(
1014 GetProcess()->GetID(), file.local_path);
1015 } else {
1016 ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
1017 GetProcess()->GetID(), file.local_path);
1020 Send(new ViewMsg_RunFileChooserResponse(GetRoutingID(), files));
1023 void RenderViewHostImpl::DirectoryEnumerationFinished(
1024 int request_id,
1025 const std::vector<base::FilePath>& files) {
1026 // Grant the security access requested to the given files.
1027 for (std::vector<base::FilePath>::const_iterator file = files.begin();
1028 file != files.end(); ++file) {
1029 ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
1030 GetProcess()->GetID(), *file);
1032 Send(new ViewMsg_EnumerateDirectoryResponse(GetRoutingID(),
1033 request_id,
1034 files));
1037 void RenderViewHostImpl::LoadStateChanged(
1038 const GURL& url,
1039 const net::LoadStateWithParam& load_state,
1040 uint64 upload_position,
1041 uint64 upload_size) {
1042 delegate_->LoadStateChanged(url, load_state, upload_position, upload_size);
1045 bool RenderViewHostImpl::SuddenTerminationAllowed() const {
1046 return sudden_termination_allowed_ ||
1047 GetProcess()->SuddenTerminationAllowed();
1050 ///////////////////////////////////////////////////////////////////////////////
1051 // RenderViewHostImpl, IPC message handlers:
1053 bool RenderViewHostImpl::OnMessageReceived(const IPC::Message& msg) {
1054 if (!BrowserMessageFilter::CheckCanDispatchOnUI(msg, this))
1055 return true;
1057 // Filter out most IPC messages if this renderer is swapped out.
1058 // We still want to handle certain ACKs to keep our state consistent.
1059 if (IsSwappedOut()) {
1060 if (!SwappedOutMessages::CanHandleWhileSwappedOut(msg)) {
1061 // If this is a synchronous message and we decided not to handle it,
1062 // we must send an error reply, or else the renderer will be stuck
1063 // and won't respond to future requests.
1064 if (msg.is_sync()) {
1065 IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
1066 reply->set_reply_error();
1067 Send(reply);
1069 // Don't continue looking for someone to handle it.
1070 return true;
1074 if (delegate_->OnMessageReceived(this, msg))
1075 return true;
1077 bool handled = true;
1078 bool msg_is_ok = true;
1079 IPC_BEGIN_MESSAGE_MAP_EX(RenderViewHostImpl, msg, msg_is_ok)
1080 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowView, OnShowView)
1081 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowWidget, OnShowWidget)
1082 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowFullscreenWidget,
1083 OnShowFullscreenWidget)
1084 IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_RunModal, OnRunModal)
1085 IPC_MESSAGE_HANDLER(ViewHostMsg_RenderViewReady, OnRenderViewReady)
1086 IPC_MESSAGE_HANDLER(ViewHostMsg_RenderProcessGone, OnRenderProcessGone)
1087 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateState, OnUpdateState)
1088 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateTitle, OnUpdateTitle)
1089 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateEncoding, OnUpdateEncoding)
1090 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateTargetURL, OnUpdateTargetURL)
1091 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateInspectorSetting,
1092 OnUpdateInspectorSetting)
1093 IPC_MESSAGE_HANDLER(ViewHostMsg_Close, OnClose)
1094 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestMove, OnRequestMove)
1095 IPC_MESSAGE_HANDLER(ViewHostMsg_DidChangeLoadProgress,
1096 OnDidChangeLoadProgress)
1097 IPC_MESSAGE_HANDLER(ViewHostMsg_DidDisownOpener, OnDidDisownOpener)
1098 IPC_MESSAGE_HANDLER(ViewHostMsg_DocumentAvailableInMainFrame,
1099 OnDocumentAvailableInMainFrame)
1100 IPC_MESSAGE_HANDLER(ViewHostMsg_DocumentOnLoadCompletedInMainFrame,
1101 OnDocumentOnLoadCompletedInMainFrame)
1102 IPC_MESSAGE_HANDLER(ViewHostMsg_ToggleFullscreen, OnToggleFullscreen)
1103 IPC_MESSAGE_HANDLER(ViewHostMsg_DidContentsPreferredSizeChange,
1104 OnDidContentsPreferredSizeChange)
1105 IPC_MESSAGE_HANDLER(ViewHostMsg_DidChangeScrollOffset,
1106 OnDidChangeScrollOffset)
1107 IPC_MESSAGE_HANDLER(ViewHostMsg_DidChangeScrollbarsForMainFrame,
1108 OnDidChangeScrollbarsForMainFrame)
1109 IPC_MESSAGE_HANDLER(ViewHostMsg_DidChangeScrollOffsetPinningForMainFrame,
1110 OnDidChangeScrollOffsetPinningForMainFrame)
1111 IPC_MESSAGE_HANDLER(ViewHostMsg_DidChangeNumWheelEvents,
1112 OnDidChangeNumWheelEvents)
1113 IPC_MESSAGE_HANDLER(ViewHostMsg_RouteCloseEvent,
1114 OnRouteCloseEvent)
1115 IPC_MESSAGE_HANDLER(ViewHostMsg_RouteMessageEvent, OnRouteMessageEvent)
1116 IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_RunJavaScriptMessage,
1117 OnRunJavaScriptMessage)
1118 IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_RunBeforeUnloadConfirm,
1119 OnRunBeforeUnloadConfirm)
1120 IPC_MESSAGE_HANDLER(DragHostMsg_StartDragging, OnStartDragging)
1121 IPC_MESSAGE_HANDLER(DragHostMsg_UpdateDragCursor, OnUpdateDragCursor)
1122 IPC_MESSAGE_HANDLER(DragHostMsg_TargetDrop_ACK, OnTargetDropACK)
1123 IPC_MESSAGE_HANDLER(ViewHostMsg_TakeFocus, OnTakeFocus)
1124 IPC_MESSAGE_HANDLER(ViewHostMsg_FocusedNodeChanged, OnFocusedNodeChanged)
1125 IPC_MESSAGE_HANDLER(ViewHostMsg_AddMessageToConsole, OnAddMessageToConsole)
1126 IPC_MESSAGE_HANDLER(ViewHostMsg_ClosePage_ACK, OnClosePageACK)
1127 IPC_MESSAGE_HANDLER(ViewHostMsg_SwapOut_ACK, OnSwapOutACK)
1128 IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionChanged, OnSelectionChanged)
1129 IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionBoundsChanged,
1130 OnSelectionBoundsChanged)
1131 #if defined(OS_ANDROID)
1132 IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionRootBoundsChanged,
1133 OnSelectionRootBoundsChanged)
1134 #endif
1135 IPC_MESSAGE_HANDLER(ViewHostMsg_ScriptEvalResponse, OnScriptEvalResponse)
1136 IPC_MESSAGE_HANDLER(ViewHostMsg_DidZoomURL, OnDidZoomURL)
1137 IPC_MESSAGE_HANDLER(DesktopNotificationHostMsg_RequestPermission,
1138 OnRequestDesktopNotificationPermission)
1139 IPC_MESSAGE_HANDLER(DesktopNotificationHostMsg_Show,
1140 OnShowDesktopNotification)
1141 IPC_MESSAGE_HANDLER(DesktopNotificationHostMsg_Cancel,
1142 OnCancelDesktopNotification)
1143 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1144 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowPopup, OnShowPopup)
1145 #endif
1146 IPC_MESSAGE_HANDLER(ViewHostMsg_RunFileChooser, OnRunFileChooser)
1147 IPC_MESSAGE_HANDLER(ViewHostMsg_DidAccessInitialDocument,
1148 OnDidAccessInitialDocument)
1149 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_Events, OnAccessibilityEvents)
1150 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_LocationChanges,
1151 OnAccessibilityLocationChanges)
1152 IPC_MESSAGE_HANDLER(ViewHostMsg_FocusedNodeTouched, OnFocusedNodeTouched)
1153 // Have the super handle all other messages.
1154 IPC_MESSAGE_UNHANDLED(
1155 handled = RenderWidgetHostImpl::OnMessageReceived(msg))
1156 IPC_END_MESSAGE_MAP_EX()
1158 if (!msg_is_ok) {
1159 // The message had a handler, but its de-serialization failed.
1160 // Kill the renderer.
1161 RecordAction(base::UserMetricsAction("BadMessageTerminate_RVH"));
1162 GetProcess()->ReceivedBadMessage();
1165 return handled;
1168 void RenderViewHostImpl::Init() {
1169 RenderWidgetHostImpl::Init();
1172 void RenderViewHostImpl::Shutdown() {
1173 // If we are being run modally (see RunModal), then we need to cleanup.
1174 if (run_modal_reply_msg_) {
1175 Send(run_modal_reply_msg_);
1176 run_modal_reply_msg_ = NULL;
1177 RenderViewHostImpl* opener =
1178 RenderViewHostImpl::FromID(GetProcess()->GetID(), run_modal_opener_id_);
1179 if (opener) {
1180 opener->StartHangMonitorTimeout(TimeDelta::FromMilliseconds(
1181 hung_renderer_delay_ms_));
1182 // Balance out the decrement when we got created.
1183 opener->increment_in_flight_event_count();
1185 run_modal_opener_id_ = MSG_ROUTING_NONE;
1188 RenderWidgetHostImpl::Shutdown();
1191 bool RenderViewHostImpl::IsRenderView() const {
1192 return true;
1195 void RenderViewHostImpl::CreateNewWindow(
1196 int route_id,
1197 int main_frame_route_id,
1198 const ViewHostMsg_CreateWindow_Params& params,
1199 SessionStorageNamespace* session_storage_namespace) {
1200 ViewHostMsg_CreateWindow_Params validated_params(params);
1201 GetProcess()->FilterURL(false, &validated_params.target_url);
1202 GetProcess()->FilterURL(false, &validated_params.opener_url);
1203 GetProcess()->FilterURL(true, &validated_params.opener_security_origin);
1205 delegate_->CreateNewWindow(
1206 GetProcess()->GetID(), route_id, main_frame_route_id, validated_params,
1207 session_storage_namespace);
1210 void RenderViewHostImpl::CreateNewWidget(int route_id,
1211 blink::WebPopupType popup_type) {
1212 delegate_->CreateNewWidget(GetProcess()->GetID(), route_id, popup_type);
1215 void RenderViewHostImpl::CreateNewFullscreenWidget(int route_id) {
1216 delegate_->CreateNewFullscreenWidget(GetProcess()->GetID(), route_id);
1219 void RenderViewHostImpl::OnShowView(int route_id,
1220 WindowOpenDisposition disposition,
1221 const gfx::Rect& initial_pos,
1222 bool user_gesture) {
1223 if (IsRVHStateActive(rvh_state_)) {
1224 delegate_->ShowCreatedWindow(
1225 route_id, disposition, initial_pos, user_gesture);
1227 Send(new ViewMsg_Move_ACK(route_id));
1230 void RenderViewHostImpl::OnShowWidget(int route_id,
1231 const gfx::Rect& initial_pos) {
1232 if (IsRVHStateActive(rvh_state_))
1233 delegate_->ShowCreatedWidget(route_id, initial_pos);
1234 Send(new ViewMsg_Move_ACK(route_id));
1237 void RenderViewHostImpl::OnShowFullscreenWidget(int route_id) {
1238 if (IsRVHStateActive(rvh_state_))
1239 delegate_->ShowCreatedFullscreenWidget(route_id);
1240 Send(new ViewMsg_Move_ACK(route_id));
1243 void RenderViewHostImpl::OnRunModal(int opener_id, IPC::Message* reply_msg) {
1244 DCHECK(!run_modal_reply_msg_);
1245 run_modal_reply_msg_ = reply_msg;
1246 run_modal_opener_id_ = opener_id;
1248 RecordAction(base::UserMetricsAction("ShowModalDialog"));
1250 RenderViewHostImpl* opener =
1251 RenderViewHostImpl::FromID(GetProcess()->GetID(), run_modal_opener_id_);
1252 if (opener) {
1253 opener->StopHangMonitorTimeout();
1254 // The ack for the mouse down won't come until the dialog closes, so fake it
1255 // so that we don't get a timeout.
1256 opener->decrement_in_flight_event_count();
1259 // TODO(darin): Bug 1107929: Need to inform our delegate to show this view in
1260 // an app-modal fashion.
1263 void RenderViewHostImpl::OnRenderViewReady() {
1264 render_view_termination_status_ = base::TERMINATION_STATUS_STILL_RUNNING;
1265 SendScreenRects();
1266 WasResized();
1267 delegate_->RenderViewReady(this);
1270 void RenderViewHostImpl::OnRenderProcessGone(int status, int exit_code) {
1271 // Keep the termination status so we can get at it later when we
1272 // need to know why it died.
1273 render_view_termination_status_ =
1274 static_cast<base::TerminationStatus>(status);
1276 // Reset frame tree state associated with this process.
1277 delegate_->GetFrameTree()->RenderProcessGone(this);
1279 // Our base class RenderWidgetHost needs to reset some stuff.
1280 RendererExited(render_view_termination_status_, exit_code);
1282 delegate_->RenderViewTerminated(this,
1283 static_cast<base::TerminationStatus>(status),
1284 exit_code);
1287 void RenderViewHostImpl::OnUpdateState(int32 page_id, const PageState& state) {
1288 // Without this check, the renderer can trick the browser into using
1289 // filenames it can't access in a future session restore.
1290 if (!CanAccessFilesOfPageState(state)) {
1291 GetProcess()->ReceivedBadMessage();
1292 return;
1295 delegate_->UpdateState(this, page_id, state);
1298 void RenderViewHostImpl::OnUpdateTitle(
1299 int32 page_id,
1300 const base::string16& title,
1301 blink::WebTextDirection title_direction) {
1302 if (title.length() > kMaxTitleChars) {
1303 NOTREACHED() << "Renderer sent too many characters in title.";
1304 return;
1307 delegate_->UpdateTitle(this, page_id, title,
1308 WebTextDirectionToChromeTextDirection(
1309 title_direction));
1312 void RenderViewHostImpl::OnUpdateEncoding(const std::string& encoding_name) {
1313 delegate_->UpdateEncoding(this, encoding_name);
1316 void RenderViewHostImpl::OnUpdateTargetURL(int32 page_id, const GURL& url) {
1317 if (IsRVHStateActive(rvh_state_))
1318 delegate_->UpdateTargetURL(page_id, url);
1320 // Send a notification back to the renderer that we are ready to
1321 // receive more target urls.
1322 Send(new ViewMsg_UpdateTargetURL_ACK(GetRoutingID()));
1325 void RenderViewHostImpl::OnUpdateInspectorSetting(
1326 const std::string& key, const std::string& value) {
1327 GetContentClient()->browser()->UpdateInspectorSetting(
1328 this, key, value);
1331 void RenderViewHostImpl::OnClose() {
1332 // If the renderer is telling us to close, it has already run the unload
1333 // events, and we can take the fast path.
1334 ClosePageIgnoringUnloadEvents();
1337 void RenderViewHostImpl::OnRequestMove(const gfx::Rect& pos) {
1338 if (IsRVHStateActive(rvh_state_))
1339 delegate_->RequestMove(pos);
1340 Send(new ViewMsg_Move_ACK(GetRoutingID()));
1343 void RenderViewHostImpl::OnDidChangeLoadProgress(double load_progress) {
1344 delegate_->DidChangeLoadProgress(load_progress);
1347 void RenderViewHostImpl::OnDidDisownOpener() {
1348 delegate_->DidDisownOpener(this);
1351 void RenderViewHostImpl::OnDocumentAvailableInMainFrame() {
1352 delegate_->DocumentAvailableInMainFrame(this);
1355 void RenderViewHostImpl::OnDocumentOnLoadCompletedInMainFrame(
1356 int32 page_id) {
1357 delegate_->DocumentOnLoadCompletedInMainFrame(this, page_id);
1360 void RenderViewHostImpl::OnToggleFullscreen(bool enter_fullscreen) {
1361 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1362 delegate_->ToggleFullscreenMode(enter_fullscreen);
1363 // We need to notify the contents that its fullscreen state has changed. This
1364 // is done as part of the resize message.
1365 WasResized();
1368 void RenderViewHostImpl::OnDidContentsPreferredSizeChange(
1369 const gfx::Size& new_size) {
1370 delegate_->UpdatePreferredSize(new_size);
1373 void RenderViewHostImpl::OnRenderAutoResized(const gfx::Size& new_size) {
1374 delegate_->ResizeDueToAutoResize(new_size);
1377 void RenderViewHostImpl::OnDidChangeScrollOffset() {
1378 if (view_)
1379 view_->ScrollOffsetChanged();
1382 void RenderViewHostImpl::OnDidChangeScrollbarsForMainFrame(
1383 bool has_horizontal_scrollbar, bool has_vertical_scrollbar) {
1384 if (view_)
1385 view_->SetHasHorizontalScrollbar(has_horizontal_scrollbar);
1388 void RenderViewHostImpl::OnDidChangeScrollOffsetPinningForMainFrame(
1389 bool is_pinned_to_left, bool is_pinned_to_right) {
1390 if (view_)
1391 view_->SetScrollOffsetPinning(is_pinned_to_left, is_pinned_to_right);
1394 void RenderViewHostImpl::OnDidChangeNumWheelEvents(int count) {
1397 void RenderViewHostImpl::OnSelectionChanged(const base::string16& text,
1398 size_t offset,
1399 const gfx::Range& range) {
1400 if (view_)
1401 view_->SelectionChanged(text, offset, range);
1404 void RenderViewHostImpl::OnSelectionBoundsChanged(
1405 const ViewHostMsg_SelectionBounds_Params& params) {
1406 if (view_) {
1407 view_->SelectionBoundsChanged(params);
1411 #if defined(OS_ANDROID)
1412 void RenderViewHostImpl::OnSelectionRootBoundsChanged(
1413 const gfx::Rect& bounds) {
1414 if (view_) {
1415 view_->SelectionRootBoundsChanged(bounds);
1418 #endif
1420 void RenderViewHostImpl::OnRouteCloseEvent() {
1421 // Have the delegate route this to the active RenderViewHost.
1422 delegate_->RouteCloseEvent(this);
1425 void RenderViewHostImpl::OnRouteMessageEvent(
1426 const ViewMsg_PostMessage_Params& params) {
1427 // Give to the delegate to route to the active RenderViewHost.
1428 delegate_->RouteMessageEvent(this, params);
1431 void RenderViewHostImpl::OnRunJavaScriptMessage(
1432 const base::string16& message,
1433 const base::string16& default_prompt,
1434 const GURL& frame_url,
1435 JavaScriptMessageType type,
1436 IPC::Message* reply_msg) {
1437 // While a JS message dialog is showing, tabs in the same process shouldn't
1438 // process input events.
1439 GetProcess()->SetIgnoreInputEvents(true);
1440 StopHangMonitorTimeout();
1441 delegate_->RunJavaScriptMessage(this, message, default_prompt, frame_url,
1442 type, reply_msg,
1443 &are_javascript_messages_suppressed_);
1446 void RenderViewHostImpl::OnRunBeforeUnloadConfirm(const GURL& frame_url,
1447 const base::string16& message,
1448 bool is_reload,
1449 IPC::Message* reply_msg) {
1450 // While a JS before unload dialog is showing, tabs in the same process
1451 // shouldn't process input events.
1452 GetProcess()->SetIgnoreInputEvents(true);
1453 StopHangMonitorTimeout();
1454 delegate_->RunBeforeUnloadConfirm(this, message, is_reload, reply_msg);
1457 void RenderViewHostImpl::OnStartDragging(
1458 const DropData& drop_data,
1459 WebDragOperationsMask drag_operations_mask,
1460 const SkBitmap& bitmap,
1461 const gfx::Vector2d& bitmap_offset_in_dip,
1462 const DragEventSourceInfo& event_info) {
1463 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1464 if (!view)
1465 return;
1467 DropData filtered_data(drop_data);
1468 RenderProcessHost* process = GetProcess();
1469 ChildProcessSecurityPolicyImpl* policy =
1470 ChildProcessSecurityPolicyImpl::GetInstance();
1472 // Allow drag of Javascript URLs to enable bookmarklet drag to bookmark bar.
1473 if (!filtered_data.url.SchemeIs(kJavaScriptScheme))
1474 process->FilterURL(true, &filtered_data.url);
1475 process->FilterURL(false, &filtered_data.html_base_url);
1476 // Filter out any paths that the renderer didn't have access to. This prevents
1477 // the following attack on a malicious renderer:
1478 // 1. StartDragging IPC sent with renderer-specified filesystem paths that it
1479 // doesn't have read permissions for.
1480 // 2. We initiate a native DnD operation.
1481 // 3. DnD operation immediately ends since mouse is not held down. DnD events
1482 // still fire though, which causes read permissions to be granted to the
1483 // renderer for any file paths in the drop.
1484 filtered_data.filenames.clear();
1485 for (std::vector<DropData::FileInfo>::const_iterator it =
1486 drop_data.filenames.begin();
1487 it != drop_data.filenames.end(); ++it) {
1488 base::FilePath path(
1489 base::FilePath::FromUTF8Unsafe(base::UTF16ToUTF8(it->path)));
1490 if (policy->CanReadFile(GetProcess()->GetID(), path))
1491 filtered_data.filenames.push_back(*it);
1493 float scale = ui::GetImageScale(GetScaleFactorForView(GetView()));
1494 gfx::ImageSkia image(gfx::ImageSkiaRep(bitmap, scale));
1495 view->StartDragging(filtered_data, drag_operations_mask, image,
1496 bitmap_offset_in_dip, event_info);
1499 void RenderViewHostImpl::OnUpdateDragCursor(WebDragOperation current_op) {
1500 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1501 if (view)
1502 view->UpdateDragCursor(current_op);
1505 void RenderViewHostImpl::OnTargetDropACK() {
1506 NotificationService::current()->Notify(
1507 NOTIFICATION_RENDER_VIEW_HOST_DID_RECEIVE_DRAG_TARGET_DROP_ACK,
1508 Source<RenderViewHost>(this),
1509 NotificationService::NoDetails());
1512 void RenderViewHostImpl::OnTakeFocus(bool reverse) {
1513 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1514 if (view)
1515 view->TakeFocus(reverse);
1518 void RenderViewHostImpl::OnFocusedNodeChanged(bool is_editable_node) {
1519 if (view_)
1520 view_->FocusedNodeChanged(is_editable_node);
1521 #if defined(OS_WIN)
1522 if (!is_editable_node && virtual_keyboard_requested_) {
1523 virtual_keyboard_requested_ = false;
1524 BrowserThread::PostDelayedTask(
1525 BrowserThread::UI, FROM_HERE,
1526 base::Bind(base::IgnoreResult(&DismissVirtualKeyboardTask)),
1527 TimeDelta::FromMilliseconds(kVirtualKeyboardDisplayWaitTimeoutMs));
1529 #endif
1530 NotificationService::current()->Notify(
1531 NOTIFICATION_FOCUS_CHANGED_IN_PAGE,
1532 Source<RenderViewHost>(this),
1533 Details<const bool>(&is_editable_node));
1536 void RenderViewHostImpl::OnAddMessageToConsole(
1537 int32 level,
1538 const base::string16& message,
1539 int32 line_no,
1540 const base::string16& source_id) {
1541 if (delegate_->AddMessageToConsole(level, message, line_no, source_id))
1542 return;
1544 // Pass through log level only on WebUI pages to limit console spew.
1545 int32 resolved_level = HasWebUIScheme(delegate_->GetURL()) ? level : 0;
1547 if (resolved_level >= ::logging::GetMinLogLevel()) {
1548 logging::LogMessage("CONSOLE", line_no, resolved_level).stream() << "\"" <<
1549 message << "\", source: " << source_id << " (" << line_no << ")";
1553 void RenderViewHostImpl::OnUserGesture() {
1554 delegate_->OnUserGesture();
1557 void RenderViewHostImpl::OnClosePageACK() {
1558 decrement_in_flight_event_count();
1559 ClosePageIgnoringUnloadEvents();
1562 void RenderViewHostImpl::NotifyRendererUnresponsive() {
1563 delegate_->RendererUnresponsive(
1564 this, is_waiting_for_beforeunload_ack_, IsWaitingForUnloadACK());
1567 void RenderViewHostImpl::NotifyRendererResponsive() {
1568 delegate_->RendererResponsive(this);
1571 void RenderViewHostImpl::RequestToLockMouse(bool user_gesture,
1572 bool last_unlocked_by_target) {
1573 delegate_->RequestToLockMouse(user_gesture, last_unlocked_by_target);
1576 bool RenderViewHostImpl::IsFullscreen() const {
1577 return delegate_->IsFullscreenForCurrentTab();
1580 void RenderViewHostImpl::OnFocus() {
1581 // Note: We allow focus and blur from swapped out RenderViewHosts, even when
1582 // the active RenderViewHost is in a different BrowsingInstance (e.g., WebUI).
1583 delegate_->Activate();
1586 void RenderViewHostImpl::OnBlur() {
1587 delegate_->Deactivate();
1590 gfx::Rect RenderViewHostImpl::GetRootWindowResizerRect() const {
1591 return delegate_->GetRootWindowResizerRect();
1594 void RenderViewHostImpl::ForwardMouseEvent(
1595 const blink::WebMouseEvent& mouse_event) {
1597 // We make a copy of the mouse event because
1598 // RenderWidgetHost::ForwardMouseEvent will delete |mouse_event|.
1599 blink::WebMouseEvent event_copy(mouse_event);
1600 RenderWidgetHostImpl::ForwardMouseEvent(event_copy);
1602 switch (event_copy.type) {
1603 case WebInputEvent::MouseMove:
1604 delegate_->HandleMouseMove();
1605 break;
1606 case WebInputEvent::MouseLeave:
1607 delegate_->HandleMouseLeave();
1608 break;
1609 case WebInputEvent::MouseDown:
1610 delegate_->HandleMouseDown();
1611 break;
1612 case WebInputEvent::MouseWheel:
1613 if (ignore_input_events())
1614 delegate_->OnIgnoredUIEvent();
1615 break;
1616 case WebInputEvent::MouseUp:
1617 delegate_->HandleMouseUp();
1618 default:
1619 // For now, we don't care about the rest.
1620 break;
1624 void RenderViewHostImpl::OnPointerEventActivate() {
1625 delegate_->HandlePointerActivate();
1628 void RenderViewHostImpl::ForwardKeyboardEvent(
1629 const NativeWebKeyboardEvent& key_event) {
1630 if (ignore_input_events()) {
1631 if (key_event.type == WebInputEvent::RawKeyDown)
1632 delegate_->OnIgnoredUIEvent();
1633 return;
1635 RenderWidgetHostImpl::ForwardKeyboardEvent(key_event);
1638 #if defined(OS_ANDROID)
1639 void RenderViewHostImpl::DidSelectPopupMenuItems(
1640 const std::vector<int>& selected_indices) {
1641 Send(new ViewMsg_SelectPopupMenuItems(GetRoutingID(), false,
1642 selected_indices));
1645 void RenderViewHostImpl::DidCancelPopupMenu() {
1646 Send(new ViewMsg_SelectPopupMenuItems(GetRoutingID(), true,
1647 std::vector<int>()));
1649 #endif
1651 #if defined(OS_MACOSX)
1652 void RenderViewHostImpl::DidSelectPopupMenuItem(int selected_index) {
1653 Send(new ViewMsg_SelectPopupMenuItem(GetRoutingID(), selected_index));
1656 void RenderViewHostImpl::DidCancelPopupMenu() {
1657 Send(new ViewMsg_SelectPopupMenuItem(GetRoutingID(), -1));
1659 #endif
1661 void RenderViewHostImpl::SendOrientationChangeEvent(int orientation) {
1662 Send(new ViewMsg_OrientationChangeEvent(GetRoutingID(), orientation));
1665 void RenderViewHostImpl::ToggleSpeechInput() {
1666 Send(new InputTagSpeechMsg_ToggleSpeechInput(GetRoutingID()));
1669 bool RenderViewHostImpl::IsWaitingForUnloadACK() const {
1670 return rvh_state_ == STATE_WAITING_FOR_UNLOAD_ACK ||
1671 rvh_state_ == STATE_WAITING_FOR_CLOSE ||
1672 rvh_state_ == STATE_PENDING_SHUTDOWN ||
1673 rvh_state_ == STATE_PENDING_SWAP_OUT;
1676 void RenderViewHostImpl::ExitFullscreen() {
1677 RejectMouseLockOrUnlockIfNecessary();
1678 // Notify delegate_ and renderer of fullscreen state change.
1679 OnToggleFullscreen(false);
1682 WebPreferences RenderViewHostImpl::GetWebkitPreferences() {
1683 return delegate_->GetWebkitPrefs();
1686 void RenderViewHostImpl::DisownOpener() {
1687 // This should only be called when swapped out.
1688 DCHECK(IsSwappedOut());
1690 Send(new ViewMsg_DisownOpener(GetRoutingID()));
1693 void RenderViewHostImpl::SetAccessibilityCallbackForTesting(
1694 const base::Callback<void(ui::AXEvent)>& callback) {
1695 accessibility_testing_callback_ = callback;
1698 void RenderViewHostImpl::UpdateWebkitPreferences(const WebPreferences& prefs) {
1699 Send(new ViewMsg_UpdateWebPreferences(GetRoutingID(), prefs));
1702 void RenderViewHostImpl::GetAudioOutputControllers(
1703 const GetAudioOutputControllersCallback& callback) const {
1704 AudioRendererHost* audio_host =
1705 static_cast<RenderProcessHostImpl*>(GetProcess())->audio_renderer_host();
1706 audio_host->GetOutputControllers(GetRoutingID(), callback);
1709 void RenderViewHostImpl::ClearFocusedElement() {
1710 Send(new ViewMsg_ClearFocusedElement(GetRoutingID()));
1713 void RenderViewHostImpl::Zoom(PageZoom zoom) {
1714 Send(new ViewMsg_Zoom(GetRoutingID(), zoom));
1717 void RenderViewHostImpl::ReloadFrame() {
1718 Send(new ViewMsg_ReloadFrame(GetRoutingID()));
1721 void RenderViewHostImpl::DisableScrollbarsForThreshold(const gfx::Size& size) {
1722 Send(new ViewMsg_DisableScrollbarsForSmallWindows(GetRoutingID(), size));
1725 void RenderViewHostImpl::EnablePreferredSizeMode() {
1726 Send(new ViewMsg_EnablePreferredSizeChangedMode(GetRoutingID()));
1729 void RenderViewHostImpl::EnableAutoResize(const gfx::Size& min_size,
1730 const gfx::Size& max_size) {
1731 SetShouldAutoResize(true);
1732 Send(new ViewMsg_EnableAutoResize(GetRoutingID(), min_size, max_size));
1735 void RenderViewHostImpl::DisableAutoResize(const gfx::Size& new_size) {
1736 SetShouldAutoResize(false);
1737 Send(new ViewMsg_DisableAutoResize(GetRoutingID(), new_size));
1740 void RenderViewHostImpl::CopyImageAt(int x, int y) {
1741 Send(new ViewMsg_CopyImageAt(GetRoutingID(), x, y));
1744 void RenderViewHostImpl::ExecuteMediaPlayerActionAtLocation(
1745 const gfx::Point& location, const blink::WebMediaPlayerAction& action) {
1746 Send(new ViewMsg_MediaPlayerActionAt(GetRoutingID(), location, action));
1749 void RenderViewHostImpl::ExecutePluginActionAtLocation(
1750 const gfx::Point& location, const blink::WebPluginAction& action) {
1751 Send(new ViewMsg_PluginActionAt(GetRoutingID(), location, action));
1754 void RenderViewHostImpl::NotifyMoveOrResizeStarted() {
1755 Send(new ViewMsg_MoveOrResizeStarted(GetRoutingID()));
1758 void RenderViewHostImpl::OnAccessibilityEvents(
1759 const std::vector<AccessibilityHostMsg_EventParams>& params) {
1760 if ((accessibility_mode() & AccessibilityModeFlagPlatform) && view_ &&
1761 IsRVHStateActive(rvh_state_)) {
1762 view_->CreateBrowserAccessibilityManagerIfNeeded();
1763 BrowserAccessibilityManager* manager =
1764 view_->GetBrowserAccessibilityManager();
1765 if (manager)
1766 manager->OnAccessibilityEvents(params);
1768 // TODO(aboxhall, dtseng): Only send notification when accessibility mode
1769 // extension enabled.
1770 std::vector<AXEventNotificationDetails> details;
1771 for (unsigned int i = 0; i < params.size(); ++i) {
1772 const AccessibilityHostMsg_EventParams& param = params[i];
1773 AXEventNotificationDetails detail(
1774 param.nodes, param.event_type, param.id, GetRoutingID());
1775 details.push_back(detail);
1778 delegate_->AccessibilityEventReceived(details);
1781 // Always send an ACK or the renderer can be in a bad state.
1782 Send(new AccessibilityMsg_Events_ACK(GetRoutingID()));
1784 // The rest of this code is just for testing; bail out if we're not
1785 // in that mode.
1786 if (accessibility_testing_callback_.is_null())
1787 return;
1789 for (unsigned i = 0; i < params.size(); i++) {
1790 const AccessibilityHostMsg_EventParams& param = params[i];
1791 if (static_cast<int>(param.event_type) < 0)
1792 continue;
1793 ui::AXTreeUpdate update;
1794 update.nodes = param.nodes;
1795 if (!ax_tree_)
1796 ax_tree_.reset(new ui::AXTree(update));
1797 else
1798 CHECK(ax_tree_->Unserialize(update)) << ax_tree_->error();
1799 accessibility_testing_callback_.Run(param.event_type);
1803 void RenderViewHostImpl::OnAccessibilityLocationChanges(
1804 const std::vector<AccessibilityHostMsg_LocationChangeParams>& params) {
1805 if (view_ && IsRVHStateActive(rvh_state_)) {
1806 view_->CreateBrowserAccessibilityManagerIfNeeded();
1807 BrowserAccessibilityManager* manager =
1808 view_->GetBrowserAccessibilityManager();
1809 if (manager)
1810 manager->OnLocationChanges(params);
1814 void RenderViewHostImpl::OnScriptEvalResponse(int id,
1815 const base::ListValue& result) {
1816 const base::Value* result_value;
1817 if (!result.Get(0, &result_value)) {
1818 // Programming error or rogue renderer.
1819 NOTREACHED() << "Got bad arguments for OnScriptEvalResponse";
1820 return;
1823 std::map<int, JavascriptResultCallback>::iterator it =
1824 javascript_callbacks_.find(id);
1825 if (it != javascript_callbacks_.end()) {
1826 // ExecuteJavascriptInWebFrameCallbackResult was used; do callback.
1827 it->second.Run(result_value);
1828 javascript_callbacks_.erase(it);
1829 } else {
1830 NOTREACHED() << "Received script response for unknown request";
1834 void RenderViewHostImpl::OnDidZoomURL(double zoom_level,
1835 bool remember,
1836 const GURL& url) {
1837 HostZoomMapImpl* host_zoom_map = static_cast<HostZoomMapImpl*>(
1838 HostZoomMap::GetForBrowserContext(GetProcess()->GetBrowserContext()));
1839 if (remember) {
1840 host_zoom_map->
1841 SetZoomLevelForHost(net::GetHostOrSpecFromURL(url), zoom_level);
1842 } else {
1843 host_zoom_map->SetTemporaryZoomLevel(
1844 GetProcess()->GetID(), GetRoutingID(), zoom_level);
1848 void RenderViewHostImpl::OnRequestDesktopNotificationPermission(
1849 const GURL& source_origin, int callback_context) {
1850 GetContentClient()->browser()->RequestDesktopNotificationPermission(
1851 source_origin, callback_context, GetProcess()->GetID(), GetRoutingID());
1854 void RenderViewHostImpl::OnShowDesktopNotification(
1855 const ShowDesktopNotificationHostMsgParams& params) {
1856 GetContentClient()->browser()->ShowDesktopNotification(
1857 params, GetProcess()->GetID(), GetRoutingID(), false);
1860 void RenderViewHostImpl::OnCancelDesktopNotification(int notification_id) {
1861 GetContentClient()->browser()->CancelDesktopNotification(
1862 GetProcess()->GetID(), GetRoutingID(), notification_id);
1865 void RenderViewHostImpl::OnRunFileChooser(const FileChooserParams& params) {
1866 delegate_->RunFileChooser(this, params);
1869 void RenderViewHostImpl::OnDidAccessInitialDocument() {
1870 has_accessed_initial_document_ = true;
1871 delegate_->DidAccessInitialDocument();
1874 void RenderViewHostImpl::OnFocusedNodeTouched(bool editable) {
1875 #if defined(OS_WIN)
1876 if (editable) {
1877 virtual_keyboard_requested_ = base::win::DisplayVirtualKeyboard();
1878 } else {
1879 virtual_keyboard_requested_ = false;
1880 base::win::DismissVirtualKeyboard();
1882 #endif
1885 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1886 void RenderViewHostImpl::OnShowPopup(
1887 const ViewHostMsg_ShowPopup_Params& params) {
1888 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1889 if (view) {
1890 view->ShowPopupMenu(params.bounds,
1891 params.item_height,
1892 params.item_font_size,
1893 params.selected_item,
1894 params.popup_items,
1895 params.right_aligned,
1896 params.allow_multiple_selection);
1899 #endif
1901 void RenderViewHostImpl::SetState(RenderViewHostImplState rvh_state) {
1902 // We update the number of RenderViews in a SiteInstance when the
1903 // swapped out status of this RenderView gets flipped to/from live.
1904 if (!IsRVHStateActive(rvh_state_) && IsRVHStateActive(rvh_state))
1905 instance_->increment_active_view_count();
1906 else if (IsRVHStateActive(rvh_state_) && !IsRVHStateActive(rvh_state))
1907 instance_->decrement_active_view_count();
1909 // Whenever we change the RVH state to and from live or swapped out state, we
1910 // should not be waiting for beforeunload or unload acks. We clear them here
1911 // to be safe, since they can cause navigations to be ignored in OnNavigate.
1912 if (rvh_state == STATE_DEFAULT ||
1913 rvh_state == STATE_SWAPPED_OUT ||
1914 rvh_state_ == STATE_DEFAULT ||
1915 rvh_state_ == STATE_SWAPPED_OUT) {
1916 is_waiting_for_beforeunload_ack_ = false;
1918 rvh_state_ = rvh_state;
1922 bool RenderViewHostImpl::CanAccessFilesOfPageState(
1923 const PageState& state) const {
1924 ChildProcessSecurityPolicyImpl* policy =
1925 ChildProcessSecurityPolicyImpl::GetInstance();
1927 const std::vector<base::FilePath>& file_paths = state.GetReferencedFiles();
1928 for (std::vector<base::FilePath>::const_iterator file = file_paths.begin();
1929 file != file_paths.end(); ++file) {
1930 if (!policy->CanReadFile(GetProcess()->GetID(), *file))
1931 return false;
1933 return true;
1936 void RenderViewHostImpl::AttachToFrameTree() {
1937 FrameTree* frame_tree = delegate_->GetFrameTree();
1939 frame_tree->ResetForMainFrameSwap();
1942 } // namespace content