Pass the size to the RenderView on creation.
[chromium-blink-merge.git] / content / browser / renderer_host / render_view_host_impl.cc
blob8bafdab90c90cc650130cc2983c044e9151b604d
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/field_trial.h"
19 #include "base/metrics/histogram.h"
20 #include "base/stl_util.h"
21 #include "base/strings/string_util.h"
22 #include "base/strings/utf_string_conversions.h"
23 #include "base/sys_info.h"
24 #include "base/time/time.h"
25 #include "base/values.h"
26 #include "cc/base/switches.h"
27 #include "content/browser/child_process_security_policy_impl.h"
28 #include "content/browser/dom_storage/session_storage_namespace_impl.h"
29 #include "content/browser/frame_host/frame_tree.h"
30 #include "content/browser/gpu/compositor_util.h"
31 #include "content/browser/gpu/gpu_data_manager_impl.h"
32 #include "content/browser/gpu/gpu_process_host.h"
33 #include "content/browser/gpu/gpu_surface_tracker.h"
34 #include "content/browser/host_zoom_map_impl.h"
35 #include "content/browser/loader/resource_dispatcher_host_impl.h"
36 #include "content/browser/renderer_host/dip_util.h"
37 #include "content/browser/renderer_host/media/audio_renderer_host.h"
38 #include "content/browser/renderer_host/render_process_host_impl.h"
39 #include "content/browser/renderer_host/render_view_host_delegate.h"
40 #include "content/browser/renderer_host/render_view_host_delegate_view.h"
41 #include "content/browser/renderer_host/render_widget_host_view_base.h"
42 #include "content/common/browser_plugin/browser_plugin_messages.h"
43 #include "content/common/content_switches_internal.h"
44 #include "content/common/drag_messages.h"
45 #include "content/common/frame_messages.h"
46 #include "content/common/input_messages.h"
47 #include "content/common/inter_process_time_ticks_converter.h"
48 #include "content/common/speech_recognition_messages.h"
49 #include "content/common/swapped_out_messages.h"
50 #include "content/common/view_messages.h"
51 #include "content/public/browser/ax_event_notification_details.h"
52 #include "content/public/browser/browser_accessibility_state.h"
53 #include "content/public/browser/browser_context.h"
54 #include "content/public/browser/browser_message_filter.h"
55 #include "content/public/browser/content_browser_client.h"
56 #include "content/public/browser/native_web_keyboard_event.h"
57 #include "content/public/browser/notification_details.h"
58 #include "content/public/browser/notification_service.h"
59 #include "content/public/browser/notification_types.h"
60 #include "content/public/browser/render_frame_host.h"
61 #include "content/public/browser/render_widget_host_iterator.h"
62 #include "content/public/browser/storage_partition.h"
63 #include "content/public/browser/user_metrics.h"
64 #include "content/public/common/bindings_policy.h"
65 #include "content/public/common/content_constants.h"
66 #include "content/public/common/content_switches.h"
67 #include "content/public/common/context_menu_params.h"
68 #include "content/public/common/drop_data.h"
69 #include "content/public/common/file_chooser_file_info.h"
70 #include "content/public/common/file_chooser_params.h"
71 #include "content/public/common/result_codes.h"
72 #include "content/public/common/url_constants.h"
73 #include "content/public/common/url_utils.h"
74 #include "net/base/filename_util.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 "storage/browser/fileapi/isolated_context.h"
79 #include "third_party/skia/include/core/SkBitmap.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 "url/url_constants.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 int64 RenderViewHostImpl::kUnloadTimeoutMS = 1000;
136 ///////////////////////////////////////////////////////////////////////////////
137 // RenderViewHost, public:
139 // static
140 RenderViewHost* RenderViewHost::FromID(int render_process_id,
141 int render_view_id) {
142 return RenderViewHostImpl::FromID(render_process_id, render_view_id);
145 // static
146 RenderViewHost* RenderViewHost::From(RenderWidgetHost* rwh) {
147 DCHECK(rwh->IsRenderView());
148 return static_cast<RenderViewHostImpl*>(RenderWidgetHostImpl::From(rwh));
151 ///////////////////////////////////////////////////////////////////////////////
152 // RenderViewHostImpl, public:
154 // static
155 RenderViewHostImpl* RenderViewHostImpl::FromID(int render_process_id,
156 int render_view_id) {
157 RenderWidgetHost* widget =
158 RenderWidgetHost::FromID(render_process_id, render_view_id);
159 if (!widget || !widget->IsRenderView())
160 return NULL;
161 return static_cast<RenderViewHostImpl*>(RenderWidgetHostImpl::From(widget));
164 RenderViewHostImpl::RenderViewHostImpl(
165 SiteInstance* instance,
166 RenderViewHostDelegate* delegate,
167 RenderWidgetHostDelegate* widget_delegate,
168 int routing_id,
169 int main_frame_routing_id,
170 bool swapped_out,
171 bool hidden,
172 bool has_initialized_audio_host)
173 : RenderWidgetHostImpl(widget_delegate,
174 instance->GetProcess(),
175 routing_id,
176 hidden),
177 frames_ref_count_(0),
178 delegate_(delegate),
179 instance_(static_cast<SiteInstanceImpl*>(instance)),
180 waiting_for_drag_context_response_(false),
181 enabled_bindings_(0),
182 page_id_(-1),
183 is_active_(!swapped_out),
184 is_swapped_out_(swapped_out),
185 main_frame_routing_id_(main_frame_routing_id),
186 run_modal_reply_msg_(NULL),
187 run_modal_opener_id_(MSG_ROUTING_NONE),
188 is_waiting_for_close_ack_(false),
189 sudden_termination_allowed_(false),
190 render_view_termination_status_(base::TERMINATION_STATUS_STILL_RUNNING),
191 virtual_keyboard_requested_(false),
192 is_focused_element_editable_(false),
193 updating_web_preferences_(false),
194 weak_factory_(this) {
195 DCHECK(instance_.get());
196 CHECK(delegate_); // http://crbug.com/82827
198 GetProcess()->EnableSendQueue();
200 if (ResourceDispatcherHostImpl::Get()) {
201 bool has_active_audio = false;
202 if (has_initialized_audio_host) {
203 scoped_refptr<AudioRendererHost> arh =
204 static_cast<RenderProcessHostImpl*>(GetProcess())
205 ->audio_renderer_host();
206 if (arh.get())
207 has_active_audio = arh->RenderViewHasActiveAudio(GetRoutingID());
209 BrowserThread::PostTask(
210 BrowserThread::IO,
211 FROM_HERE,
212 base::Bind(&ResourceDispatcherHostImpl::OnRenderViewHostCreated,
213 base::Unretained(ResourceDispatcherHostImpl::Get()),
214 GetProcess()->GetID(),
215 GetRoutingID(),
216 !is_hidden(),
217 has_active_audio));
219 #if defined(ENABLE_BROWSER_CDMS)
220 media_web_contents_observer_.reset(new MediaWebContentsObserver(this));
221 #endif
224 RenderViewHostImpl::~RenderViewHostImpl() {
225 if (ResourceDispatcherHostImpl::Get()) {
226 BrowserThread::PostTask(
227 BrowserThread::IO, FROM_HERE,
228 base::Bind(&ResourceDispatcherHostImpl::OnRenderViewHostDeleted,
229 base::Unretained(ResourceDispatcherHostImpl::Get()),
230 GetProcess()->GetID(), GetRoutingID()));
233 delegate_->RenderViewDeleted(this);
236 RenderViewHostDelegate* RenderViewHostImpl::GetDelegate() const {
237 return delegate_;
240 SiteInstanceImpl* RenderViewHostImpl::GetSiteInstance() const {
241 return instance_.get();
244 bool RenderViewHostImpl::CreateRenderView(
245 const base::string16& frame_name,
246 int opener_route_id,
247 int proxy_route_id,
248 int32 max_page_id,
249 bool window_was_created_with_opener) {
250 TRACE_EVENT0("renderer_host,navigation",
251 "RenderViewHostImpl::CreateRenderView");
252 DCHECK(!IsRenderViewLive()) << "Creating view twice";
254 // The process may (if we're sharing a process with another host that already
255 // initialized it) or may not (we have our own process or the old process
256 // crashed) have been initialized. Calling Init multiple times will be
257 // ignored, so this is safe.
258 if (!GetProcess()->Init())
259 return false;
260 DCHECK(GetProcess()->HasConnection());
261 DCHECK(GetProcess()->GetBrowserContext());
263 renderer_initialized_ = true;
265 GpuSurfaceTracker::Get()->SetSurfaceHandle(
266 surface_id(), GetCompositingSurface());
268 // Ensure the RenderView starts with a next_page_id larger than any existing
269 // page ID it might be asked to render.
270 int32 next_page_id = 1;
271 if (max_page_id > -1)
272 next_page_id = max_page_id + 1;
274 ViewMsg_New_Params params;
275 params.renderer_preferences =
276 delegate_->GetRendererPrefs(GetProcess()->GetBrowserContext());
277 params.web_preferences = GetWebkitPreferences();
278 params.view_id = GetRoutingID();
279 params.main_frame_routing_id = main_frame_routing_id_;
280 params.surface_id = surface_id();
281 params.session_storage_namespace_id =
282 delegate_->GetSessionStorageNamespace(instance_.get())->id();
283 params.frame_name = frame_name;
284 // Ensure the RenderView sets its opener correctly.
285 params.opener_route_id = opener_route_id;
286 params.swapped_out = !is_active_;
287 params.proxy_routing_id = proxy_route_id;
288 params.hidden = is_hidden();
289 params.never_visible = delegate_->IsNeverVisible();
290 params.window_was_created_with_opener = window_was_created_with_opener;
291 params.next_page_id = next_page_id;
292 params.enable_auto_resize = auto_resize_enabled();
293 params.min_size = min_size_for_auto_resize();
294 params.max_size = max_size_for_auto_resize();
295 GetResizeParams(&params.initial_size);
297 if (!Send(new ViewMsg_New(params)))
298 return false;
299 SetInitialRenderSizeParams(params.initial_size);
301 // If it's enabled, tell the renderer to set up the Javascript bindings for
302 // sending messages back to the browser.
303 if (GetProcess()->IsIsolatedGuest())
304 DCHECK_EQ(0, enabled_bindings_);
305 Send(new ViewMsg_AllowBindings(GetRoutingID(), enabled_bindings_));
306 // Let our delegate know that we created a RenderView.
307 delegate_->RenderViewCreated(this);
309 return true;
312 bool RenderViewHostImpl::IsRenderViewLive() const {
313 return GetProcess()->HasConnection() && renderer_initialized_;
316 void RenderViewHostImpl::SyncRendererPrefs() {
317 Send(new ViewMsg_SetRendererPrefs(GetRoutingID(),
318 delegate_->GetRendererPrefs(
319 GetProcess()->GetBrowserContext())));
322 WebPreferences RenderViewHostImpl::ComputeWebkitPrefs(const GURL& url) {
323 TRACE_EVENT0("browser", "RenderViewHostImpl::GetWebkitPrefs");
324 WebPreferences prefs;
326 const base::CommandLine& command_line =
327 *base::CommandLine::ForCurrentProcess();
329 prefs.javascript_enabled =
330 !command_line.HasSwitch(switches::kDisableJavaScript);
331 prefs.web_security_enabled =
332 !command_line.HasSwitch(switches::kDisableWebSecurity);
333 prefs.plugins_enabled =
334 !command_line.HasSwitch(switches::kDisablePlugins);
335 prefs.java_enabled =
336 !command_line.HasSwitch(switches::kDisableJava);
338 prefs.remote_fonts_enabled =
339 !command_line.HasSwitch(switches::kDisableRemoteFonts);
340 prefs.xslt_enabled =
341 !command_line.HasSwitch(switches::kDisableXSLT);
342 prefs.xss_auditor_enabled =
343 !command_line.HasSwitch(switches::kDisableXSSAuditor);
344 prefs.application_cache_enabled =
345 !command_line.HasSwitch(switches::kDisableApplicationCache);
347 prefs.local_storage_enabled =
348 !command_line.HasSwitch(switches::kDisableLocalStorage);
349 prefs.databases_enabled =
350 !command_line.HasSwitch(switches::kDisableDatabases);
351 #if defined(OS_ANDROID)
352 // WebAudio is enabled by default on x86 and ARM.
353 prefs.webaudio_enabled =
354 !command_line.HasSwitch(switches::kDisableWebAudio);
355 #endif
357 prefs.experimental_webgl_enabled =
358 GpuProcessHost::gpu_enabled() &&
359 !command_line.HasSwitch(switches::kDisable3DAPIs) &&
360 !command_line.HasSwitch(switches::kDisableExperimentalWebGL);
362 prefs.pepper_3d_enabled =
363 !command_line.HasSwitch(switches::kDisablePepper3d);
365 prefs.flash_3d_enabled =
366 GpuProcessHost::gpu_enabled() &&
367 !command_line.HasSwitch(switches::kDisableFlash3d);
368 prefs.flash_stage3d_enabled =
369 GpuProcessHost::gpu_enabled() &&
370 !command_line.HasSwitch(switches::kDisableFlashStage3d);
371 prefs.flash_stage3d_baseline_enabled =
372 GpuProcessHost::gpu_enabled() &&
373 !command_line.HasSwitch(switches::kDisableFlashStage3d);
375 prefs.allow_file_access_from_file_urls =
376 command_line.HasSwitch(switches::kAllowFileAccessFromFiles);
378 prefs.layer_squashing_enabled = true;
379 if (command_line.HasSwitch(switches::kEnableLayerSquashing))
380 prefs.layer_squashing_enabled = true;
381 if (command_line.HasSwitch(switches::kDisableLayerSquashing))
382 prefs.layer_squashing_enabled = false;
384 prefs.accelerated_2d_canvas_enabled =
385 GpuProcessHost::gpu_enabled() &&
386 !command_line.HasSwitch(switches::kDisableAccelerated2dCanvas);
387 prefs.antialiased_2d_canvas_disabled =
388 command_line.HasSwitch(switches::kDisable2dCanvasAntialiasing);
389 prefs.antialiased_clips_2d_canvas_enabled =
390 command_line.HasSwitch(switches::kEnable2dCanvasClipAntialiasing);
391 prefs.accelerated_2d_canvas_msaa_sample_count =
392 atoi(command_line.GetSwitchValueASCII(
393 switches::kAcceleratedCanvas2dMSAASampleCount).c_str());
394 prefs.container_culling_enabled =
395 command_line.HasSwitch(switches::kEnableContainerCulling);
396 prefs.text_blobs_enabled =
397 command_line.HasSwitch(switches::kEnableTextBlobs);
398 prefs.region_based_columns_enabled =
399 command_line.HasSwitch(switches::kEnableRegionBasedColumns);
401 if (IsPinchVirtualViewportEnabled()) {
402 prefs.pinch_virtual_viewport_enabled = true;
403 prefs.pinch_overlay_scrollbar_thickness = 10;
405 prefs.use_solid_color_scrollbars = ui::IsOverlayScrollbarEnabled();
407 #if defined(OS_ANDROID)
408 // On Android, user gestures are normally required, unless that requirement
409 // is disabled with a command-line switch or the equivalent field trial is
410 // is set to "Enabled".
411 const std::string autoplay_group_name = base::FieldTrialList::FindFullName(
412 "MediaElementAutoplay");
413 prefs.user_gesture_required_for_media_playback = !command_line.HasSwitch(
414 switches::kDisableGestureRequirementForMediaPlayback) &&
415 (autoplay_group_name.empty() || autoplay_group_name != "Enabled");
416 #endif
418 prefs.touch_enabled = ui::AreTouchEventsEnabled();
419 prefs.device_supports_touch = prefs.touch_enabled &&
420 ui::IsTouchDevicePresent();
421 #if defined(OS_ANDROID)
422 prefs.device_supports_mouse = false;
423 #endif
425 prefs.pointer_events_max_touch_points = ui::MaxTouchPoints();
427 prefs.touch_adjustment_enabled =
428 !command_line.HasSwitch(switches::kDisableTouchAdjustment);
430 prefs.slimming_paint_enabled =
431 command_line.HasSwitch(switches::kEnableSlimmingPaint);
433 #if defined(OS_MACOSX) || defined(OS_CHROMEOS)
434 bool default_enable_scroll_animator = true;
435 #else
436 bool default_enable_scroll_animator = false;
437 #endif
438 prefs.enable_scroll_animator = default_enable_scroll_animator;
439 if (command_line.HasSwitch(switches::kEnableSmoothScrolling))
440 prefs.enable_scroll_animator = true;
441 if (command_line.HasSwitch(switches::kDisableSmoothScrolling))
442 prefs.enable_scroll_animator = false;
444 // Certain GPU features might have been blacklisted.
445 GpuDataManagerImpl::GetInstance()->UpdateRendererWebPrefs(&prefs);
447 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
448 GetProcess()->GetID())) {
449 prefs.loads_images_automatically = true;
450 prefs.javascript_enabled = true;
453 prefs.connection_type = net::NetworkChangeNotifier::GetConnectionType();
454 prefs.is_online =
455 prefs.connection_type != net::NetworkChangeNotifier::CONNECTION_NONE;
457 prefs.number_of_cpu_cores = base::SysInfo::NumberOfProcessors();
459 prefs.viewport_meta_enabled =
460 command_line.HasSwitch(switches::kEnableViewportMeta);
462 prefs.viewport_enabled =
463 command_line.HasSwitch(switches::kEnableViewport) ||
464 prefs.viewport_meta_enabled;
466 prefs.main_frame_resizes_are_orientation_changes =
467 command_line.HasSwitch(switches::kMainFrameResizesAreOrientationChanges);
469 prefs.deferred_image_decoding_enabled =
470 command_line.HasSwitch(switches::kEnableDeferredImageDecoding) ||
471 content::IsImplSidePaintingEnabled();
473 prefs.image_color_profiles_enabled =
474 command_line.HasSwitch(switches::kEnableImageColorProfiles);
476 prefs.spatial_navigation_enabled = command_line.HasSwitch(
477 switches::kEnableSpatialNavigation);
479 if (command_line.HasSwitch(switches::kV8CacheOptions)) {
480 const std::string v8_cache_options =
481 command_line.GetSwitchValueASCII(switches::kV8CacheOptions);
482 if (v8_cache_options == "parse") {
483 prefs.v8_cache_options = V8_CACHE_OPTIONS_PARSE;
484 } else if (v8_cache_options == "code") {
485 prefs.v8_cache_options = V8_CACHE_OPTIONS_CODE;
486 } else {
487 prefs.v8_cache_options = V8_CACHE_OPTIONS_OFF;
491 std::string streaming_experiment_group =
492 base::FieldTrialList::FindFullName("V8ScriptStreaming");
493 prefs.v8_script_streaming_enabled =
494 command_line.HasSwitch(switches::kEnableV8ScriptStreaming);
495 if (streaming_experiment_group == "Enabled") {
496 prefs.v8_script_streaming_enabled = true;
497 prefs.v8_script_streaming_mode = V8_SCRIPT_STREAMING_MODE_ALL;
498 } else if (streaming_experiment_group == "OnlyAsyncAndDefer") {
499 prefs.v8_script_streaming_enabled = true;
500 prefs.v8_script_streaming_mode =
501 V8_SCRIPT_STREAMING_MODE_ONLY_ASYNC_AND_DEFER;
502 } else if (streaming_experiment_group == "AllPlusBlockParserBlocking") {
503 prefs.v8_script_streaming_enabled = true;
504 prefs.v8_script_streaming_mode =
505 V8_SCRIPT_STREAMING_MODE_ALL_PLUS_BLOCK_PARSER_BLOCKING;
508 GetContentClient()->browser()->OverrideWebkitPrefs(this, url, &prefs);
509 return prefs;
512 void RenderViewHostImpl::SuppressDialogsUntilSwapOut() {
513 Send(new ViewMsg_SuppressDialogsUntilSwapOut(GetRoutingID()));
516 void RenderViewHostImpl::ClosePage() {
517 is_waiting_for_close_ack_ = true;
518 StartHangMonitorTimeout(TimeDelta::FromMilliseconds(kUnloadTimeoutMS));
520 if (IsRenderViewLive()) {
521 // Since we are sending an IPC message to the renderer, increase the event
522 // count to prevent the hang monitor timeout from being stopped by input
523 // event acknowledgements.
524 increment_in_flight_event_count();
526 // TODO(creis): Should this be moved to Shutdown? It may not be called for
527 // RenderViewHosts that have been swapped out.
528 NotificationService::current()->Notify(
529 NOTIFICATION_RENDER_VIEW_HOST_WILL_CLOSE_RENDER_VIEW,
530 Source<RenderViewHost>(this),
531 NotificationService::NoDetails());
533 Send(new ViewMsg_ClosePage(GetRoutingID()));
534 } else {
535 // This RenderViewHost doesn't have a live renderer, so just skip the unload
536 // event and close the page.
537 ClosePageIgnoringUnloadEvents();
541 void RenderViewHostImpl::ClosePageIgnoringUnloadEvents() {
542 StopHangMonitorTimeout();
543 is_waiting_for_close_ack_ = false;
545 sudden_termination_allowed_ = true;
546 delegate_->Close(this);
549 #if defined(OS_ANDROID)
550 void RenderViewHostImpl::ActivateNearestFindResult(int request_id,
551 float x,
552 float y) {
553 Send(new InputMsg_ActivateNearestFindResult(GetRoutingID(),
554 request_id, x, y));
557 void RenderViewHostImpl::RequestFindMatchRects(int current_version) {
558 Send(new ViewMsg_FindMatchRects(GetRoutingID(), current_version));
560 #endif
562 void RenderViewHostImpl::DragTargetDragEnter(
563 const DropData& drop_data,
564 const gfx::Point& client_pt,
565 const gfx::Point& screen_pt,
566 WebDragOperationsMask operations_allowed,
567 int key_modifiers) {
568 const int renderer_id = GetProcess()->GetID();
569 ChildProcessSecurityPolicyImpl* policy =
570 ChildProcessSecurityPolicyImpl::GetInstance();
572 #if defined(OS_CHROMEOS)
573 // The externalfile:// scheme is used in Chrome OS to open external files in a
574 // browser tab.
575 if (drop_data.url.SchemeIs(content::kExternalFileScheme))
576 policy->GrantRequestURL(renderer_id, drop_data.url);
577 #endif
579 // The URL could have been cobbled together from any highlighted text string,
580 // and can't be interpreted as a capability.
581 DropData filtered_data(drop_data);
582 GetProcess()->FilterURL(true, &filtered_data.url);
583 if (drop_data.did_originate_from_renderer) {
584 filtered_data.filenames.clear();
587 // The filenames vector, on the other hand, does represent a capability to
588 // access the given files.
589 storage::IsolatedContext::FileInfoSet files;
590 for (std::vector<ui::FileInfo>::iterator iter(
591 filtered_data.filenames.begin());
592 iter != filtered_data.filenames.end();
593 ++iter) {
594 // A dragged file may wind up as the value of an input element, or it
595 // may be used as the target of a navigation instead. We don't know
596 // which will happen at this point, so generously grant both access
597 // and request permissions to the specific file to cover both cases.
598 // We do not give it the permission to request all file:// URLs.
600 // Make sure we have the same display_name as the one we register.
601 if (iter->display_name.empty()) {
602 std::string name;
603 files.AddPath(iter->path, &name);
604 iter->display_name = base::FilePath::FromUTF8Unsafe(name);
605 } else {
606 files.AddPathWithName(iter->path, iter->display_name.AsUTF8Unsafe());
609 policy->GrantRequestSpecificFileURL(renderer_id,
610 net::FilePathToFileURL(iter->path));
612 // If the renderer already has permission to read these paths, we don't need
613 // to re-grant them. This prevents problems with DnD for files in the CrOS
614 // file manager--the file manager already had read/write access to those
615 // directories, but dragging a file would cause the read/write access to be
616 // overwritten with read-only access, making them impossible to delete or
617 // rename until the renderer was killed.
618 if (!policy->CanReadFile(renderer_id, iter->path))
619 policy->GrantReadFile(renderer_id, iter->path);
622 storage::IsolatedContext* isolated_context =
623 storage::IsolatedContext::GetInstance();
624 DCHECK(isolated_context);
625 std::string filesystem_id = isolated_context->RegisterDraggedFileSystem(
626 files);
627 if (!filesystem_id.empty()) {
628 // Grant the permission iff the ID is valid.
629 policy->GrantReadFileSystem(renderer_id, filesystem_id);
631 filtered_data.filesystem_id = base::UTF8ToUTF16(filesystem_id);
633 storage::FileSystemContext* file_system_context =
634 BrowserContext::GetStoragePartition(GetProcess()->GetBrowserContext(),
635 GetSiteInstance())
636 ->GetFileSystemContext();
637 for (size_t i = 0; i < filtered_data.file_system_files.size(); ++i) {
638 storage::FileSystemURL file_system_url =
639 file_system_context->CrackURL(filtered_data.file_system_files[i].url);
641 std::string register_name;
642 std::string filesystem_id = isolated_context->RegisterFileSystemForPath(
643 file_system_url.type(), file_system_url.filesystem_id(),
644 file_system_url.path(), &register_name);
645 policy->GrantReadFileSystem(renderer_id, filesystem_id);
647 // Note: We are using the origin URL provided by the sender here. It may be
648 // different from the receiver's.
649 filtered_data.file_system_files[i].url =
650 GURL(storage::GetIsolatedFileSystemRootURIString(
651 file_system_url.origin(), filesystem_id, std::string())
652 .append(register_name));
655 Send(new DragMsg_TargetDragEnter(GetRoutingID(), filtered_data, client_pt,
656 screen_pt, operations_allowed,
657 key_modifiers));
660 void RenderViewHostImpl::DragTargetDragOver(
661 const gfx::Point& client_pt,
662 const gfx::Point& screen_pt,
663 WebDragOperationsMask operations_allowed,
664 int key_modifiers) {
665 Send(new DragMsg_TargetDragOver(GetRoutingID(), client_pt, screen_pt,
666 operations_allowed, key_modifiers));
669 void RenderViewHostImpl::DragTargetDragLeave() {
670 Send(new DragMsg_TargetDragLeave(GetRoutingID()));
673 void RenderViewHostImpl::DragTargetDrop(
674 const gfx::Point& client_pt,
675 const gfx::Point& screen_pt,
676 int key_modifiers) {
677 Send(new DragMsg_TargetDrop(GetRoutingID(), client_pt, screen_pt,
678 key_modifiers));
681 void RenderViewHostImpl::DragSourceEndedAt(
682 int client_x, int client_y, int screen_x, int screen_y,
683 WebDragOperation operation) {
684 Send(new DragMsg_SourceEnded(GetRoutingID(),
685 gfx::Point(client_x, client_y),
686 gfx::Point(screen_x, screen_y),
687 operation));
690 void RenderViewHostImpl::DragSourceSystemDragEnded() {
691 Send(new DragMsg_SourceSystemDragEnded(GetRoutingID()));
694 RenderFrameHost* RenderViewHostImpl::GetMainFrame() {
695 return RenderFrameHost::FromID(GetProcess()->GetID(), main_frame_routing_id_);
698 void RenderViewHostImpl::AllowBindings(int bindings_flags) {
699 // Never grant any bindings to browser plugin guests.
700 if (GetProcess()->IsIsolatedGuest()) {
701 NOTREACHED() << "Never grant bindings to a guest process.";
702 return;
705 // Ensure we aren't granting WebUI bindings to a process that has already
706 // been used for non-privileged views.
707 if (bindings_flags & BINDINGS_POLICY_WEB_UI &&
708 GetProcess()->HasConnection() &&
709 !ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
710 GetProcess()->GetID())) {
711 // This process has no bindings yet. Make sure it does not have more
712 // than this single active view.
713 RenderProcessHostImpl* process =
714 static_cast<RenderProcessHostImpl*>(GetProcess());
715 // --single-process only has one renderer.
716 if (process->GetActiveViewCount() > 1 &&
717 !base::CommandLine::ForCurrentProcess()->HasSwitch(
718 switches::kSingleProcess))
719 return;
722 if (bindings_flags & BINDINGS_POLICY_WEB_UI) {
723 ChildProcessSecurityPolicyImpl::GetInstance()->GrantWebUIBindings(
724 GetProcess()->GetID());
727 enabled_bindings_ |= bindings_flags;
728 if (renderer_initialized_)
729 Send(new ViewMsg_AllowBindings(GetRoutingID(), enabled_bindings_));
732 int RenderViewHostImpl::GetEnabledBindings() const {
733 return enabled_bindings_;
736 void RenderViewHostImpl::SetWebUIProperty(const std::string& name,
737 const std::string& value) {
738 // This is a sanity check before telling the renderer to enable the property.
739 // It could lie and send the corresponding IPC messages anyway, but we will
740 // not act on them if enabled_bindings_ doesn't agree. If we get here without
741 // WebUI bindings, kill the renderer process.
742 if (enabled_bindings_ & BINDINGS_POLICY_WEB_UI) {
743 Send(new ViewMsg_SetWebUIProperty(GetRoutingID(), name, value));
744 } else {
745 RecordAction(
746 base::UserMetricsAction("BindingsMismatchTerminate_RVH_WebUI"));
747 base::KillProcess(
748 GetProcess()->GetHandle(), content::RESULT_CODE_KILLED, false);
752 void RenderViewHostImpl::GotFocus() {
753 RenderWidgetHostImpl::GotFocus(); // Notifies the renderer it got focus.
755 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
756 if (view)
757 view->GotFocus();
760 void RenderViewHostImpl::LostCapture() {
761 RenderWidgetHostImpl::LostCapture();
762 delegate_->LostCapture();
765 void RenderViewHostImpl::LostMouseLock() {
766 RenderWidgetHostImpl::LostMouseLock();
767 delegate_->LostMouseLock();
770 void RenderViewHostImpl::SetInitialFocus(bool reverse) {
771 Send(new ViewMsg_SetInitialFocus(GetRoutingID(), reverse));
774 void RenderViewHostImpl::FilesSelectedInChooser(
775 const std::vector<content::FileChooserFileInfo>& files,
776 FileChooserParams::Mode permissions) {
777 storage::FileSystemContext* const file_system_context =
778 BrowserContext::GetStoragePartition(GetProcess()->GetBrowserContext(),
779 GetSiteInstance())
780 ->GetFileSystemContext();
781 // Grant the security access requested to the given files.
782 for (size_t i = 0; i < files.size(); ++i) {
783 const content::FileChooserFileInfo& file = files[i];
784 if (permissions == FileChooserParams::Save) {
785 ChildProcessSecurityPolicyImpl::GetInstance()->GrantCreateReadWriteFile(
786 GetProcess()->GetID(), file.file_path);
787 } else {
788 ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
789 GetProcess()->GetID(), file.file_path);
791 if (file.file_system_url.is_valid()) {
792 ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFileSystem(
793 GetProcess()->GetID(),
794 file_system_context->CrackURL(file.file_system_url)
795 .mount_filesystem_id());
798 Send(new ViewMsg_RunFileChooserResponse(GetRoutingID(), files));
801 void RenderViewHostImpl::DirectoryEnumerationFinished(
802 int request_id,
803 const std::vector<base::FilePath>& files) {
804 // Grant the security access requested to the given files.
805 for (std::vector<base::FilePath>::const_iterator file = files.begin();
806 file != files.end(); ++file) {
807 ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
808 GetProcess()->GetID(), *file);
810 Send(new ViewMsg_EnumerateDirectoryResponse(GetRoutingID(),
811 request_id,
812 files));
815 void RenderViewHostImpl::SetIsLoading(bool is_loading) {
816 if (ResourceDispatcherHostImpl::Get()) {
817 BrowserThread::PostTask(
818 BrowserThread::IO,
819 FROM_HERE,
820 base::Bind(&ResourceDispatcherHostImpl::OnRenderViewHostSetIsLoading,
821 base::Unretained(ResourceDispatcherHostImpl::Get()),
822 GetProcess()->GetID(),
823 GetRoutingID(),
824 is_loading));
826 RenderWidgetHostImpl::SetIsLoading(is_loading);
829 void RenderViewHostImpl::LoadStateChanged(
830 const GURL& url,
831 const net::LoadStateWithParam& load_state,
832 uint64 upload_position,
833 uint64 upload_size) {
834 delegate_->LoadStateChanged(url, load_state, upload_position, upload_size);
837 bool RenderViewHostImpl::SuddenTerminationAllowed() const {
838 return sudden_termination_allowed_ ||
839 GetProcess()->SuddenTerminationAllowed();
842 ///////////////////////////////////////////////////////////////////////////////
843 // RenderViewHostImpl, IPC message handlers:
845 bool RenderViewHostImpl::OnMessageReceived(const IPC::Message& msg) {
846 if (!BrowserMessageFilter::CheckCanDispatchOnUI(msg, this))
847 return true;
849 // Filter out most IPC messages if this renderer is swapped out.
850 // We still want to handle certain ACKs to keep our state consistent.
851 if (is_swapped_out_) {
852 if (!SwappedOutMessages::CanHandleWhileSwappedOut(msg)) {
853 // If this is a synchronous message and we decided not to handle it,
854 // we must send an error reply, or else the renderer will be stuck
855 // and won't respond to future requests.
856 if (msg.is_sync()) {
857 IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
858 reply->set_reply_error();
859 Send(reply);
861 // Don't continue looking for someone to handle it.
862 return true;
866 if (delegate_->OnMessageReceived(this, msg))
867 return true;
869 bool handled = true;
870 IPC_BEGIN_MESSAGE_MAP(RenderViewHostImpl, msg)
871 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowView, OnShowView)
872 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowWidget, OnShowWidget)
873 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowFullscreenWidget,
874 OnShowFullscreenWidget)
875 IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_RunModal, OnRunModal)
876 IPC_MESSAGE_HANDLER(ViewHostMsg_RenderViewReady, OnRenderViewReady)
877 IPC_MESSAGE_HANDLER(ViewHostMsg_RenderProcessGone, OnRenderProcessGone)
878 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateState, OnUpdateState)
879 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateTargetURL, OnUpdateTargetURL)
880 IPC_MESSAGE_HANDLER(ViewHostMsg_Close, OnClose)
881 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestMove, OnRequestMove)
882 IPC_MESSAGE_HANDLER(ViewHostMsg_DocumentAvailableInMainFrame,
883 OnDocumentAvailableInMainFrame)
884 IPC_MESSAGE_HANDLER(ViewHostMsg_ToggleFullscreen, OnToggleFullscreen)
885 IPC_MESSAGE_HANDLER(ViewHostMsg_DidContentsPreferredSizeChange,
886 OnDidContentsPreferredSizeChange)
887 IPC_MESSAGE_HANDLER(ViewHostMsg_RouteCloseEvent,
888 OnRouteCloseEvent)
889 IPC_MESSAGE_HANDLER(ViewHostMsg_RouteMessageEvent, OnRouteMessageEvent)
890 IPC_MESSAGE_HANDLER(DragHostMsg_StartDragging, OnStartDragging)
891 IPC_MESSAGE_HANDLER(DragHostMsg_UpdateDragCursor, OnUpdateDragCursor)
892 IPC_MESSAGE_HANDLER(DragHostMsg_TargetDrop_ACK, OnTargetDropACK)
893 IPC_MESSAGE_HANDLER(ViewHostMsg_TakeFocus, OnTakeFocus)
894 IPC_MESSAGE_HANDLER(ViewHostMsg_FocusedNodeChanged, OnFocusedNodeChanged)
895 IPC_MESSAGE_HANDLER(ViewHostMsg_ClosePage_ACK, OnClosePageACK)
896 IPC_MESSAGE_HANDLER(ViewHostMsg_DidZoomURL, OnDidZoomURL)
897 IPC_MESSAGE_HANDLER(ViewHostMsg_RunFileChooser, OnRunFileChooser)
898 IPC_MESSAGE_HANDLER(ViewHostMsg_FocusedNodeTouched, OnFocusedNodeTouched)
899 // Have the super handle all other messages.
900 IPC_MESSAGE_UNHANDLED(
901 handled = RenderWidgetHostImpl::OnMessageReceived(msg))
902 IPC_END_MESSAGE_MAP()
904 return handled;
907 void RenderViewHostImpl::Init() {
908 RenderWidgetHostImpl::Init();
911 void RenderViewHostImpl::Shutdown() {
912 // If we are being run modally (see RunModal), then we need to cleanup.
913 if (run_modal_reply_msg_) {
914 Send(run_modal_reply_msg_);
915 run_modal_reply_msg_ = NULL;
916 RenderViewHostImpl* opener =
917 RenderViewHostImpl::FromID(GetProcess()->GetID(), run_modal_opener_id_);
918 if (opener) {
919 opener->StartHangMonitorTimeout(TimeDelta::FromMilliseconds(
920 hung_renderer_delay_ms_));
921 // Balance out the decrement when we got created.
922 opener->increment_in_flight_event_count();
924 run_modal_opener_id_ = MSG_ROUTING_NONE;
927 // We can't release the SessionStorageNamespace until our peer
928 // in the renderer has wound down.
929 if (GetProcess()->HasConnection()) {
930 RenderProcessHostImpl::ReleaseOnCloseACK(
931 GetProcess(),
932 delegate_->GetSessionStorageNamespaceMap(),
933 GetRoutingID());
936 RenderWidgetHostImpl::Shutdown();
939 void RenderViewHostImpl::WasHidden() {
940 if (ResourceDispatcherHostImpl::Get()) {
941 BrowserThread::PostTask(
942 BrowserThread::IO, FROM_HERE,
943 base::Bind(&ResourceDispatcherHostImpl::OnRenderViewHostWasHidden,
944 base::Unretained(ResourceDispatcherHostImpl::Get()),
945 GetProcess()->GetID(), GetRoutingID()));
948 RenderWidgetHostImpl::WasHidden();
951 void RenderViewHostImpl::WasShown(const ui::LatencyInfo& latency_info) {
952 if (ResourceDispatcherHostImpl::Get()) {
953 BrowserThread::PostTask(
954 BrowserThread::IO, FROM_HERE,
955 base::Bind(&ResourceDispatcherHostImpl::OnRenderViewHostWasShown,
956 base::Unretained(ResourceDispatcherHostImpl::Get()),
957 GetProcess()->GetID(), GetRoutingID()));
960 RenderWidgetHostImpl::WasShown(latency_info);
963 bool RenderViewHostImpl::IsRenderView() const {
964 return true;
967 void RenderViewHostImpl::CreateNewWindow(
968 int route_id,
969 int main_frame_route_id,
970 const ViewHostMsg_CreateWindow_Params& params,
971 SessionStorageNamespace* session_storage_namespace) {
972 ViewHostMsg_CreateWindow_Params validated_params(params);
973 GetProcess()->FilterURL(false, &validated_params.target_url);
974 GetProcess()->FilterURL(false, &validated_params.opener_url);
975 GetProcess()->FilterURL(true, &validated_params.opener_security_origin);
977 delegate_->CreateNewWindow(
978 GetProcess()->GetID(), route_id, main_frame_route_id, validated_params,
979 session_storage_namespace);
982 void RenderViewHostImpl::CreateNewWidget(int route_id,
983 blink::WebPopupType popup_type) {
984 delegate_->CreateNewWidget(GetProcess()->GetID(), route_id, popup_type);
987 void RenderViewHostImpl::CreateNewFullscreenWidget(int route_id) {
988 delegate_->CreateNewFullscreenWidget(GetProcess()->GetID(), route_id);
991 void RenderViewHostImpl::OnShowView(int route_id,
992 WindowOpenDisposition disposition,
993 const gfx::Rect& initial_pos,
994 bool user_gesture) {
995 if (is_active_) {
996 delegate_->ShowCreatedWindow(
997 route_id, disposition, initial_pos, user_gesture);
999 Send(new ViewMsg_Move_ACK(route_id));
1002 void RenderViewHostImpl::OnShowWidget(int route_id,
1003 const gfx::Rect& initial_pos) {
1004 if (is_active_)
1005 delegate_->ShowCreatedWidget(route_id, initial_pos);
1006 Send(new ViewMsg_Move_ACK(route_id));
1009 void RenderViewHostImpl::OnShowFullscreenWidget(int route_id) {
1010 if (is_active_)
1011 delegate_->ShowCreatedFullscreenWidget(route_id);
1012 Send(new ViewMsg_Move_ACK(route_id));
1015 void RenderViewHostImpl::OnRunModal(int opener_id, IPC::Message* reply_msg) {
1016 DCHECK(!run_modal_reply_msg_);
1017 run_modal_reply_msg_ = reply_msg;
1018 run_modal_opener_id_ = opener_id;
1020 RecordAction(base::UserMetricsAction("ShowModalDialog"));
1022 RenderViewHostImpl* opener =
1023 RenderViewHostImpl::FromID(GetProcess()->GetID(), run_modal_opener_id_);
1024 if (opener) {
1025 opener->StopHangMonitorTimeout();
1026 // The ack for the mouse down won't come until the dialog closes, so fake it
1027 // so that we don't get a timeout.
1028 opener->decrement_in_flight_event_count();
1031 // TODO(darin): Bug 1107929: Need to inform our delegate to show this view in
1032 // an app-modal fashion.
1035 void RenderViewHostImpl::OnRenderViewReady() {
1036 render_view_termination_status_ = base::TERMINATION_STATUS_STILL_RUNNING;
1037 SendScreenRects();
1038 WasResized();
1039 delegate_->RenderViewReady(this);
1042 void RenderViewHostImpl::OnRenderProcessGone(int status, int exit_code) {
1043 // Keep the termination status so we can get at it later when we
1044 // need to know why it died.
1045 render_view_termination_status_ =
1046 static_cast<base::TerminationStatus>(status);
1048 // Reset frame tree state associated with this process. This must happen
1049 // before RenderViewTerminated because observers expect the subframes of any
1050 // affected frames to be cleared first.
1051 delegate_->GetFrameTree()->RenderProcessGone(this);
1053 // Our base class RenderWidgetHost needs to reset some stuff.
1054 RendererExited(render_view_termination_status_, exit_code);
1056 delegate_->RenderViewTerminated(this,
1057 static_cast<base::TerminationStatus>(status),
1058 exit_code);
1061 void RenderViewHostImpl::OnUpdateState(int32 page_id, const PageState& state) {
1062 // If the following DCHECK fails, you have encountered a tricky edge-case that
1063 // has evaded reproduction for a very long time. Please report what you were
1064 // doing on http://crbug.com/407376, whether or not you can reproduce the
1065 // failure.
1066 DCHECK_EQ(page_id, page_id_);
1068 // Without this check, the renderer can trick the browser into using
1069 // filenames it can't access in a future session restore.
1070 if (!CanAccessFilesOfPageState(state)) {
1071 GetProcess()->ReceivedBadMessage();
1072 return;
1075 delegate_->UpdateState(this, page_id, state);
1078 void RenderViewHostImpl::OnUpdateTargetURL(const GURL& url) {
1079 if (is_active_)
1080 delegate_->UpdateTargetURL(url);
1082 // Send a notification back to the renderer that we are ready to
1083 // receive more target urls.
1084 Send(new ViewMsg_UpdateTargetURL_ACK(GetRoutingID()));
1087 void RenderViewHostImpl::OnClose() {
1088 // If the renderer is telling us to close, it has already run the unload
1089 // events, and we can take the fast path.
1090 ClosePageIgnoringUnloadEvents();
1093 void RenderViewHostImpl::OnRequestMove(const gfx::Rect& pos) {
1094 if (is_active_)
1095 delegate_->RequestMove(pos);
1096 Send(new ViewMsg_Move_ACK(GetRoutingID()));
1099 void RenderViewHostImpl::OnDocumentAvailableInMainFrame(
1100 bool uses_temporary_zoom_level) {
1101 delegate_->DocumentAvailableInMainFrame(this);
1103 if (!uses_temporary_zoom_level)
1104 return;
1106 HostZoomMapImpl* host_zoom_map =
1107 static_cast<HostZoomMapImpl*>(HostZoomMap::GetDefaultForBrowserContext(
1108 GetProcess()->GetBrowserContext()));
1109 host_zoom_map->SetTemporaryZoomLevel(GetProcess()->GetID(),
1110 GetRoutingID(),
1111 host_zoom_map->GetDefaultZoomLevel());
1114 void RenderViewHostImpl::OnToggleFullscreen(bool enter_fullscreen) {
1115 DCHECK_CURRENTLY_ON(BrowserThread::UI);
1116 delegate_->ToggleFullscreenMode(enter_fullscreen);
1117 // We need to notify the contents that its fullscreen state has changed. This
1118 // is done as part of the resize message.
1119 WasResized();
1122 void RenderViewHostImpl::OnDidContentsPreferredSizeChange(
1123 const gfx::Size& new_size) {
1124 delegate_->UpdatePreferredSize(new_size);
1127 void RenderViewHostImpl::OnRenderAutoResized(const gfx::Size& new_size) {
1128 delegate_->ResizeDueToAutoResize(new_size);
1131 void RenderViewHostImpl::OnRouteCloseEvent() {
1132 // Have the delegate route this to the active RenderViewHost.
1133 delegate_->RouteCloseEvent(this);
1136 void RenderViewHostImpl::OnRouteMessageEvent(
1137 const ViewMsg_PostMessage_Params& params) {
1138 // Give to the delegate to route to the active RenderViewHost.
1139 delegate_->RouteMessageEvent(this, params);
1142 void RenderViewHostImpl::OnStartDragging(
1143 const DropData& drop_data,
1144 WebDragOperationsMask drag_operations_mask,
1145 const SkBitmap& bitmap,
1146 const gfx::Vector2d& bitmap_offset_in_dip,
1147 const DragEventSourceInfo& event_info) {
1148 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1149 if (!view)
1150 return;
1152 DropData filtered_data(drop_data);
1153 RenderProcessHost* process = GetProcess();
1154 ChildProcessSecurityPolicyImpl* policy =
1155 ChildProcessSecurityPolicyImpl::GetInstance();
1157 // Allow drag of Javascript URLs to enable bookmarklet drag to bookmark bar.
1158 if (!filtered_data.url.SchemeIs(url::kJavaScriptScheme))
1159 process->FilterURL(true, &filtered_data.url);
1160 process->FilterURL(false, &filtered_data.html_base_url);
1161 // Filter out any paths that the renderer didn't have access to. This prevents
1162 // the following attack on a malicious renderer:
1163 // 1. StartDragging IPC sent with renderer-specified filesystem paths that it
1164 // doesn't have read permissions for.
1165 // 2. We initiate a native DnD operation.
1166 // 3. DnD operation immediately ends since mouse is not held down. DnD events
1167 // still fire though, which causes read permissions to be granted to the
1168 // renderer for any file paths in the drop.
1169 filtered_data.filenames.clear();
1170 for (std::vector<ui::FileInfo>::const_iterator it =
1171 drop_data.filenames.begin();
1172 it != drop_data.filenames.end();
1173 ++it) {
1174 if (policy->CanReadFile(GetProcess()->GetID(), it->path))
1175 filtered_data.filenames.push_back(*it);
1178 storage::FileSystemContext* file_system_context =
1179 BrowserContext::GetStoragePartition(GetProcess()->GetBrowserContext(),
1180 GetSiteInstance())
1181 ->GetFileSystemContext();
1182 filtered_data.file_system_files.clear();
1183 for (size_t i = 0; i < drop_data.file_system_files.size(); ++i) {
1184 storage::FileSystemURL file_system_url =
1185 file_system_context->CrackURL(drop_data.file_system_files[i].url);
1186 if (policy->CanReadFileSystemFile(GetProcess()->GetID(), file_system_url))
1187 filtered_data.file_system_files.push_back(drop_data.file_system_files[i]);
1190 float scale = GetScaleFactorForView(GetView());
1191 gfx::ImageSkia image(gfx::ImageSkiaRep(bitmap, scale));
1192 view->StartDragging(filtered_data, drag_operations_mask, image,
1193 bitmap_offset_in_dip, event_info);
1196 void RenderViewHostImpl::OnUpdateDragCursor(WebDragOperation current_op) {
1197 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1198 if (view)
1199 view->UpdateDragCursor(current_op);
1202 void RenderViewHostImpl::OnTargetDropACK() {
1203 NotificationService::current()->Notify(
1204 NOTIFICATION_RENDER_VIEW_HOST_DID_RECEIVE_DRAG_TARGET_DROP_ACK,
1205 Source<RenderViewHost>(this),
1206 NotificationService::NoDetails());
1209 void RenderViewHostImpl::OnTakeFocus(bool reverse) {
1210 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1211 if (view)
1212 view->TakeFocus(reverse);
1215 void RenderViewHostImpl::OnFocusedNodeChanged(bool is_editable_node) {
1216 is_focused_element_editable_ = is_editable_node;
1217 if (view_)
1218 view_->FocusedNodeChanged(is_editable_node);
1219 #if defined(OS_WIN)
1220 if (!is_editable_node && virtual_keyboard_requested_) {
1221 virtual_keyboard_requested_ = false;
1222 delegate_->SetIsVirtualKeyboardRequested(false);
1223 BrowserThread::PostDelayedTask(
1224 BrowserThread::UI, FROM_HERE,
1225 base::Bind(base::IgnoreResult(&DismissVirtualKeyboardTask)),
1226 TimeDelta::FromMilliseconds(kVirtualKeyboardDisplayWaitTimeoutMs));
1228 #endif
1229 NotificationService::current()->Notify(
1230 NOTIFICATION_FOCUS_CHANGED_IN_PAGE,
1231 Source<RenderViewHost>(this),
1232 Details<const bool>(&is_editable_node));
1235 void RenderViewHostImpl::OnUserGesture() {
1236 delegate_->OnUserGesture();
1239 void RenderViewHostImpl::OnClosePageACK() {
1240 decrement_in_flight_event_count();
1241 ClosePageIgnoringUnloadEvents();
1244 void RenderViewHostImpl::NotifyRendererUnresponsive() {
1245 delegate_->RendererUnresponsive(this);
1248 void RenderViewHostImpl::NotifyRendererResponsive() {
1249 delegate_->RendererResponsive(this);
1252 void RenderViewHostImpl::RequestToLockMouse(bool user_gesture,
1253 bool last_unlocked_by_target) {
1254 delegate_->RequestToLockMouse(user_gesture, last_unlocked_by_target);
1257 bool RenderViewHostImpl::IsFullscreen() const {
1258 return delegate_->IsFullscreenForCurrentTab();
1261 void RenderViewHostImpl::OnFocus() {
1262 // Note: We allow focus and blur from swapped out RenderViewHosts, even when
1263 // the active RenderViewHost is in a different BrowsingInstance (e.g., WebUI).
1264 delegate_->Activate();
1267 void RenderViewHostImpl::OnBlur() {
1268 delegate_->Deactivate();
1271 gfx::Rect RenderViewHostImpl::GetRootWindowResizerRect() const {
1272 return delegate_->GetRootWindowResizerRect();
1275 void RenderViewHostImpl::ForwardMouseEvent(
1276 const blink::WebMouseEvent& mouse_event) {
1278 // We make a copy of the mouse event because
1279 // RenderWidgetHost::ForwardMouseEvent will delete |mouse_event|.
1280 blink::WebMouseEvent event_copy(mouse_event);
1281 RenderWidgetHostImpl::ForwardMouseEvent(event_copy);
1283 switch (event_copy.type) {
1284 case WebInputEvent::MouseMove:
1285 delegate_->HandleMouseMove();
1286 break;
1287 case WebInputEvent::MouseLeave:
1288 delegate_->HandleMouseLeave();
1289 break;
1290 case WebInputEvent::MouseDown:
1291 delegate_->HandleMouseDown();
1292 break;
1293 case WebInputEvent::MouseWheel:
1294 if (ignore_input_events())
1295 delegate_->OnIgnoredUIEvent();
1296 break;
1297 case WebInputEvent::MouseUp:
1298 delegate_->HandleMouseUp();
1299 default:
1300 // For now, we don't care about the rest.
1301 break;
1305 void RenderViewHostImpl::OnPointerEventActivate() {
1306 delegate_->HandlePointerActivate();
1309 void RenderViewHostImpl::ForwardKeyboardEvent(
1310 const NativeWebKeyboardEvent& key_event) {
1311 if (ignore_input_events()) {
1312 if (key_event.type == WebInputEvent::RawKeyDown)
1313 delegate_->OnIgnoredUIEvent();
1314 return;
1316 RenderWidgetHostImpl::ForwardKeyboardEvent(key_event);
1319 void RenderViewHostImpl::OnTextSurroundingSelectionResponse(
1320 const base::string16& content,
1321 size_t start_offset,
1322 size_t end_offset) {
1323 if (!view_)
1324 return;
1325 view_->OnTextSurroundingSelectionResponse(content, start_offset, end_offset);
1328 void RenderViewHostImpl::ExitFullscreen() {
1329 RejectMouseLockOrUnlockIfNecessary();
1330 // Notify delegate_ and renderer of fullscreen state change.
1331 OnToggleFullscreen(false);
1334 WebPreferences RenderViewHostImpl::GetWebkitPreferences() {
1335 if (!web_preferences_.get()) {
1336 OnWebkitPreferencesChanged();
1338 return *web_preferences_;
1341 void RenderViewHostImpl::UpdateWebkitPreferences(const WebPreferences& prefs) {
1342 web_preferences_.reset(new WebPreferences(prefs));
1343 Send(new ViewMsg_UpdateWebPreferences(GetRoutingID(), prefs));
1346 void RenderViewHostImpl::OnWebkitPreferencesChanged() {
1347 // This is defensive code to avoid infinite loops due to code run inside
1348 // UpdateWebkitPreferences() accidentally updating more preferences and thus
1349 // calling back into this code. See crbug.com/398751 for one past example.
1350 if (updating_web_preferences_)
1351 return;
1352 updating_web_preferences_ = true;
1353 UpdateWebkitPreferences(delegate_->ComputeWebkitPrefs());
1354 updating_web_preferences_ = false;
1357 void RenderViewHostImpl::GetAudioOutputControllers(
1358 const GetAudioOutputControllersCallback& callback) const {
1359 scoped_refptr<AudioRendererHost> audio_host =
1360 static_cast<RenderProcessHostImpl*>(GetProcess())->audio_renderer_host();
1361 audio_host->GetOutputControllers(GetRoutingID(), callback);
1364 void RenderViewHostImpl::ClearFocusedElement() {
1365 is_focused_element_editable_ = false;
1366 Send(new ViewMsg_ClearFocusedElement(GetRoutingID()));
1369 bool RenderViewHostImpl::IsFocusedElementEditable() {
1370 return is_focused_element_editable_;
1373 void RenderViewHostImpl::Zoom(PageZoom zoom) {
1374 Send(new ViewMsg_Zoom(GetRoutingID(), zoom));
1377 void RenderViewHostImpl::DisableScrollbarsForThreshold(const gfx::Size& size) {
1378 Send(new ViewMsg_DisableScrollbarsForSmallWindows(GetRoutingID(), size));
1381 void RenderViewHostImpl::EnablePreferredSizeMode() {
1382 Send(new ViewMsg_EnablePreferredSizeChangedMode(GetRoutingID()));
1385 void RenderViewHostImpl::EnableAutoResize(const gfx::Size& min_size,
1386 const gfx::Size& max_size) {
1387 SetAutoResize(true, min_size, max_size);
1388 Send(new ViewMsg_EnableAutoResize(GetRoutingID(), min_size, max_size));
1391 void RenderViewHostImpl::DisableAutoResize(const gfx::Size& new_size) {
1392 SetAutoResize(false, gfx::Size(), gfx::Size());
1393 Send(new ViewMsg_DisableAutoResize(GetRoutingID(), new_size));
1394 if (!new_size.IsEmpty())
1395 GetView()->SetSize(new_size);
1398 void RenderViewHostImpl::CopyImageAt(int x, int y) {
1399 Send(new ViewMsg_CopyImageAt(GetRoutingID(), x, y));
1402 void RenderViewHostImpl::SaveImageAt(int x, int y) {
1403 Send(new ViewMsg_SaveImageAt(GetRoutingID(), x, y));
1406 void RenderViewHostImpl::ExecuteMediaPlayerActionAtLocation(
1407 const gfx::Point& location, const blink::WebMediaPlayerAction& action) {
1408 Send(new ViewMsg_MediaPlayerActionAt(GetRoutingID(), location, action));
1411 void RenderViewHostImpl::ExecutePluginActionAtLocation(
1412 const gfx::Point& location, const blink::WebPluginAction& action) {
1413 Send(new ViewMsg_PluginActionAt(GetRoutingID(), location, action));
1416 void RenderViewHostImpl::NotifyMoveOrResizeStarted() {
1417 Send(new ViewMsg_MoveOrResizeStarted(GetRoutingID()));
1420 void RenderViewHostImpl::OnDidZoomURL(double zoom_level,
1421 const GURL& url) {
1422 HostZoomMapImpl* host_zoom_map =
1423 static_cast<HostZoomMapImpl*>(HostZoomMap::GetDefaultForBrowserContext(
1424 GetProcess()->GetBrowserContext()));
1426 host_zoom_map->SetZoomLevelForView(GetProcess()->GetID(),
1427 GetRoutingID(),
1428 zoom_level,
1429 net::GetHostOrSpecFromURL(url));
1432 void RenderViewHostImpl::OnRunFileChooser(const FileChooserParams& params) {
1433 delegate_->RunFileChooser(this, params);
1436 void RenderViewHostImpl::OnFocusedNodeTouched(bool editable) {
1437 #if defined(OS_WIN)
1438 if (editable) {
1439 virtual_keyboard_requested_ = base::win::DisplayVirtualKeyboard();
1440 delegate_->SetIsVirtualKeyboardRequested(true);
1441 } else {
1442 virtual_keyboard_requested_ = false;
1443 delegate_->SetIsVirtualKeyboardRequested(false);
1444 base::win::DismissVirtualKeyboard();
1446 #endif
1449 bool RenderViewHostImpl::CanAccessFilesOfPageState(
1450 const PageState& state) const {
1451 ChildProcessSecurityPolicyImpl* policy =
1452 ChildProcessSecurityPolicyImpl::GetInstance();
1454 const std::vector<base::FilePath>& file_paths = state.GetReferencedFiles();
1455 for (std::vector<base::FilePath>::const_iterator file = file_paths.begin();
1456 file != file_paths.end(); ++file) {
1457 if (!policy->CanReadFile(GetProcess()->GetID(), *file))
1458 return false;
1460 return true;
1463 void RenderViewHostImpl::AttachToFrameTree() {
1464 FrameTree* frame_tree = delegate_->GetFrameTree();
1466 frame_tree->ResetForMainFrameSwap();
1469 void RenderViewHostImpl::SelectWordAroundCaret() {
1470 Send(new ViewMsg_SelectWordAroundCaret(GetRoutingID()));
1473 } // namespace content