[blink-in-js] Migrate resources required for blink-in-js to grd - part 2
[chromium-blink-merge.git] / content / browser / renderer_host / render_view_host_impl.cc
blob8ba826a4cd693ac9ecddcb0ff5a26b4d6120c7e3
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/crash_logging.h"
15 #include "base/debug/trace_event.h"
16 #include "base/i18n/rtl.h"
17 #include "base/json/json_reader.h"
18 #include "base/message_loop/message_loop.h"
19 #include "base/metrics/histogram.h"
20 #include "base/stl_util.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "base/strings/string_util.h"
23 #include "base/strings/utf_string_conversions.h"
24 #include "base/sys_info.h"
25 #include "base/time/time.h"
26 #include "base/values.h"
27 #include "cc/base/switches.h"
28 #include "content/browser/child_process_security_policy_impl.h"
29 #include "content/browser/dom_storage/session_storage_namespace_impl.h"
30 #include "content/browser/frame_host/frame_tree.h"
31 #include "content/browser/gpu/compositor_util.h"
32 #include "content/browser/gpu/gpu_data_manager_impl.h"
33 #include "content/browser/gpu/gpu_process_host.h"
34 #include "content/browser/gpu/gpu_surface_tracker.h"
35 #include "content/browser/host_zoom_map_impl.h"
36 #include "content/browser/loader/resource_dispatcher_host_impl.h"
37 #include "content/browser/renderer_host/dip_util.h"
38 #include "content/browser/renderer_host/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/browser/renderer_host/render_view_host_delegate_view.h"
43 #include "content/browser/renderer_host/render_widget_host_view_base.h"
44 #include "content/common/browser_plugin/browser_plugin_messages.h"
45 #include "content/common/content_switches_internal.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/public/browser/ax_event_notification_details.h"
54 #include "content/public/browser/browser_accessibility_state.h"
55 #include "content/public/browser/browser_context.h"
56 #include "content/public/browser/browser_message_filter.h"
57 #include "content/public/browser/content_browser_client.h"
58 #include "content/public/browser/native_web_keyboard_event.h"
59 #include "content/public/browser/notification_details.h"
60 #include "content/public/browser/notification_service.h"
61 #include "content/public/browser/notification_types.h"
62 #include "content/public/browser/render_frame_host.h"
63 #include "content/public/browser/render_widget_host_iterator.h"
64 #include "content/public/browser/storage_partition.h"
65 #include "content/public/browser/user_metrics.h"
66 #include "content/public/common/bindings_policy.h"
67 #include "content/public/common/content_constants.h"
68 #include "content/public/common/content_switches.h"
69 #include "content/public/common/context_menu_params.h"
70 #include "content/public/common/drop_data.h"
71 #include "content/public/common/result_codes.h"
72 #include "content/public/common/url_utils.h"
73 #include "net/base/filename_util.h"
74 #include "net/base/net_util.h"
75 #include "net/base/network_change_notifier.h"
76 #include "net/url_request/url_request_context_getter.h"
77 #include "third_party/skia/include/core/SkBitmap.h"
78 #include "ui/base/touch/touch_device.h"
79 #include "ui/base/touch/touch_enabled.h"
80 #include "ui/base/ui_base_switches.h"
81 #include "ui/gfx/image/image_skia.h"
82 #include "ui/gfx/native_widget_types.h"
83 #include "ui/native_theme/native_theme_switches.h"
84 #include "ui/shell_dialogs/selected_file_info.h"
85 #include "url/url_constants.h"
86 #include "webkit/browser/fileapi/isolated_context.h"
88 #if defined(OS_WIN)
89 #include "base/win/win_util.h"
90 #endif
92 #if defined(ENABLE_BROWSER_CDMS)
93 #include "content/browser/media/media_web_contents_observer.h"
94 #endif
96 using base::TimeDelta;
97 using blink::WebConsoleMessage;
98 using blink::WebDragOperation;
99 using blink::WebDragOperationNone;
100 using blink::WebDragOperationsMask;
101 using blink::WebInputEvent;
102 using blink::WebMediaPlayerAction;
103 using blink::WebPluginAction;
105 namespace content {
106 namespace {
108 #if defined(OS_WIN)
110 const int kVirtualKeyboardDisplayWaitTimeoutMs = 100;
111 const int kMaxVirtualKeyboardDisplayRetries = 5;
113 void DismissVirtualKeyboardTask() {
114 static int virtual_keyboard_display_retries = 0;
115 // If the virtual keyboard is not yet visible, then we execute the task again
116 // waiting for it to show up.
117 if (!base::win::DismissVirtualKeyboard()) {
118 if (virtual_keyboard_display_retries < kMaxVirtualKeyboardDisplayRetries) {
119 BrowserThread::PostDelayedTask(
120 BrowserThread::UI, FROM_HERE,
121 base::Bind(base::IgnoreResult(&DismissVirtualKeyboardTask)),
122 TimeDelta::FromMilliseconds(kVirtualKeyboardDisplayWaitTimeoutMs));
123 ++virtual_keyboard_display_retries;
124 } else {
125 virtual_keyboard_display_retries = 0;
129 #endif
131 } // namespace
133 // static
134 const int RenderViewHostImpl::kUnloadTimeoutMS = 1000;
136 ///////////////////////////////////////////////////////////////////////////////
137 // RenderViewHost, public:
139 // static
140 bool RenderViewHostImpl::IsRVHStateActive(RenderViewHostImplState rvh_state) {
141 if (rvh_state == STATE_DEFAULT ||
142 rvh_state == STATE_WAITING_FOR_CLOSE)
143 return true;
144 return false;
147 // static
148 RenderViewHost* RenderViewHost::FromID(int render_process_id,
149 int render_view_id) {
150 return RenderViewHostImpl::FromID(render_process_id, render_view_id);
153 // static
154 RenderViewHost* RenderViewHost::From(RenderWidgetHost* rwh) {
155 DCHECK(rwh->IsRenderView());
156 return static_cast<RenderViewHostImpl*>(RenderWidgetHostImpl::From(rwh));
159 ///////////////////////////////////////////////////////////////////////////////
160 // RenderViewHostImpl, public:
162 // static
163 RenderViewHostImpl* RenderViewHostImpl::FromID(int render_process_id,
164 int render_view_id) {
165 RenderWidgetHost* widget =
166 RenderWidgetHost::FromID(render_process_id, render_view_id);
167 if (!widget || !widget->IsRenderView())
168 return NULL;
169 return static_cast<RenderViewHostImpl*>(RenderWidgetHostImpl::From(widget));
172 RenderViewHostImpl::RenderViewHostImpl(
173 SiteInstance* instance,
174 RenderViewHostDelegate* delegate,
175 RenderWidgetHostDelegate* widget_delegate,
176 int routing_id,
177 int main_frame_routing_id,
178 bool swapped_out,
179 bool hidden)
180 : RenderWidgetHostImpl(widget_delegate,
181 instance->GetProcess(),
182 routing_id,
183 hidden),
184 frames_ref_count_(0),
185 delegate_(delegate),
186 instance_(static_cast<SiteInstanceImpl*>(instance)),
187 waiting_for_drag_context_response_(false),
188 enabled_bindings_(0),
189 page_id_(-1),
190 main_frame_routing_id_(main_frame_routing_id),
191 run_modal_reply_msg_(NULL),
192 run_modal_opener_id_(MSG_ROUTING_NONE),
193 is_waiting_for_beforeunload_ack_(false),
194 unload_ack_is_for_cross_site_transition_(false),
195 sudden_termination_allowed_(false),
196 render_view_termination_status_(base::TERMINATION_STATUS_STILL_RUNNING),
197 virtual_keyboard_requested_(false),
198 weak_factory_(this),
199 is_focused_element_editable_(false),
200 updating_web_preferences_(false) {
201 DCHECK(instance_.get());
202 CHECK(delegate_); // http://crbug.com/82827
204 GetProcess()->EnableSendQueue();
206 if (swapped_out) {
207 rvh_state_ = STATE_SWAPPED_OUT;
208 } else {
209 rvh_state_ = STATE_DEFAULT;
210 instance_->increment_active_view_count();
213 if (ResourceDispatcherHostImpl::Get()) {
214 BrowserThread::PostTask(
215 BrowserThread::IO, FROM_HERE,
216 base::Bind(&ResourceDispatcherHostImpl::OnRenderViewHostCreated,
217 base::Unretained(ResourceDispatcherHostImpl::Get()),
218 GetProcess()->GetID(), GetRoutingID(), !is_hidden()));
221 #if defined(ENABLE_BROWSER_CDMS)
222 media_web_contents_observer_.reset(new MediaWebContentsObserver(this));
223 #endif
225 unload_event_monitor_timeout_.reset(new TimeoutMonitor(base::Bind(
226 &RenderViewHostImpl::OnSwappedOut, weak_factory_.GetWeakPtr(), true)));
229 RenderViewHostImpl::~RenderViewHostImpl() {
230 if (ResourceDispatcherHostImpl::Get()) {
231 BrowserThread::PostTask(
232 BrowserThread::IO, FROM_HERE,
233 base::Bind(&ResourceDispatcherHostImpl::OnRenderViewHostDeleted,
234 base::Unretained(ResourceDispatcherHostImpl::Get()),
235 GetProcess()->GetID(), GetRoutingID()));
238 delegate_->RenderViewDeleted(this);
240 // If this was swapped out, it already decremented the active view
241 // count of the SiteInstance it belongs to.
242 if (IsRVHStateActive(rvh_state_))
243 instance_->decrement_active_view_count();
246 RenderViewHostDelegate* RenderViewHostImpl::GetDelegate() const {
247 return delegate_;
250 SiteInstance* RenderViewHostImpl::GetSiteInstance() const {
251 return instance_.get();
254 bool RenderViewHostImpl::CreateRenderView(
255 const base::string16& frame_name,
256 int opener_route_id,
257 int proxy_route_id,
258 int32 max_page_id,
259 bool window_was_created_with_opener) {
260 TRACE_EVENT0("renderer_host,navigation",
261 "RenderViewHostImpl::CreateRenderView");
262 DCHECK(!IsRenderViewLive()) << "Creating view twice";
264 // The process may (if we're sharing a process with another host that already
265 // initialized it) or may not (we have our own process or the old process
266 // crashed) have been initialized. Calling Init multiple times will be
267 // ignored, so this is safe.
268 if (!GetProcess()->Init())
269 return false;
270 DCHECK(GetProcess()->HasConnection());
271 DCHECK(GetProcess()->GetBrowserContext());
273 renderer_initialized_ = true;
275 GpuSurfaceTracker::Get()->SetSurfaceHandle(
276 surface_id(), GetCompositingSurface());
278 // Ensure the RenderView starts with a next_page_id larger than any existing
279 // page ID it might be asked to render.
280 int32 next_page_id = 1;
281 if (max_page_id > -1)
282 next_page_id = max_page_id + 1;
284 ViewMsg_New_Params params;
285 params.renderer_preferences =
286 delegate_->GetRendererPrefs(GetProcess()->GetBrowserContext());
287 params.web_preferences = GetWebkitPreferences();
288 params.view_id = GetRoutingID();
289 params.main_frame_routing_id = main_frame_routing_id_;
290 params.surface_id = surface_id();
291 params.session_storage_namespace_id =
292 delegate_->GetSessionStorageNamespace(instance_.get())->id();
293 params.frame_name = frame_name;
294 // Ensure the RenderView sets its opener correctly.
295 params.opener_route_id = opener_route_id;
296 params.swapped_out = !IsRVHStateActive(rvh_state_);
297 params.proxy_routing_id = proxy_route_id;
298 params.hidden = is_hidden();
299 params.never_visible = delegate_->IsNeverVisible();
300 params.window_was_created_with_opener = window_was_created_with_opener;
301 params.next_page_id = next_page_id;
302 GetWebScreenInfo(&params.screen_info);
304 Send(new ViewMsg_New(params));
306 // If it's enabled, tell the renderer to set up the Javascript bindings for
307 // sending messages back to the browser.
308 if (GetProcess()->IsIsolatedGuest())
309 DCHECK_EQ(0, enabled_bindings_);
310 Send(new ViewMsg_AllowBindings(GetRoutingID(), enabled_bindings_));
311 // Let our delegate know that we created a RenderView.
312 delegate_->RenderViewCreated(this);
314 return true;
317 bool RenderViewHostImpl::IsRenderViewLive() const {
318 return GetProcess()->HasConnection() && renderer_initialized_;
321 void RenderViewHostImpl::SyncRendererPrefs() {
322 Send(new ViewMsg_SetRendererPrefs(GetRoutingID(),
323 delegate_->GetRendererPrefs(
324 GetProcess()->GetBrowserContext())));
327 WebPreferences RenderViewHostImpl::ComputeWebkitPrefs(const GURL& url) {
328 TRACE_EVENT0("browser", "RenderViewHostImpl::GetWebkitPrefs");
329 WebPreferences prefs;
331 const base::CommandLine& command_line =
332 *base::CommandLine::ForCurrentProcess();
334 prefs.javascript_enabled =
335 !command_line.HasSwitch(switches::kDisableJavaScript);
336 prefs.web_security_enabled =
337 !command_line.HasSwitch(switches::kDisableWebSecurity);
338 prefs.plugins_enabled =
339 !command_line.HasSwitch(switches::kDisablePlugins);
340 prefs.java_enabled =
341 !command_line.HasSwitch(switches::kDisableJava);
343 prefs.remote_fonts_enabled =
344 !command_line.HasSwitch(switches::kDisableRemoteFonts);
345 prefs.xslt_enabled =
346 !command_line.HasSwitch(switches::kDisableXSLT);
347 prefs.xss_auditor_enabled =
348 !command_line.HasSwitch(switches::kDisableXSSAuditor);
349 prefs.application_cache_enabled =
350 !command_line.HasSwitch(switches::kDisableApplicationCache);
352 prefs.local_storage_enabled =
353 !command_line.HasSwitch(switches::kDisableLocalStorage);
354 prefs.databases_enabled =
355 !command_line.HasSwitch(switches::kDisableDatabases);
356 #if defined(OS_ANDROID)
357 // WebAudio is enabled by default on x86 and ARM.
358 prefs.webaudio_enabled =
359 !command_line.HasSwitch(switches::kDisableWebAudio);
360 #endif
362 prefs.experimental_webgl_enabled =
363 GpuProcessHost::gpu_enabled() &&
364 !command_line.HasSwitch(switches::kDisable3DAPIs) &&
365 !command_line.HasSwitch(switches::kDisableExperimentalWebGL);
367 prefs.pepper_3d_enabled =
368 !command_line.HasSwitch(switches::kDisablePepper3d);
370 prefs.flash_3d_enabled =
371 GpuProcessHost::gpu_enabled() &&
372 !command_line.HasSwitch(switches::kDisableFlash3d);
373 prefs.flash_stage3d_enabled =
374 GpuProcessHost::gpu_enabled() &&
375 !command_line.HasSwitch(switches::kDisableFlashStage3d);
376 prefs.flash_stage3d_baseline_enabled =
377 GpuProcessHost::gpu_enabled() &&
378 !command_line.HasSwitch(switches::kDisableFlashStage3d);
380 prefs.allow_file_access_from_file_urls =
381 command_line.HasSwitch(switches::kAllowFileAccessFromFiles);
383 prefs.layer_squashing_enabled = true;
384 if (command_line.HasSwitch(switches::kEnableLayerSquashing))
385 prefs.layer_squashing_enabled = true;
386 if (command_line.HasSwitch(switches::kDisableLayerSquashing))
387 prefs.layer_squashing_enabled = false;
389 prefs.accelerated_2d_canvas_enabled =
390 GpuProcessHost::gpu_enabled() &&
391 !command_line.HasSwitch(switches::kDisableAccelerated2dCanvas);
392 prefs.antialiased_2d_canvas_disabled =
393 command_line.HasSwitch(switches::kDisable2dCanvasAntialiasing);
394 prefs.accelerated_2d_canvas_msaa_sample_count =
395 atoi(command_line.GetSwitchValueASCII(
396 switches::kAcceleratedCanvas2dMSAASampleCount).c_str());
397 prefs.deferred_filters_enabled =
398 !command_line.HasSwitch(switches::kDisableDeferredFilters);
399 prefs.container_culling_enabled =
400 command_line.HasSwitch(switches::kEnableContainerCulling);
401 prefs.region_based_columns_enabled =
402 command_line.HasSwitch(switches::kEnableRegionBasedColumns);
404 if (IsPinchVirtualViewportEnabled()) {
405 prefs.pinch_virtual_viewport_enabled = true;
406 prefs.pinch_overlay_scrollbar_thickness = 10;
408 prefs.use_solid_color_scrollbars = ui::IsOverlayScrollbarEnabled();
410 #if defined(OS_ANDROID)
411 prefs.user_gesture_required_for_media_playback = !command_line.HasSwitch(
412 switches::kDisableGestureRequirementForMediaPlayback);
413 #endif
415 prefs.touch_enabled = ui::AreTouchEventsEnabled();
416 prefs.device_supports_touch = prefs.touch_enabled &&
417 ui::IsTouchDevicePresent();
418 #if defined(OS_ANDROID)
419 prefs.device_supports_mouse = false;
420 #endif
422 prefs.pointer_events_max_touch_points = ui::MaxTouchPoints();
424 prefs.touch_adjustment_enabled =
425 !command_line.HasSwitch(switches::kDisableTouchAdjustment);
427 #if defined(OS_MACOSX) || defined(OS_CHROMEOS)
428 bool default_enable_scroll_animator = true;
429 #else
430 bool default_enable_scroll_animator = false;
431 #endif
432 prefs.enable_scroll_animator = default_enable_scroll_animator;
433 if (command_line.HasSwitch(switches::kEnableSmoothScrolling))
434 prefs.enable_scroll_animator = true;
435 if (command_line.HasSwitch(switches::kDisableSmoothScrolling))
436 prefs.enable_scroll_animator = false;
438 // Certain GPU features might have been blacklisted.
439 GpuDataManagerImpl::GetInstance()->UpdateRendererWebPrefs(&prefs);
441 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
442 GetProcess()->GetID())) {
443 prefs.loads_images_automatically = true;
444 prefs.javascript_enabled = true;
447 prefs.connection_type = net::NetworkChangeNotifier::GetConnectionType();
448 prefs.is_online =
449 prefs.connection_type != net::NetworkChangeNotifier::CONNECTION_NONE;
451 prefs.number_of_cpu_cores = base::SysInfo::NumberOfProcessors();
453 prefs.viewport_meta_enabled =
454 command_line.HasSwitch(switches::kEnableViewportMeta);
456 prefs.viewport_enabled =
457 command_line.HasSwitch(switches::kEnableViewport) ||
458 prefs.viewport_meta_enabled;
460 prefs.main_frame_resizes_are_orientation_changes =
461 command_line.HasSwitch(switches::kMainFrameResizesAreOrientationChanges);
463 prefs.deferred_image_decoding_enabled =
464 command_line.HasSwitch(switches::kEnableDeferredImageDecoding) ||
465 content::IsImplSidePaintingEnabled();
467 prefs.spatial_navigation_enabled = command_line.HasSwitch(
468 switches::kEnableSpatialNavigation);
470 if (command_line.HasSwitch(switches::kV8CacheOptions)) {
471 const std::string v8_cache_options =
472 command_line.GetSwitchValueASCII(switches::kV8CacheOptions);
473 if (v8_cache_options == "parse") {
474 prefs.v8_cache_options = V8_CACHE_OPTIONS_PARSE;
475 } else if (v8_cache_options == "code") {
476 prefs.v8_cache_options = V8_CACHE_OPTIONS_CODE;
477 } else {
478 prefs.v8_cache_options = V8_CACHE_OPTIONS_OFF;
482 GetContentClient()->browser()->OverrideWebkitPrefs(this, url, &prefs);
483 return prefs;
486 void RenderViewHostImpl::Navigate(const FrameMsg_Navigate_Params& params) {
487 TRACE_EVENT0("renderer_host,navigation", "RenderViewHostImpl::Navigate");
488 delegate_->GetFrameTree()->GetMainFrame()->Navigate(params);
491 void RenderViewHostImpl::NavigateToURL(const GURL& url) {
492 delegate_->GetFrameTree()->GetMainFrame()->NavigateToURL(url);
495 void RenderViewHostImpl::SuppressDialogsUntilSwapOut() {
496 Send(new ViewMsg_SuppressDialogsUntilSwapOut(GetRoutingID()));
499 void RenderViewHostImpl::OnSwappedOut(bool timed_out) {
500 // Ignore spurious swap out ack.
501 if (!IsWaitingForUnloadACK())
502 return;
504 TRACE_EVENT0("navigation", "RenderViewHostImpl::OnSwappedOut");
505 unload_event_monitor_timeout_->Stop();
506 if (timed_out) {
507 base::ProcessHandle process_handle = GetProcess()->GetHandle();
508 int views = 0;
510 // Count the number of active widget hosts for the process, which
511 // is equivalent to views using the process as of this writing.
512 scoped_ptr<RenderWidgetHostIterator> widgets(
513 RenderWidgetHost::GetRenderWidgetHosts());
514 while (RenderWidgetHost* widget = widgets->GetNextHost()) {
515 if (widget->GetProcess()->GetID() == GetProcess()->GetID())
516 ++views;
519 if (!RenderProcessHost::run_renderer_in_process() &&
520 process_handle && views <= 1) {
521 // The process can safely be terminated, only if WebContents sets
522 // SuddenTerminationAllowed, which indicates that the timer has expired.
523 // This is not the case if we load data URLs or about:blank. The reason
524 // is that those have no network requests and this code is hit without
525 // setting the unresponsiveness timer. This allows a corner case where a
526 // navigation to a data URL will leave a process running, if the
527 // beforeunload handler completes fine, but the unload handler hangs.
528 // At this time, the complexity to solve this edge case is not worthwhile.
529 if (SuddenTerminationAllowed()) {
530 // We should kill the process, but for now, just log the data so we can
531 // diagnose the kill rate and investigate if separate timer is needed.
532 // http://crbug.com/104346.
534 // Log a histogram point to help us diagnose how many of those kills
535 // we have performed. 1 is the enum value for RendererType Normal for
536 // the histogram.
537 UMA_HISTOGRAM_PERCENTAGE(
538 "BrowserRenderProcessHost.ChildKillsUnresponsive", 1);
541 // This is going to be incorrect for subframes and will only hit if
542 // --site-per-process is specified.
543 TRACE_EVENT_ASYNC_END0("navigation", "RenderFrameHostImpl::SwapOut", this);
546 switch (rvh_state_) {
547 case STATE_PENDING_SWAP_OUT:
548 SetState(STATE_SWAPPED_OUT);
549 break;
550 case STATE_PENDING_SHUTDOWN:
551 DCHECK(!pending_shutdown_on_swap_out_.is_null());
552 pending_shutdown_on_swap_out_.Run();
553 break;
554 default:
555 NOTREACHED();
559 void RenderViewHostImpl::SetPendingShutdown(const base::Closure& on_swap_out) {
560 pending_shutdown_on_swap_out_ = on_swap_out;
561 SetState(STATE_PENDING_SHUTDOWN);
564 void RenderViewHostImpl::ClosePage() {
565 SetState(STATE_WAITING_FOR_CLOSE);
566 StartHangMonitorTimeout(TimeDelta::FromMilliseconds(kUnloadTimeoutMS));
568 if (IsRenderViewLive()) {
569 // Since we are sending an IPC message to the renderer, increase the event
570 // count to prevent the hang monitor timeout from being stopped by input
571 // event acknowledgements.
572 increment_in_flight_event_count();
574 // TODO(creis): Should this be moved to Shutdown? It may not be called for
575 // RenderViewHosts that have been swapped out.
576 NotificationService::current()->Notify(
577 NOTIFICATION_RENDER_VIEW_HOST_WILL_CLOSE_RENDER_VIEW,
578 Source<RenderViewHost>(this),
579 NotificationService::NoDetails());
581 Send(new ViewMsg_ClosePage(GetRoutingID()));
582 } else {
583 // This RenderViewHost doesn't have a live renderer, so just skip the unload
584 // event and close the page.
585 ClosePageIgnoringUnloadEvents();
589 void RenderViewHostImpl::ClosePageIgnoringUnloadEvents() {
590 StopHangMonitorTimeout();
591 is_waiting_for_beforeunload_ack_ = false;
593 sudden_termination_allowed_ = true;
594 delegate_->Close(this);
597 #if defined(OS_ANDROID)
598 void RenderViewHostImpl::ActivateNearestFindResult(int request_id,
599 float x,
600 float y) {
601 Send(new InputMsg_ActivateNearestFindResult(GetRoutingID(),
602 request_id, x, y));
605 void RenderViewHostImpl::RequestFindMatchRects(int current_version) {
606 Send(new ViewMsg_FindMatchRects(GetRoutingID(), current_version));
608 #endif
610 void RenderViewHostImpl::DragTargetDragEnter(
611 const DropData& drop_data,
612 const gfx::Point& client_pt,
613 const gfx::Point& screen_pt,
614 WebDragOperationsMask operations_allowed,
615 int key_modifiers) {
616 const int renderer_id = GetProcess()->GetID();
617 ChildProcessSecurityPolicyImpl* policy =
618 ChildProcessSecurityPolicyImpl::GetInstance();
620 // The URL could have been cobbled together from any highlighted text string,
621 // and can't be interpreted as a capability.
622 DropData filtered_data(drop_data);
623 GetProcess()->FilterURL(true, &filtered_data.url);
624 if (drop_data.did_originate_from_renderer) {
625 filtered_data.filenames.clear();
628 // The filenames vector, on the other hand, does represent a capability to
629 // access the given files.
630 storage::IsolatedContext::FileInfoSet files;
631 for (std::vector<ui::FileInfo>::iterator iter(
632 filtered_data.filenames.begin());
633 iter != filtered_data.filenames.end();
634 ++iter) {
635 // A dragged file may wind up as the value of an input element, or it
636 // may be used as the target of a navigation instead. We don't know
637 // which will happen at this point, so generously grant both access
638 // and request permissions to the specific file to cover both cases.
639 // We do not give it the permission to request all file:// URLs.
641 // Make sure we have the same display_name as the one we register.
642 if (iter->display_name.empty()) {
643 std::string name;
644 files.AddPath(iter->path, &name);
645 iter->display_name = base::FilePath::FromUTF8Unsafe(name);
646 } else {
647 files.AddPathWithName(iter->path, iter->display_name.AsUTF8Unsafe());
650 policy->GrantRequestSpecificFileURL(renderer_id,
651 net::FilePathToFileURL(iter->path));
653 // If the renderer already has permission to read these paths, we don't need
654 // to re-grant them. This prevents problems with DnD for files in the CrOS
655 // file manager--the file manager already had read/write access to those
656 // directories, but dragging a file would cause the read/write access to be
657 // overwritten with read-only access, making them impossible to delete or
658 // rename until the renderer was killed.
659 if (!policy->CanReadFile(renderer_id, iter->path))
660 policy->GrantReadFile(renderer_id, iter->path);
663 storage::IsolatedContext* isolated_context =
664 storage::IsolatedContext::GetInstance();
665 DCHECK(isolated_context);
666 std::string filesystem_id = isolated_context->RegisterDraggedFileSystem(
667 files);
668 if (!filesystem_id.empty()) {
669 // Grant the permission iff the ID is valid.
670 policy->GrantReadFileSystem(renderer_id, filesystem_id);
672 filtered_data.filesystem_id = base::UTF8ToUTF16(filesystem_id);
674 storage::FileSystemContext* file_system_context =
675 BrowserContext::GetStoragePartition(GetProcess()->GetBrowserContext(),
676 GetSiteInstance())
677 ->GetFileSystemContext();
678 for (size_t i = 0; i < filtered_data.file_system_files.size(); ++i) {
679 storage::FileSystemURL file_system_url =
680 file_system_context->CrackURL(filtered_data.file_system_files[i].url);
682 std::string register_name;
683 std::string filesystem_id = isolated_context->RegisterFileSystemForPath(
684 file_system_url.type(), file_system_url.filesystem_id(),
685 file_system_url.path(), &register_name);
686 policy->GrantReadFileSystem(renderer_id, filesystem_id);
688 // Note: We are using the origin URL provided by the sender here. It may be
689 // different from the receiver's.
690 filtered_data.file_system_files[i].url =
691 GURL(storage::GetIsolatedFileSystemRootURIString(
692 file_system_url.origin(), filesystem_id, std::string())
693 .append(register_name));
696 Send(new DragMsg_TargetDragEnter(GetRoutingID(), filtered_data, client_pt,
697 screen_pt, operations_allowed,
698 key_modifiers));
701 void RenderViewHostImpl::DragTargetDragOver(
702 const gfx::Point& client_pt,
703 const gfx::Point& screen_pt,
704 WebDragOperationsMask operations_allowed,
705 int key_modifiers) {
706 Send(new DragMsg_TargetDragOver(GetRoutingID(), client_pt, screen_pt,
707 operations_allowed, key_modifiers));
710 void RenderViewHostImpl::DragTargetDragLeave() {
711 Send(new DragMsg_TargetDragLeave(GetRoutingID()));
714 void RenderViewHostImpl::DragTargetDrop(
715 const gfx::Point& client_pt,
716 const gfx::Point& screen_pt,
717 int key_modifiers) {
718 Send(new DragMsg_TargetDrop(GetRoutingID(), client_pt, screen_pt,
719 key_modifiers));
722 void RenderViewHostImpl::DragSourceEndedAt(
723 int client_x, int client_y, int screen_x, int screen_y,
724 WebDragOperation operation) {
725 Send(new DragMsg_SourceEnded(GetRoutingID(),
726 gfx::Point(client_x, client_y),
727 gfx::Point(screen_x, screen_y),
728 operation));
731 void RenderViewHostImpl::DragSourceSystemDragEnded() {
732 Send(new DragMsg_SourceSystemDragEnded(GetRoutingID()));
735 RenderFrameHost* RenderViewHostImpl::GetMainFrame() {
736 return RenderFrameHost::FromID(GetProcess()->GetID(), main_frame_routing_id_);
739 void RenderViewHostImpl::AllowBindings(int bindings_flags) {
740 // Never grant any bindings to browser plugin guests.
741 if (GetProcess()->IsIsolatedGuest()) {
742 NOTREACHED() << "Never grant bindings to a guest process.";
743 return;
746 // Ensure we aren't granting WebUI bindings to a process that has already
747 // been used for non-privileged views.
748 if (bindings_flags & BINDINGS_POLICY_WEB_UI &&
749 GetProcess()->HasConnection() &&
750 !ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
751 GetProcess()->GetID())) {
752 // This process has no bindings yet. Make sure it does not have more
753 // than this single active view.
754 RenderProcessHostImpl* process =
755 static_cast<RenderProcessHostImpl*>(GetProcess());
756 // --single-process only has one renderer.
757 if (process->GetActiveViewCount() > 1 &&
758 !base::CommandLine::ForCurrentProcess()->HasSwitch(
759 switches::kSingleProcess))
760 return;
763 if (bindings_flags & BINDINGS_POLICY_WEB_UI) {
764 ChildProcessSecurityPolicyImpl::GetInstance()->GrantWebUIBindings(
765 GetProcess()->GetID());
768 enabled_bindings_ |= bindings_flags;
769 if (renderer_initialized_)
770 Send(new ViewMsg_AllowBindings(GetRoutingID(), enabled_bindings_));
773 int RenderViewHostImpl::GetEnabledBindings() const {
774 return enabled_bindings_;
777 void RenderViewHostImpl::SetWebUIProperty(const std::string& name,
778 const std::string& value) {
779 // This is a sanity check before telling the renderer to enable the property.
780 // It could lie and send the corresponding IPC messages anyway, but we will
781 // not act on them if enabled_bindings_ doesn't agree. If we get here without
782 // WebUI bindings, kill the renderer process.
783 if (enabled_bindings_ & BINDINGS_POLICY_WEB_UI) {
784 Send(new ViewMsg_SetWebUIProperty(GetRoutingID(), name, value));
785 } else {
786 RecordAction(
787 base::UserMetricsAction("BindingsMismatchTerminate_RVH_WebUI"));
788 base::KillProcess(
789 GetProcess()->GetHandle(), content::RESULT_CODE_KILLED, false);
793 void RenderViewHostImpl::GotFocus() {
794 RenderWidgetHostImpl::GotFocus(); // Notifies the renderer it got focus.
796 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
797 if (view)
798 view->GotFocus();
801 void RenderViewHostImpl::LostCapture() {
802 RenderWidgetHostImpl::LostCapture();
803 delegate_->LostCapture();
806 void RenderViewHostImpl::LostMouseLock() {
807 RenderWidgetHostImpl::LostMouseLock();
808 delegate_->LostMouseLock();
811 void RenderViewHostImpl::SetInitialFocus(bool reverse) {
812 Send(new ViewMsg_SetInitialFocus(GetRoutingID(), reverse));
815 void RenderViewHostImpl::FilesSelectedInChooser(
816 const std::vector<ui::SelectedFileInfo>& files,
817 FileChooserParams::Mode permissions) {
818 // Grant the security access requested to the given files.
819 for (size_t i = 0; i < files.size(); ++i) {
820 const ui::SelectedFileInfo& file = files[i];
821 if (permissions == FileChooserParams::Save) {
822 ChildProcessSecurityPolicyImpl::GetInstance()->GrantCreateReadWriteFile(
823 GetProcess()->GetID(), file.local_path);
824 } else {
825 ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
826 GetProcess()->GetID(), file.local_path);
829 Send(new ViewMsg_RunFileChooserResponse(GetRoutingID(), files));
832 void RenderViewHostImpl::DirectoryEnumerationFinished(
833 int request_id,
834 const std::vector<base::FilePath>& files) {
835 // Grant the security access requested to the given files.
836 for (std::vector<base::FilePath>::const_iterator file = files.begin();
837 file != files.end(); ++file) {
838 ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
839 GetProcess()->GetID(), *file);
841 Send(new ViewMsg_EnumerateDirectoryResponse(GetRoutingID(),
842 request_id,
843 files));
846 void RenderViewHostImpl::SetIsLoading(bool is_loading) {
847 if (ResourceDispatcherHostImpl::Get()) {
848 BrowserThread::PostTask(
849 BrowserThread::IO,
850 FROM_HERE,
851 base::Bind(&ResourceDispatcherHostImpl::OnRenderViewHostSetIsLoading,
852 base::Unretained(ResourceDispatcherHostImpl::Get()),
853 GetProcess()->GetID(),
854 GetRoutingID(),
855 is_loading));
857 RenderWidgetHostImpl::SetIsLoading(is_loading);
860 void RenderViewHostImpl::LoadStateChanged(
861 const GURL& url,
862 const net::LoadStateWithParam& load_state,
863 uint64 upload_position,
864 uint64 upload_size) {
865 delegate_->LoadStateChanged(url, load_state, upload_position, upload_size);
868 bool RenderViewHostImpl::SuddenTerminationAllowed() const {
869 return sudden_termination_allowed_ ||
870 GetProcess()->SuddenTerminationAllowed();
873 ///////////////////////////////////////////////////////////////////////////////
874 // RenderViewHostImpl, IPC message handlers:
876 bool RenderViewHostImpl::OnMessageReceived(const IPC::Message& msg) {
877 if (!BrowserMessageFilter::CheckCanDispatchOnUI(msg, this))
878 return true;
880 // Filter out most IPC messages if this renderer is swapped out.
881 // We still want to handle certain ACKs to keep our state consistent.
882 if (IsSwappedOut()) {
883 if (!SwappedOutMessages::CanHandleWhileSwappedOut(msg)) {
884 // If this is a synchronous message and we decided not to handle it,
885 // we must send an error reply, or else the renderer will be stuck
886 // and won't respond to future requests.
887 if (msg.is_sync()) {
888 IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
889 reply->set_reply_error();
890 Send(reply);
892 // Don't continue looking for someone to handle it.
893 return true;
897 if (delegate_->OnMessageReceived(this, msg))
898 return true;
900 bool handled = true;
901 IPC_BEGIN_MESSAGE_MAP(RenderViewHostImpl, msg)
902 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowView, OnShowView)
903 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowWidget, OnShowWidget)
904 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowFullscreenWidget,
905 OnShowFullscreenWidget)
906 IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_RunModal, OnRunModal)
907 IPC_MESSAGE_HANDLER(ViewHostMsg_RenderViewReady, OnRenderViewReady)
908 IPC_MESSAGE_HANDLER(ViewHostMsg_RenderProcessGone, OnRenderProcessGone)
909 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateState, OnUpdateState)
910 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateTargetURL, OnUpdateTargetURL)
911 IPC_MESSAGE_HANDLER(ViewHostMsg_Close, OnClose)
912 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestMove, OnRequestMove)
913 IPC_MESSAGE_HANDLER(ViewHostMsg_DocumentAvailableInMainFrame,
914 OnDocumentAvailableInMainFrame)
915 IPC_MESSAGE_HANDLER(ViewHostMsg_ToggleFullscreen, OnToggleFullscreen)
916 IPC_MESSAGE_HANDLER(ViewHostMsg_DidContentsPreferredSizeChange,
917 OnDidContentsPreferredSizeChange)
918 IPC_MESSAGE_HANDLER(ViewHostMsg_RouteCloseEvent,
919 OnRouteCloseEvent)
920 IPC_MESSAGE_HANDLER(ViewHostMsg_RouteMessageEvent, OnRouteMessageEvent)
921 IPC_MESSAGE_HANDLER(DragHostMsg_StartDragging, OnStartDragging)
922 IPC_MESSAGE_HANDLER(DragHostMsg_UpdateDragCursor, OnUpdateDragCursor)
923 IPC_MESSAGE_HANDLER(DragHostMsg_TargetDrop_ACK, OnTargetDropACK)
924 IPC_MESSAGE_HANDLER(ViewHostMsg_TakeFocus, OnTakeFocus)
925 IPC_MESSAGE_HANDLER(ViewHostMsg_FocusedNodeChanged, OnFocusedNodeChanged)
926 IPC_MESSAGE_HANDLER(ViewHostMsg_ClosePage_ACK, OnClosePageACK)
927 IPC_MESSAGE_HANDLER(ViewHostMsg_DidZoomURL, OnDidZoomURL)
928 IPC_MESSAGE_HANDLER(ViewHostMsg_RunFileChooser, OnRunFileChooser)
929 IPC_MESSAGE_HANDLER(ViewHostMsg_FocusedNodeTouched, OnFocusedNodeTouched)
930 // Have the super handle all other messages.
931 IPC_MESSAGE_UNHANDLED(
932 handled = RenderWidgetHostImpl::OnMessageReceived(msg))
933 IPC_END_MESSAGE_MAP()
935 return handled;
938 void RenderViewHostImpl::Init() {
939 RenderWidgetHostImpl::Init();
942 void RenderViewHostImpl::Shutdown() {
943 // If we are being run modally (see RunModal), then we need to cleanup.
944 if (run_modal_reply_msg_) {
945 Send(run_modal_reply_msg_);
946 run_modal_reply_msg_ = NULL;
947 RenderViewHostImpl* opener =
948 RenderViewHostImpl::FromID(GetProcess()->GetID(), run_modal_opener_id_);
949 if (opener) {
950 opener->StartHangMonitorTimeout(TimeDelta::FromMilliseconds(
951 hung_renderer_delay_ms_));
952 // Balance out the decrement when we got created.
953 opener->increment_in_flight_event_count();
955 run_modal_opener_id_ = MSG_ROUTING_NONE;
958 // We can't release the SessionStorageNamespace until our peer
959 // in the renderer has wound down.
960 if (GetProcess()->HasConnection()) {
961 RenderProcessHostImpl::ReleaseOnCloseACK(
962 GetProcess(),
963 delegate_->GetSessionStorageNamespaceMap(),
964 GetRoutingID());
967 RenderWidgetHostImpl::Shutdown();
970 void RenderViewHostImpl::WasHidden() {
971 if (ResourceDispatcherHostImpl::Get()) {
972 BrowserThread::PostTask(
973 BrowserThread::IO, FROM_HERE,
974 base::Bind(&ResourceDispatcherHostImpl::OnRenderViewHostWasHidden,
975 base::Unretained(ResourceDispatcherHostImpl::Get()),
976 GetProcess()->GetID(), GetRoutingID()));
979 RenderWidgetHostImpl::WasHidden();
982 void RenderViewHostImpl::WasShown(const ui::LatencyInfo& latency_info) {
983 if (ResourceDispatcherHostImpl::Get()) {
984 BrowserThread::PostTask(
985 BrowserThread::IO, FROM_HERE,
986 base::Bind(&ResourceDispatcherHostImpl::OnRenderViewHostWasShown,
987 base::Unretained(ResourceDispatcherHostImpl::Get()),
988 GetProcess()->GetID(), GetRoutingID()));
991 RenderWidgetHostImpl::WasShown(latency_info);
994 bool RenderViewHostImpl::IsRenderView() const {
995 return true;
998 void RenderViewHostImpl::CreateNewWindow(
999 int route_id,
1000 int main_frame_route_id,
1001 const ViewHostMsg_CreateWindow_Params& params,
1002 SessionStorageNamespace* session_storage_namespace) {
1003 ViewHostMsg_CreateWindow_Params validated_params(params);
1004 GetProcess()->FilterURL(false, &validated_params.target_url);
1005 GetProcess()->FilterURL(false, &validated_params.opener_url);
1006 GetProcess()->FilterURL(true, &validated_params.opener_security_origin);
1008 delegate_->CreateNewWindow(
1009 GetProcess()->GetID(), route_id, main_frame_route_id, validated_params,
1010 session_storage_namespace);
1013 void RenderViewHostImpl::CreateNewWidget(int route_id,
1014 blink::WebPopupType popup_type) {
1015 delegate_->CreateNewWidget(GetProcess()->GetID(), route_id, popup_type);
1018 void RenderViewHostImpl::CreateNewFullscreenWidget(int route_id) {
1019 delegate_->CreateNewFullscreenWidget(GetProcess()->GetID(), route_id);
1022 void RenderViewHostImpl::OnShowView(int route_id,
1023 WindowOpenDisposition disposition,
1024 const gfx::Rect& initial_pos,
1025 bool user_gesture) {
1026 if (IsRVHStateActive(rvh_state_)) {
1027 delegate_->ShowCreatedWindow(
1028 route_id, disposition, initial_pos, user_gesture);
1030 Send(new ViewMsg_Move_ACK(route_id));
1033 void RenderViewHostImpl::OnShowWidget(int route_id,
1034 const gfx::Rect& initial_pos) {
1035 if (IsRVHStateActive(rvh_state_))
1036 delegate_->ShowCreatedWidget(route_id, initial_pos);
1037 Send(new ViewMsg_Move_ACK(route_id));
1040 void RenderViewHostImpl::OnShowFullscreenWidget(int route_id) {
1041 if (IsRVHStateActive(rvh_state_))
1042 delegate_->ShowCreatedFullscreenWidget(route_id);
1043 Send(new ViewMsg_Move_ACK(route_id));
1046 void RenderViewHostImpl::OnRunModal(int opener_id, IPC::Message* reply_msg) {
1047 DCHECK(!run_modal_reply_msg_);
1048 run_modal_reply_msg_ = reply_msg;
1049 run_modal_opener_id_ = opener_id;
1051 RecordAction(base::UserMetricsAction("ShowModalDialog"));
1053 RenderViewHostImpl* opener =
1054 RenderViewHostImpl::FromID(GetProcess()->GetID(), run_modal_opener_id_);
1055 if (opener) {
1056 opener->StopHangMonitorTimeout();
1057 // The ack for the mouse down won't come until the dialog closes, so fake it
1058 // so that we don't get a timeout.
1059 opener->decrement_in_flight_event_count();
1062 // TODO(darin): Bug 1107929: Need to inform our delegate to show this view in
1063 // an app-modal fashion.
1066 void RenderViewHostImpl::OnRenderViewReady() {
1067 render_view_termination_status_ = base::TERMINATION_STATUS_STILL_RUNNING;
1068 SendScreenRects();
1069 WasResized();
1070 delegate_->RenderViewReady(this);
1073 void RenderViewHostImpl::OnRenderProcessGone(int status, int exit_code) {
1074 // Keep the termination status so we can get at it later when we
1075 // need to know why it died.
1076 render_view_termination_status_ =
1077 static_cast<base::TerminationStatus>(status);
1079 // Reset frame tree state associated with this process. This must happen
1080 // before RenderViewTerminated because observers expect the subframes of any
1081 // affected frames to be cleared first.
1082 delegate_->GetFrameTree()->RenderProcessGone(this);
1084 // Our base class RenderWidgetHost needs to reset some stuff.
1085 RendererExited(render_view_termination_status_, exit_code);
1087 delegate_->RenderViewTerminated(this,
1088 static_cast<base::TerminationStatus>(status),
1089 exit_code);
1092 void RenderViewHostImpl::OnUpdateState(int32 page_id, const PageState& state) {
1093 if (page_id_ != page_id) {
1094 base::debug::SetCrashKeyValue(
1095 "url1", GetMainFrame()->GetLastCommittedURL().possibly_invalid_spec());
1096 base::debug::SetCrashKeyValue("id1", base::IntToString(page_id_));
1097 base::debug::SetCrashKeyValue("id2", base::IntToString(page_id));
1098 CHECK(false);
1100 // Without this check, the renderer can trick the browser into using
1101 // filenames it can't access in a future session restore.
1102 if (!CanAccessFilesOfPageState(state)) {
1103 GetProcess()->ReceivedBadMessage();
1104 return;
1107 delegate_->UpdateState(this, page_id_, state);
1110 void RenderViewHostImpl::OnUpdateTargetURL(int32 page_id, const GURL& url) {
1111 if (page_id_ != page_id) {
1112 base::debug::SetCrashKeyValue("url1", url.possibly_invalid_spec());
1113 base::debug::SetCrashKeyValue("id1", base::IntToString(page_id_));
1114 base::debug::SetCrashKeyValue("id2", base::IntToString(page_id));
1115 CHECK(false);
1117 if (IsRVHStateActive(rvh_state_))
1118 delegate_->UpdateTargetURL(page_id_, url);
1120 // Send a notification back to the renderer that we are ready to
1121 // receive more target urls.
1122 Send(new ViewMsg_UpdateTargetURL_ACK(GetRoutingID()));
1125 void RenderViewHostImpl::OnClose() {
1126 // If the renderer is telling us to close, it has already run the unload
1127 // events, and we can take the fast path.
1128 ClosePageIgnoringUnloadEvents();
1131 void RenderViewHostImpl::OnRequestMove(const gfx::Rect& pos) {
1132 if (IsRVHStateActive(rvh_state_))
1133 delegate_->RequestMove(pos);
1134 Send(new ViewMsg_Move_ACK(GetRoutingID()));
1137 void RenderViewHostImpl::OnDocumentAvailableInMainFrame(
1138 bool uses_temporary_zoom_level) {
1139 delegate_->DocumentAvailableInMainFrame(this);
1141 if (!uses_temporary_zoom_level)
1142 return;
1144 HostZoomMapImpl* host_zoom_map =
1145 static_cast<HostZoomMapImpl*>(HostZoomMap::GetDefaultForBrowserContext(
1146 GetProcess()->GetBrowserContext()));
1147 host_zoom_map->SetTemporaryZoomLevel(GetProcess()->GetID(),
1148 GetRoutingID(),
1149 host_zoom_map->GetDefaultZoomLevel());
1152 void RenderViewHostImpl::OnToggleFullscreen(bool enter_fullscreen) {
1153 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1154 delegate_->ToggleFullscreenMode(enter_fullscreen);
1155 // We need to notify the contents that its fullscreen state has changed. This
1156 // is done as part of the resize message.
1157 WasResized();
1160 void RenderViewHostImpl::OnDidContentsPreferredSizeChange(
1161 const gfx::Size& new_size) {
1162 delegate_->UpdatePreferredSize(new_size);
1165 void RenderViewHostImpl::OnRenderAutoResized(const gfx::Size& new_size) {
1166 delegate_->ResizeDueToAutoResize(new_size);
1169 void RenderViewHostImpl::OnRouteCloseEvent() {
1170 // Have the delegate route this to the active RenderViewHost.
1171 delegate_->RouteCloseEvent(this);
1174 void RenderViewHostImpl::OnRouteMessageEvent(
1175 const ViewMsg_PostMessage_Params& params) {
1176 // Give to the delegate to route to the active RenderViewHost.
1177 delegate_->RouteMessageEvent(this, params);
1180 void RenderViewHostImpl::OnStartDragging(
1181 const DropData& drop_data,
1182 WebDragOperationsMask drag_operations_mask,
1183 const SkBitmap& bitmap,
1184 const gfx::Vector2d& bitmap_offset_in_dip,
1185 const DragEventSourceInfo& event_info) {
1186 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1187 if (!view)
1188 return;
1190 DropData filtered_data(drop_data);
1191 RenderProcessHost* process = GetProcess();
1192 ChildProcessSecurityPolicyImpl* policy =
1193 ChildProcessSecurityPolicyImpl::GetInstance();
1195 // Allow drag of Javascript URLs to enable bookmarklet drag to bookmark bar.
1196 if (!filtered_data.url.SchemeIs(url::kJavaScriptScheme))
1197 process->FilterURL(true, &filtered_data.url);
1198 process->FilterURL(false, &filtered_data.html_base_url);
1199 // Filter out any paths that the renderer didn't have access to. This prevents
1200 // the following attack on a malicious renderer:
1201 // 1. StartDragging IPC sent with renderer-specified filesystem paths that it
1202 // doesn't have read permissions for.
1203 // 2. We initiate a native DnD operation.
1204 // 3. DnD operation immediately ends since mouse is not held down. DnD events
1205 // still fire though, which causes read permissions to be granted to the
1206 // renderer for any file paths in the drop.
1207 filtered_data.filenames.clear();
1208 for (std::vector<ui::FileInfo>::const_iterator it =
1209 drop_data.filenames.begin();
1210 it != drop_data.filenames.end();
1211 ++it) {
1212 if (policy->CanReadFile(GetProcess()->GetID(), it->path))
1213 filtered_data.filenames.push_back(*it);
1216 storage::FileSystemContext* file_system_context =
1217 BrowserContext::GetStoragePartition(GetProcess()->GetBrowserContext(),
1218 GetSiteInstance())
1219 ->GetFileSystemContext();
1220 filtered_data.file_system_files.clear();
1221 for (size_t i = 0; i < drop_data.file_system_files.size(); ++i) {
1222 storage::FileSystemURL file_system_url =
1223 file_system_context->CrackURL(drop_data.file_system_files[i].url);
1224 if (policy->CanReadFileSystemFile(GetProcess()->GetID(), file_system_url))
1225 filtered_data.file_system_files.push_back(drop_data.file_system_files[i]);
1228 float scale = GetScaleFactorForView(GetView());
1229 gfx::ImageSkia image(gfx::ImageSkiaRep(bitmap, scale));
1230 view->StartDragging(filtered_data, drag_operations_mask, image,
1231 bitmap_offset_in_dip, event_info);
1234 void RenderViewHostImpl::OnUpdateDragCursor(WebDragOperation current_op) {
1235 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1236 if (view)
1237 view->UpdateDragCursor(current_op);
1240 void RenderViewHostImpl::OnTargetDropACK() {
1241 NotificationService::current()->Notify(
1242 NOTIFICATION_RENDER_VIEW_HOST_DID_RECEIVE_DRAG_TARGET_DROP_ACK,
1243 Source<RenderViewHost>(this),
1244 NotificationService::NoDetails());
1247 void RenderViewHostImpl::OnTakeFocus(bool reverse) {
1248 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1249 if (view)
1250 view->TakeFocus(reverse);
1253 void RenderViewHostImpl::OnFocusedNodeChanged(bool is_editable_node) {
1254 is_focused_element_editable_ = is_editable_node;
1255 if (view_)
1256 view_->FocusedNodeChanged(is_editable_node);
1257 #if defined(OS_WIN)
1258 if (!is_editable_node && virtual_keyboard_requested_) {
1259 virtual_keyboard_requested_ = false;
1260 BrowserThread::PostDelayedTask(
1261 BrowserThread::UI, FROM_HERE,
1262 base::Bind(base::IgnoreResult(&DismissVirtualKeyboardTask)),
1263 TimeDelta::FromMilliseconds(kVirtualKeyboardDisplayWaitTimeoutMs));
1265 #endif
1266 NotificationService::current()->Notify(
1267 NOTIFICATION_FOCUS_CHANGED_IN_PAGE,
1268 Source<RenderViewHost>(this),
1269 Details<const bool>(&is_editable_node));
1272 void RenderViewHostImpl::OnUserGesture() {
1273 delegate_->OnUserGesture();
1276 void RenderViewHostImpl::OnClosePageACK() {
1277 decrement_in_flight_event_count();
1278 ClosePageIgnoringUnloadEvents();
1281 void RenderViewHostImpl::NotifyRendererUnresponsive() {
1282 delegate_->RendererUnresponsive(
1283 this, is_waiting_for_beforeunload_ack_, IsWaitingForUnloadACK());
1286 void RenderViewHostImpl::NotifyRendererResponsive() {
1287 delegate_->RendererResponsive(this);
1290 void RenderViewHostImpl::RequestToLockMouse(bool user_gesture,
1291 bool last_unlocked_by_target) {
1292 delegate_->RequestToLockMouse(user_gesture, last_unlocked_by_target);
1295 bool RenderViewHostImpl::IsFullscreen() const {
1296 return delegate_->IsFullscreenForCurrentTab();
1299 void RenderViewHostImpl::OnFocus() {
1300 // Note: We allow focus and blur from swapped out RenderViewHosts, even when
1301 // the active RenderViewHost is in a different BrowsingInstance (e.g., WebUI).
1302 delegate_->Activate();
1305 void RenderViewHostImpl::OnBlur() {
1306 delegate_->Deactivate();
1309 gfx::Rect RenderViewHostImpl::GetRootWindowResizerRect() const {
1310 return delegate_->GetRootWindowResizerRect();
1313 void RenderViewHostImpl::ForwardMouseEvent(
1314 const blink::WebMouseEvent& mouse_event) {
1316 // We make a copy of the mouse event because
1317 // RenderWidgetHost::ForwardMouseEvent will delete |mouse_event|.
1318 blink::WebMouseEvent event_copy(mouse_event);
1319 RenderWidgetHostImpl::ForwardMouseEvent(event_copy);
1321 switch (event_copy.type) {
1322 case WebInputEvent::MouseMove:
1323 delegate_->HandleMouseMove();
1324 break;
1325 case WebInputEvent::MouseLeave:
1326 delegate_->HandleMouseLeave();
1327 break;
1328 case WebInputEvent::MouseDown:
1329 delegate_->HandleMouseDown();
1330 break;
1331 case WebInputEvent::MouseWheel:
1332 if (ignore_input_events())
1333 delegate_->OnIgnoredUIEvent();
1334 break;
1335 case WebInputEvent::MouseUp:
1336 delegate_->HandleMouseUp();
1337 default:
1338 // For now, we don't care about the rest.
1339 break;
1343 void RenderViewHostImpl::OnPointerEventActivate() {
1344 delegate_->HandlePointerActivate();
1347 void RenderViewHostImpl::ForwardKeyboardEvent(
1348 const NativeWebKeyboardEvent& key_event) {
1349 if (ignore_input_events()) {
1350 if (key_event.type == WebInputEvent::RawKeyDown)
1351 delegate_->OnIgnoredUIEvent();
1352 return;
1354 RenderWidgetHostImpl::ForwardKeyboardEvent(key_event);
1357 bool RenderViewHostImpl::IsWaitingForUnloadACK() const {
1358 return rvh_state_ == STATE_WAITING_FOR_CLOSE ||
1359 rvh_state_ == STATE_PENDING_SHUTDOWN ||
1360 rvh_state_ == STATE_PENDING_SWAP_OUT;
1363 void RenderViewHostImpl::OnTextSurroundingSelectionResponse(
1364 const base::string16& content,
1365 size_t start_offset,
1366 size_t end_offset) {
1367 if (!view_)
1368 return;
1369 view_->OnTextSurroundingSelectionResponse(content, start_offset, end_offset);
1372 void RenderViewHostImpl::ExitFullscreen() {
1373 RejectMouseLockOrUnlockIfNecessary();
1374 // Notify delegate_ and renderer of fullscreen state change.
1375 OnToggleFullscreen(false);
1378 WebPreferences RenderViewHostImpl::GetWebkitPreferences() {
1379 if (!web_preferences_.get()) {
1380 OnWebkitPreferencesChanged();
1382 return *web_preferences_;
1385 void RenderViewHostImpl::UpdateWebkitPreferences(const WebPreferences& prefs) {
1386 web_preferences_.reset(new WebPreferences(prefs));
1387 Send(new ViewMsg_UpdateWebPreferences(GetRoutingID(), prefs));
1390 void RenderViewHostImpl::OnWebkitPreferencesChanged() {
1391 // This is defensive code to avoid infinite loops due to code run inside
1392 // UpdateWebkitPreferences() accidentally updating more preferences and thus
1393 // calling back into this code. See crbug.com/398751 for one past example.
1394 if (updating_web_preferences_)
1395 return;
1396 updating_web_preferences_ = true;
1397 UpdateWebkitPreferences(delegate_->ComputeWebkitPrefs());
1398 updating_web_preferences_ = false;
1401 void RenderViewHostImpl::GetAudioOutputControllers(
1402 const GetAudioOutputControllersCallback& callback) const {
1403 scoped_refptr<AudioRendererHost> audio_host =
1404 static_cast<RenderProcessHostImpl*>(GetProcess())->audio_renderer_host();
1405 audio_host->GetOutputControllers(GetRoutingID(), callback);
1408 void RenderViewHostImpl::ClearFocusedElement() {
1409 is_focused_element_editable_ = false;
1410 Send(new ViewMsg_ClearFocusedElement(GetRoutingID()));
1413 bool RenderViewHostImpl::IsFocusedElementEditable() {
1414 return is_focused_element_editable_;
1417 void RenderViewHostImpl::Zoom(PageZoom zoom) {
1418 Send(new ViewMsg_Zoom(GetRoutingID(), zoom));
1421 void RenderViewHostImpl::DisableScrollbarsForThreshold(const gfx::Size& size) {
1422 Send(new ViewMsg_DisableScrollbarsForSmallWindows(GetRoutingID(), size));
1425 void RenderViewHostImpl::EnablePreferredSizeMode() {
1426 Send(new ViewMsg_EnablePreferredSizeChangedMode(GetRoutingID()));
1429 void RenderViewHostImpl::EnableAutoResize(const gfx::Size& min_size,
1430 const gfx::Size& max_size) {
1431 SetShouldAutoResize(true);
1432 Send(new ViewMsg_EnableAutoResize(GetRoutingID(), min_size, max_size));
1435 void RenderViewHostImpl::DisableAutoResize(const gfx::Size& new_size) {
1436 SetShouldAutoResize(false);
1437 Send(new ViewMsg_DisableAutoResize(GetRoutingID(), new_size));
1438 if (!new_size.IsEmpty())
1439 GetView()->SetSize(new_size);
1442 void RenderViewHostImpl::CopyImageAt(int x, int y) {
1443 Send(new ViewMsg_CopyImageAt(GetRoutingID(), x, y));
1446 void RenderViewHostImpl::SaveImageAt(int x, int y) {
1447 Send(new ViewMsg_SaveImageAt(GetRoutingID(), x, y));
1450 void RenderViewHostImpl::ExecuteMediaPlayerActionAtLocation(
1451 const gfx::Point& location, const blink::WebMediaPlayerAction& action) {
1452 Send(new ViewMsg_MediaPlayerActionAt(GetRoutingID(), location, action));
1455 void RenderViewHostImpl::ExecutePluginActionAtLocation(
1456 const gfx::Point& location, const blink::WebPluginAction& action) {
1457 Send(new ViewMsg_PluginActionAt(GetRoutingID(), location, action));
1460 void RenderViewHostImpl::NotifyMoveOrResizeStarted() {
1461 Send(new ViewMsg_MoveOrResizeStarted(GetRoutingID()));
1464 void RenderViewHostImpl::OnDidZoomURL(double zoom_level,
1465 const GURL& url) {
1466 HostZoomMapImpl* host_zoom_map =
1467 static_cast<HostZoomMapImpl*>(HostZoomMap::GetDefaultForBrowserContext(
1468 GetProcess()->GetBrowserContext()));
1470 host_zoom_map->SetZoomLevelForView(GetProcess()->GetID(),
1471 GetRoutingID(),
1472 zoom_level,
1473 net::GetHostOrSpecFromURL(url));
1476 void RenderViewHostImpl::OnRunFileChooser(const FileChooserParams& params) {
1477 delegate_->RunFileChooser(this, params);
1480 void RenderViewHostImpl::OnFocusedNodeTouched(bool editable) {
1481 #if defined(OS_WIN)
1482 if (editable) {
1483 virtual_keyboard_requested_ = base::win::DisplayVirtualKeyboard();
1484 } else {
1485 virtual_keyboard_requested_ = false;
1486 base::win::DismissVirtualKeyboard();
1488 #endif
1491 void RenderViewHostImpl::SetState(RenderViewHostImplState rvh_state) {
1492 // We update the number of RenderViews in a SiteInstance when the
1493 // swapped out status of this RenderView gets flipped to/from live.
1494 if (!IsRVHStateActive(rvh_state_) && IsRVHStateActive(rvh_state))
1495 instance_->increment_active_view_count();
1496 else if (IsRVHStateActive(rvh_state_) && !IsRVHStateActive(rvh_state))
1497 instance_->decrement_active_view_count();
1499 // Whenever we change the RVH state to and from live or swapped out state, we
1500 // should not be waiting for beforeunload or unload acks. We clear them here
1501 // to be safe, since they can cause navigations to be ignored in OnNavigate.
1502 if (rvh_state == STATE_DEFAULT ||
1503 rvh_state == STATE_SWAPPED_OUT ||
1504 rvh_state_ == STATE_DEFAULT ||
1505 rvh_state_ == STATE_SWAPPED_OUT) {
1506 is_waiting_for_beforeunload_ack_ = false;
1508 rvh_state_ = rvh_state;
1512 bool RenderViewHostImpl::CanAccessFilesOfPageState(
1513 const PageState& state) const {
1514 ChildProcessSecurityPolicyImpl* policy =
1515 ChildProcessSecurityPolicyImpl::GetInstance();
1517 const std::vector<base::FilePath>& file_paths = state.GetReferencedFiles();
1518 for (std::vector<base::FilePath>::const_iterator file = file_paths.begin();
1519 file != file_paths.end(); ++file) {
1520 if (!policy->CanReadFile(GetProcess()->GetID(), *file))
1521 return false;
1523 return true;
1526 void RenderViewHostImpl::AttachToFrameTree() {
1527 FrameTree* frame_tree = delegate_->GetFrameTree();
1529 frame_tree->ResetForMainFrameSwap();
1532 void RenderViewHostImpl::SelectWordAroundCaret() {
1533 Send(new ViewMsg_SelectWordAroundCaret(GetRoutingID()));
1536 } // namespace content