Suppress sending mousedown / mouseup when in fling
[chromium-blink-merge.git] / content / browser / renderer_host / render_view_host_impl.cc
blob4b01c50c233b71de16d3d238c1a39c5be07c42d8
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/i18n/rtl.h"
13 #include "base/json/json_reader.h"
14 #include "base/json/json_writer.h"
15 #include "base/command_line.h"
16 #include "base/message_loop.h"
17 #include "base/metrics/histogram.h"
18 #include "base/stl_util.h"
19 #include "base/string_util.h"
20 #include "base/time.h"
21 #include "base/utf_string_conversions.h"
22 #include "base/values.h"
23 #include "content/browser/accessibility/browser_accessibility_state_impl.h"
24 #include "content/browser/child_process_security_policy_impl.h"
25 #include "content/browser/cross_site_request_manager.h"
26 #include "content/browser/dom_storage/session_storage_namespace_impl.h"
27 #include "content/browser/gpu/gpu_surface_tracker.h"
28 #include "content/browser/host_zoom_map_impl.h"
29 #include "content/browser/power_save_blocker.h"
30 #include "content/browser/renderer_host/dip_util.h"
31 #include "content/browser/renderer_host/render_process_host_impl.h"
32 #include "content/browser/renderer_host/render_view_host_delegate.h"
33 #include "content/common/accessibility_messages.h"
34 #include "content/common/browser_plugin_messages.h"
35 #include "content/common/content_constants_internal.h"
36 #include "content/common/desktop_notification_messages.h"
37 #include "content/common/drag_messages.h"
38 #include "content/common/inter_process_time_ticks_converter.h"
39 #include "content/common/speech_recognition_messages.h"
40 #include "content/common/swapped_out_messages.h"
41 #include "content/common/view_messages.h"
42 #include "content/port/browser/render_view_host_delegate_view.h"
43 #include "content/port/browser/render_widget_host_view_port.h"
44 #include "content/public/browser/browser_accessibility_state.h"
45 #include "content/public/browser/browser_context.h"
46 #include "content/public/browser/browser_message_filter.h"
47 #include "content/public/browser/content_browser_client.h"
48 #include "content/public/browser/dom_operation_notification_details.h"
49 #include "content/public/browser/native_web_keyboard_event.h"
50 #include "content/public/browser/notification_details.h"
51 #include "content/public/browser/notification_service.h"
52 #include "content/public/browser/notification_types.h"
53 #include "content/public/browser/render_view_host_observer.h"
54 #include "content/public/browser/user_metrics.h"
55 #include "content/public/common/bindings_policy.h"
56 #include "content/public/common/content_constants.h"
57 #include "content/public/common/content_switches.h"
58 #include "content/public/common/context_menu_params.h"
59 #include "content/public/common/context_menu_source_type.h"
60 #include "content/public/common/result_codes.h"
61 #include "content/public/common/url_constants.h"
62 #include "net/base/net_util.h"
63 #include "net/url_request/url_request_context_getter.h"
64 #include "third_party/skia/include/core/SkBitmap.h"
65 #include "ui/base/dialogs/selected_file_info.h"
66 #include "ui/gfx/image/image_skia.h"
67 #include "ui/gfx/native_widget_types.h"
68 #include "webkit/fileapi/isolated_context.h"
69 #include "webkit/glue/webdropdata.h"
70 #include "webkit/glue/webkit_glue.h"
72 #if defined(OS_WIN)
73 #include "base/win/windows_version.h"
74 #include "third_party/WebKit/Source/WebKit/chromium/public/win/WebScreenInfoFactory.h"
75 #elif defined(OS_MACOSX)
76 #include "content/browser/renderer_host/popup_menu_helper_mac.h"
77 #elif defined(OS_ANDROID)
78 #include "content/browser/android/media_player_manager_android.h"
79 #endif
81 using base::TimeDelta;
82 using WebKit::WebConsoleMessage;
83 using WebKit::WebDragOperation;
84 using WebKit::WebDragOperationNone;
85 using WebKit::WebDragOperationsMask;
86 using WebKit::WebInputEvent;
87 using WebKit::WebMediaPlayerAction;
88 using WebKit::WebPluginAction;
90 namespace content {
91 namespace {
93 // Delay to wait on closing the WebContents for a beforeunload/unload handler to
94 // fire.
95 const int kUnloadTimeoutMS = 1000;
97 // Translate a WebKit text direction into a base::i18n one.
98 base::i18n::TextDirection WebTextDirectionToChromeTextDirection(
99 WebKit::WebTextDirection dir) {
100 switch (dir) {
101 case WebKit::WebTextDirectionLeftToRight:
102 return base::i18n::LEFT_TO_RIGHT;
103 case WebKit::WebTextDirectionRightToLeft:
104 return base::i18n::RIGHT_TO_LEFT;
105 default:
106 NOTREACHED();
107 return base::i18n::UNKNOWN_DIRECTION;
111 } // namespace
113 ///////////////////////////////////////////////////////////////////////////////
114 // RenderViewHost, public:
116 // static
117 RenderViewHost* RenderViewHost::FromID(int render_process_id,
118 int render_view_id) {
119 RenderProcessHost* process = RenderProcessHost::FromID(render_process_id);
120 if (!process)
121 return NULL;
122 RenderWidgetHost* widget = process->GetRenderWidgetHostByID(render_view_id);
123 if (!widget || !widget->IsRenderView())
124 return NULL;
125 return static_cast<RenderViewHostImpl*>(RenderWidgetHostImpl::From(widget));
128 // static
129 RenderViewHost* RenderViewHost::From(RenderWidgetHost* rwh) {
130 return static_cast<RenderViewHostImpl*>(RenderWidgetHostImpl::From(rwh));
133 // static
134 void RenderViewHost::FilterURL(const RenderProcessHost* process,
135 bool empty_allowed,
136 GURL* url) {
137 RenderViewHostImpl::FilterURL(ChildProcessSecurityPolicyImpl::GetInstance(),
138 process, empty_allowed, url);
141 ///////////////////////////////////////////////////////////////////////////////
142 // RenderViewHostImpl, public:
144 // static
145 RenderViewHostImpl* RenderViewHostImpl::FromID(int render_process_id,
146 int render_view_id) {
147 return static_cast<RenderViewHostImpl*>(
148 RenderViewHost::FromID(render_process_id, render_view_id));
151 RenderViewHostImpl::RenderViewHostImpl(
152 SiteInstance* instance,
153 RenderViewHostDelegate* delegate,
154 RenderWidgetHostDelegate* widget_delegate,
155 int routing_id,
156 bool swapped_out,
157 SessionStorageNamespace* session_storage)
158 : RenderWidgetHostImpl(widget_delegate, instance->GetProcess(), routing_id),
159 delegate_(delegate),
160 instance_(static_cast<SiteInstanceImpl*>(instance)),
161 waiting_for_drag_context_response_(false),
162 enabled_bindings_(0),
163 pending_request_id_(-1),
164 navigations_suspended_(false),
165 suspended_nav_message_(NULL),
166 is_swapped_out_(swapped_out),
167 run_modal_reply_msg_(NULL),
168 run_modal_opener_id_(MSG_ROUTING_NONE),
169 is_waiting_for_beforeunload_ack_(false),
170 is_waiting_for_unload_ack_(false),
171 has_timed_out_on_unload_(false),
172 unload_ack_is_for_cross_site_transition_(false),
173 are_javascript_messages_suppressed_(false),
174 sudden_termination_allowed_(false),
175 session_storage_namespace_(
176 static_cast<SessionStorageNamespaceImpl*>(session_storage)),
177 save_accessibility_tree_for_testing_(false),
178 render_view_termination_status_(base::TERMINATION_STATUS_STILL_RUNNING) {
179 DCHECK(session_storage_namespace_);
180 DCHECK(instance_);
181 CHECK(delegate_); // http://crbug.com/82827
183 GetProcess()->EnableSendQueue();
185 GetContentClient()->browser()->RenderViewHostCreated(this);
187 NotificationService::current()->Notify(
188 NOTIFICATION_RENDER_VIEW_HOST_CREATED,
189 Source<RenderViewHost>(this),
190 NotificationService::NoDetails());
192 #if defined(OS_ANDROID)
193 media_player_manager_ = new MediaPlayerManagerAndroid(this);
194 #endif
197 RenderViewHostImpl::~RenderViewHostImpl() {
198 FOR_EACH_OBSERVER(
199 RenderViewHostObserver, observers_, RenderViewHostDestruction());
201 NotificationService::current()->Notify(
202 NOTIFICATION_RENDER_VIEW_HOST_DELETED,
203 Source<RenderViewHost>(this),
204 NotificationService::NoDetails());
206 ClearPowerSaveBlockers();
208 GetDelegate()->RenderViewDeleted(this);
210 // Be sure to clean up any leftover state from cross-site requests.
211 CrossSiteRequestManager::GetInstance()->SetHasPendingCrossSiteRequest(
212 GetProcess()->GetID(), GetRoutingID(), false);
215 RenderViewHostDelegate* RenderViewHostImpl::GetDelegate() const {
216 return delegate_;
219 SiteInstance* RenderViewHostImpl::GetSiteInstance() const {
220 return instance_;
223 bool RenderViewHostImpl::CreateRenderView(
224 const string16& frame_name,
225 int opener_route_id,
226 int32 max_page_id) {
227 DCHECK(!IsRenderViewLive()) << "Creating view twice";
229 // The process may (if we're sharing a process with another host that already
230 // initialized it) or may not (we have our own process or the old process
231 // crashed) have been initialized. Calling Init multiple times will be
232 // ignored, so this is safe.
233 if (!GetProcess()->Init())
234 return false;
235 DCHECK(GetProcess()->HasConnection());
236 DCHECK(GetProcess()->GetBrowserContext());
238 renderer_initialized_ = true;
240 GpuSurfaceTracker::Get()->SetSurfaceHandle(
241 surface_id(), GetCompositingSurface());
243 // Ensure the RenderView starts with a next_page_id larger than any existing
244 // page ID it might be asked to render.
245 int32 next_page_id = 1;
246 if (max_page_id > -1)
247 next_page_id = max_page_id + 1;
249 ViewMsg_New_Params params;
250 params.renderer_preferences =
251 delegate_->GetRendererPrefs(GetProcess()->GetBrowserContext());
252 params.web_preferences = delegate_->GetWebkitPrefs();
253 params.view_id = GetRoutingID();
254 params.surface_id = surface_id();
255 params.session_storage_namespace_id = session_storage_namespace_->id();
256 params.frame_name = frame_name;
257 // Ensure the RenderView sets its opener correctly.
258 params.opener_route_id = opener_route_id;
259 params.swapped_out = is_swapped_out_;
260 params.next_page_id = next_page_id;
261 GetWebScreenInfo(&params.screen_info);
263 params.accessibility_mode =
264 BrowserAccessibilityStateImpl::GetInstance()->GetAccessibilityMode();
266 Send(new ViewMsg_New(params));
268 // If it's enabled, tell the renderer to set up the Javascript bindings for
269 // sending messages back to the browser.
270 if (GetProcess()->IsGuest())
271 DCHECK_EQ(0, enabled_bindings_);
272 Send(new ViewMsg_AllowBindings(GetRoutingID(), enabled_bindings_));
273 // Let our delegate know that we created a RenderView.
274 delegate_->RenderViewCreated(this);
276 FOR_EACH_OBSERVER(
277 RenderViewHostObserver, observers_, RenderViewHostInitialized());
279 return true;
282 bool RenderViewHostImpl::IsRenderViewLive() const {
283 return GetProcess()->HasConnection() && renderer_initialized_;
286 void RenderViewHostImpl::SyncRendererPrefs() {
287 Send(new ViewMsg_SetRendererPrefs(GetRoutingID(),
288 delegate_->GetRendererPrefs(
289 GetProcess()->GetBrowserContext())));
292 void RenderViewHostImpl::Navigate(const ViewMsg_Navigate_Params& params) {
293 // Browser plugin guests are not allowed to navigate outside web-safe schemes,
294 // so do not grant them the ability to request additional URLs.
295 if (!GetProcess()->IsGuest()) {
296 ChildProcessSecurityPolicyImpl::GetInstance()->GrantRequestURL(
297 GetProcess()->GetID(), params.url);
298 if (params.url.SchemeIs(chrome::kDataScheme) &&
299 params.base_url_for_data_url.SchemeIs(chrome::kFileScheme)) {
300 // If 'data:' is used, and we have a 'file:' base url, grant access to
301 // local files.
302 ChildProcessSecurityPolicyImpl::GetInstance()->GrantRequestURL(
303 GetProcess()->GetID(), params.base_url_for_data_url);
307 ViewMsg_Navigate* nav_message = new ViewMsg_Navigate(GetRoutingID(), params);
309 // Only send the message if we aren't suspended at the start of a cross-site
310 // request.
311 if (navigations_suspended_) {
312 // Shouldn't be possible to have a second navigation while suspended, since
313 // navigations will only be suspended during a cross-site request. If a
314 // second navigation occurs, WebContentsImpl will cancel this pending RVH
315 // create a new pending RVH.
316 DCHECK(!suspended_nav_message_.get());
317 suspended_nav_message_.reset(nav_message);
318 } else {
319 // Get back to a clean state, in case we start a new navigation without
320 // completing a RVH swap or unload handler.
321 SetSwappedOut(false);
323 Send(nav_message);
326 // Force the throbber to start. We do this because WebKit's "started
327 // loading" message will be received asynchronously from the UI of the
328 // browser. But we want to keep the throbber in sync with what's happening
329 // in the UI. For example, we want to start throbbing immediately when the
330 // user naivgates even if the renderer is delayed. There is also an issue
331 // with the throbber starting because the WebUI (which controls whether the
332 // favicon is displayed) happens synchronously. If the start loading
333 // messages was asynchronous, then the default favicon would flash in.
335 // WebKit doesn't send throb notifications for JavaScript URLs, so we
336 // don't want to either.
337 if (!params.url.SchemeIs(chrome::kJavaScriptScheme))
338 delegate_->DidStartLoading(this);
340 FOR_EACH_OBSERVER(RenderViewHostObserver, observers_, Navigate(params.url));
343 void RenderViewHostImpl::NavigateToURL(const GURL& url) {
344 ViewMsg_Navigate_Params params;
345 params.page_id = -1;
346 params.pending_history_list_offset = -1;
347 params.current_history_list_offset = -1;
348 params.current_history_list_length = 0;
349 params.url = url;
350 params.transition = PAGE_TRANSITION_LINK;
351 params.navigation_type = ViewMsg_Navigate_Type::NORMAL;
352 Navigate(params);
355 void RenderViewHostImpl::SetNavigationsSuspended(bool suspend) {
356 // This should only be called to toggle the state.
357 DCHECK(navigations_suspended_ != suspend);
359 navigations_suspended_ = suspend;
360 if (!suspend && suspended_nav_message_.get()) {
361 // There's a navigation message waiting to be sent. Now that we're not
362 // suspended anymore, resume navigation by sending it. If we were swapped
363 // out, we should also stop filtering out the IPC messages now.
364 SetSwappedOut(false);
366 Send(suspended_nav_message_.release());
370 void RenderViewHostImpl::CancelSuspendedNavigations() {
371 // Clear any state if a pending navigation is canceled or pre-empted.
372 if (suspended_nav_message_.get())
373 suspended_nav_message_.reset();
374 navigations_suspended_ = false;
377 void RenderViewHostImpl::SetNavigationStartTime(
378 const base::TimeTicks& navigation_start) {
379 Send(new ViewMsg_SetNavigationStartTime(GetRoutingID(), navigation_start));
382 void RenderViewHostImpl::FirePageBeforeUnload(bool for_cross_site_transition) {
383 if (!IsRenderViewLive()) {
384 // This RenderViewHostImpl doesn't have a live renderer, so just
385 // skip running the onbeforeunload handler.
386 is_waiting_for_beforeunload_ack_ = true; // Checked by OnMsgShouldCloseACK.
387 unload_ack_is_for_cross_site_transition_ = for_cross_site_transition;
388 base::TimeTicks now = base::TimeTicks::Now();
389 OnMsgShouldCloseACK(true, now, now);
390 return;
393 // This may be called more than once (if the user clicks the tab close button
394 // several times, or if she clicks the tab close button then the browser close
395 // button), and we only send the message once.
396 if (is_waiting_for_beforeunload_ack_) {
397 // Some of our close messages could be for the tab, others for cross-site
398 // transitions. We always want to think it's for closing the tab if any
399 // of the messages were, since otherwise it might be impossible to close
400 // (if there was a cross-site "close" request pending when the user clicked
401 // the close button). We want to keep the "for cross site" flag only if
402 // both the old and the new ones are also for cross site.
403 unload_ack_is_for_cross_site_transition_ =
404 unload_ack_is_for_cross_site_transition_ && for_cross_site_transition;
405 } else {
406 // Start the hang monitor in case the renderer hangs in the beforeunload
407 // handler.
408 is_waiting_for_beforeunload_ack_ = true;
409 unload_ack_is_for_cross_site_transition_ = for_cross_site_transition;
410 // Increment the in-flight event count, to ensure that input events won't
411 // cancel the timeout timer.
412 increment_in_flight_event_count();
413 StartHangMonitorTimeout(TimeDelta::FromMilliseconds(kUnloadTimeoutMS));
414 send_should_close_start_time_ = base::TimeTicks::Now();
415 Send(new ViewMsg_ShouldClose(GetRoutingID()));
419 void RenderViewHostImpl::SwapOut(int new_render_process_host_id,
420 int new_request_id) {
421 // This will be set back to false in OnSwapOutACK, just before we replace
422 // this RVH with the pending RVH.
423 is_waiting_for_unload_ack_ = true;
424 // Start the hang monitor in case the renderer hangs in the unload handler.
425 // Increment the in-flight event count, to ensure that input events won't
426 // cancel the timeout timer.
427 increment_in_flight_event_count();
428 StartHangMonitorTimeout(TimeDelta::FromMilliseconds(kUnloadTimeoutMS));
430 ViewMsg_SwapOut_Params params;
431 params.closing_process_id = GetProcess()->GetID();
432 params.closing_route_id = GetRoutingID();
433 params.new_render_process_host_id = new_render_process_host_id;
434 params.new_request_id = new_request_id;
435 if (IsRenderViewLive()) {
436 Send(new ViewMsg_SwapOut(GetRoutingID(), params));
437 } else {
438 // This RenderViewHost doesn't have a live renderer, so just skip the unload
439 // event. We must notify the ResourceDispatcherHost on the IO thread,
440 // which we will do through the RenderProcessHost's widget helper.
441 GetProcess()->SimulateSwapOutACK(params);
445 void RenderViewHostImpl::OnSwapOutACK(bool timed_out) {
446 // Stop the hang monitor now that the unload handler has finished.
447 decrement_in_flight_event_count();
448 StopHangMonitorTimeout();
449 is_waiting_for_unload_ack_ = false;
450 has_timed_out_on_unload_ = timed_out;
451 delegate_->SwappedOut(this);
454 void RenderViewHostImpl::WasSwappedOut() {
455 // Don't bother reporting hung state anymore.
456 StopHangMonitorTimeout();
458 // If we have timed out on running the unload handler, we consider
459 // the process hung and we should terminate it if there are no other tabs
460 // using the process. If there are other views using this process, the
461 // unresponsive renderer timeout will catch it.
462 bool hung = has_timed_out_on_unload_;
464 // Now that we're no longer the active RVH in the tab, start filtering out
465 // most IPC messages. Usually the renderer will have stopped sending
466 // messages as of OnSwapOutACK. However, we may have timed out waiting
467 // for that message, and additional IPC messages may keep streaming in.
468 // We filter them out, as long as that won't cause problems (e.g., we
469 // still allow synchronous messages through).
470 SetSwappedOut(true);
472 // If we are not running the renderer in process and no other tab is using
473 // the hung process, consider it eligible to be killed, assuming it is a real
474 // process (unit tests don't have real processes).
475 if (hung) {
476 base::ProcessHandle process_handle = GetProcess()->GetHandle();
477 int views = 0;
479 // Count the number of widget hosts for the process, which is equivalent to
480 // views using the process as of this writing.
481 RenderProcessHost::RenderWidgetHostsIterator iter(
482 GetProcess()->GetRenderWidgetHostsIterator());
483 for (; !iter.IsAtEnd(); iter.Advance())
484 ++views;
486 if (!RenderProcessHost::run_renderer_in_process() &&
487 process_handle && views <= 1) {
488 // The process can safely be terminated, only if WebContents sets
489 // SuddenTerminationAllowed, which indicates that the timer has expired.
490 // This is not the case if we load data URLs or about:blank. The reason
491 // is that those have no network requests and this code is hit without
492 // setting the unresponsiveness timer. This allows a corner case where a
493 // navigation to a data URL will leave a process running, if the
494 // beforeunload handler completes fine, but the unload handler hangs.
495 // At this time, the complexity to solve this edge case is not worthwhile.
496 if (SuddenTerminationAllowed()) {
497 // We should kill the process, but for now, just log the data so we can
498 // diagnose the kill rate and investigate if separate timer is needed.
499 // http://crbug.com/104346.
501 // Log a histogram point to help us diagnose how many of those kills
502 // we have performed. 1 is the enum value for RendererType Normal for
503 // the histogram.
504 UMA_HISTOGRAM_PERCENTAGE(
505 "BrowserRenderProcessHost.ChildKillsUnresponsive", 1);
510 // Inform the renderer that it can exit if no one else is using it.
511 Send(new ViewMsg_WasSwappedOut(GetRoutingID()));
514 void RenderViewHostImpl::ClosePage() {
515 // Start the hang monitor in case the renderer hangs in the unload handler.
516 is_waiting_for_unload_ack_ = true;
517 StartHangMonitorTimeout(TimeDelta::FromMilliseconds(kUnloadTimeoutMS));
519 if (IsRenderViewLive()) {
520 // Since we are sending an IPC message to the renderer, increase the event
521 // count to prevent the hang monitor timeout from being stopped by input
522 // event acknowledgements.
523 increment_in_flight_event_count();
525 // TODO(creis): Should this be moved to Shutdown? It may not be called for
526 // RenderViewHosts that have been swapped out.
527 NotificationService::current()->Notify(
528 NOTIFICATION_RENDER_VIEW_HOST_WILL_CLOSE_RENDER_VIEW,
529 Source<RenderViewHost>(this),
530 NotificationService::NoDetails());
532 Send(new ViewMsg_ClosePage(GetRoutingID()));
533 } else {
534 // This RenderViewHost doesn't have a live renderer, so just skip the unload
535 // event and close the page.
536 ClosePageIgnoringUnloadEvents();
540 void RenderViewHostImpl::ClosePageIgnoringUnloadEvents() {
541 StopHangMonitorTimeout();
542 is_waiting_for_beforeunload_ack_ = false;
543 is_waiting_for_unload_ack_ = false;
545 sudden_termination_allowed_ = true;
546 delegate_->Close(this);
549 void RenderViewHostImpl::SetHasPendingCrossSiteRequest(bool has_pending_request,
550 int request_id) {
551 CrossSiteRequestManager::GetInstance()->SetHasPendingCrossSiteRequest(
552 GetProcess()->GetID(), GetRoutingID(), has_pending_request);
553 pending_request_id_ = request_id;
556 int RenderViewHostImpl::GetPendingRequestId() {
557 return pending_request_id_;
560 #if defined(OS_ANDROID)
561 void RenderViewHostImpl::ActivateNearestFindResult(int request_id,
562 float x,
563 float y) {
564 Send(new ViewMsg_ActivateNearestFindResult(GetRoutingID(), request_id, x, y));
567 void RenderViewHostImpl::RequestFindMatchRects(int current_version) {
568 Send(new ViewMsg_FindMatchRects(GetRoutingID(), current_version));
571 void RenderViewHostImpl::SynchronousFind(int request_id,
572 const string16& search_text,
573 const WebKit::WebFindOptions& options,
574 int* match_count,
575 int* active_ordinal) {
576 if (!CommandLine::ForCurrentProcess()->HasSwitch(
577 switches::kEnableWebViewSynchronousAPIs)) {
578 return;
581 Send(new ViewMsg_SynchronousFind(GetRoutingID(), request_id, search_text,
582 options, match_count, active_ordinal));
584 #endif
586 void RenderViewHostImpl::DragTargetDragEnter(
587 const WebDropData& drop_data,
588 const gfx::Point& client_pt,
589 const gfx::Point& screen_pt,
590 WebDragOperationsMask operations_allowed,
591 int key_modifiers) {
592 const int renderer_id = GetProcess()->GetID();
593 ChildProcessSecurityPolicyImpl* policy =
594 ChildProcessSecurityPolicyImpl::GetInstance();
596 // The URL could have been cobbled together from any highlighted text string,
597 // and can't be interpreted as a capability.
598 WebDropData filtered_data(drop_data);
599 FilterURL(policy, GetProcess(), true, &filtered_data.url);
601 // The filenames vector, on the other hand, does represent a capability to
602 // access the given files.
603 fileapi::IsolatedContext::FileInfoSet files;
604 for (std::vector<WebDropData::FileInfo>::iterator iter(
605 filtered_data.filenames.begin());
606 iter != filtered_data.filenames.end(); ++iter) {
607 // A dragged file may wind up as the value of an input element, or it
608 // may be used as the target of a navigation instead. We don't know
609 // which will happen at this point, so generously grant both access
610 // and request permissions to the specific file to cover both cases.
611 // We do not give it the permission to request all file:// URLs.
612 FilePath path = FilePath::FromUTF8Unsafe(UTF16ToUTF8(iter->path));
614 // Make sure we have the same display_name as the one we register.
615 if (iter->display_name.empty()) {
616 std::string name;
617 files.AddPath(path, &name);
618 iter->display_name = UTF8ToUTF16(name);
619 } else {
620 files.AddPathWithName(path, UTF16ToUTF8(iter->display_name));
623 policy->GrantRequestSpecificFileURL(renderer_id,
624 net::FilePathToFileURL(path));
626 // If the renderer already has permission to read these paths, we don't need
627 // to re-grant them. This prevents problems with DnD for files in the CrOS
628 // file manager--the file manager already had read/write access to those
629 // directories, but dragging a file would cause the read/write access to be
630 // overwritten with read-only access, making them impossible to delete or
631 // rename until the renderer was killed.
632 if (!policy->CanReadFile(renderer_id, path)) {
633 policy->GrantReadFile(renderer_id, path);
634 // Allow dragged directories to be enumerated by the child process.
635 // Note that we can't tell a file from a directory at this point.
636 policy->GrantReadDirectory(renderer_id, path);
640 fileapi::IsolatedContext* isolated_context =
641 fileapi::IsolatedContext::GetInstance();
642 DCHECK(isolated_context);
643 std::string filesystem_id = isolated_context->RegisterDraggedFileSystem(
644 files);
645 if (!filesystem_id.empty()) {
646 // Grant the permission iff the ID is valid.
647 policy->GrantReadFileSystem(renderer_id, filesystem_id);
649 filtered_data.filesystem_id = UTF8ToUTF16(filesystem_id);
651 Send(new DragMsg_TargetDragEnter(GetRoutingID(), filtered_data, client_pt,
652 screen_pt, operations_allowed,
653 key_modifiers));
656 void RenderViewHostImpl::DragTargetDragOver(
657 const gfx::Point& client_pt,
658 const gfx::Point& screen_pt,
659 WebDragOperationsMask operations_allowed,
660 int key_modifiers) {
661 Send(new DragMsg_TargetDragOver(GetRoutingID(), client_pt, screen_pt,
662 operations_allowed, key_modifiers));
665 void RenderViewHostImpl::DragTargetDragLeave() {
666 Send(new DragMsg_TargetDragLeave(GetRoutingID()));
669 void RenderViewHostImpl::DragTargetDrop(
670 const gfx::Point& client_pt,
671 const gfx::Point& screen_pt,
672 int key_modifiers) {
673 Send(new DragMsg_TargetDrop(GetRoutingID(), client_pt, screen_pt,
674 key_modifiers));
677 void RenderViewHostImpl::DesktopNotificationPermissionRequestDone(
678 int callback_context) {
679 Send(new DesktopNotificationMsg_PermissionRequestDone(
680 GetRoutingID(), callback_context));
683 void RenderViewHostImpl::DesktopNotificationPostDisplay(int callback_context) {
684 Send(new DesktopNotificationMsg_PostDisplay(GetRoutingID(),
685 callback_context));
688 void RenderViewHostImpl::DesktopNotificationPostError(int notification_id,
689 const string16& message) {
690 Send(new DesktopNotificationMsg_PostError(
691 GetRoutingID(), notification_id, message));
694 void RenderViewHostImpl::DesktopNotificationPostClose(int notification_id,
695 bool by_user) {
696 Send(new DesktopNotificationMsg_PostClose(
697 GetRoutingID(), notification_id, by_user));
700 void RenderViewHostImpl::DesktopNotificationPostClick(int notification_id) {
701 Send(new DesktopNotificationMsg_PostClick(GetRoutingID(), notification_id));
704 void RenderViewHostImpl::ExecuteJavascriptInWebFrame(
705 const string16& frame_xpath,
706 const string16& jscript) {
707 Send(new ViewMsg_ScriptEvalRequest(GetRoutingID(), frame_xpath, jscript,
708 0, false));
711 int RenderViewHostImpl::ExecuteJavascriptInWebFrameNotifyResult(
712 const string16& frame_xpath,
713 const string16& jscript) {
714 static int next_id = 1;
715 Send(new ViewMsg_ScriptEvalRequest(GetRoutingID(), frame_xpath, jscript,
716 next_id, true));
717 return next_id++;
720 typedef std::pair<int, Value*> ExecuteDetailType;
722 ExecuteNotificationObserver::ExecuteNotificationObserver(int id)
723 : id_(id) {
726 ExecuteNotificationObserver::~ExecuteNotificationObserver() {
729 void ExecuteNotificationObserver::Observe(int type,
730 const NotificationSource& source,
731 const NotificationDetails& details) {
732 Details<ExecuteDetailType> execute_details =
733 static_cast<Details<ExecuteDetailType> >(details);
734 int id = execute_details->first;
735 if (id != id_)
736 return;
737 Value* value = execute_details->second;
738 if (value)
739 value_.reset(value->DeepCopy());
740 MessageLoop::current()->Quit();
743 Value* RenderViewHostImpl::ExecuteJavascriptAndGetValue(
744 const string16& frame_xpath,
745 const string16& jscript) {
746 int id = ExecuteJavascriptInWebFrameNotifyResult(frame_xpath, jscript);
747 ExecuteNotificationObserver observer(id);
748 NotificationRegistrar notification_registrar;
749 notification_registrar.Add(
750 &observer, NOTIFICATION_EXECUTE_JAVASCRIPT_RESULT,
751 Source<RenderViewHost>(this));
752 MessageLoop* loop = MessageLoop::current();
753 loop->Run();
754 return observer.value()->DeepCopy();
757 void RenderViewHostImpl::JavaScriptDialogClosed(IPC::Message* reply_msg,
758 bool success,
759 const string16& user_input) {
760 GetProcess()->SetIgnoreInputEvents(false);
761 bool is_waiting =
762 is_waiting_for_beforeunload_ack_ || is_waiting_for_unload_ack_;
764 // If we are executing as part of (before)unload event handling, we don't
765 // want to use the regular hung_renderer_delay_ms_ if the user has agreed to
766 // leave the current page. In this case, use the regular timeout value used
767 // during the (before)unload handling.
768 if (is_waiting) {
769 StartHangMonitorTimeout(TimeDelta::FromMilliseconds(
770 success ? kUnloadTimeoutMS : hung_renderer_delay_ms_));
773 ViewHostMsg_RunJavaScriptMessage::WriteReplyParams(reply_msg,
774 success, user_input);
775 Send(reply_msg);
777 // If we are waiting for an unload or beforeunload ack and the user has
778 // suppressed messages, kill the tab immediately; a page that's spamming
779 // alerts in onbeforeunload is presumably malicious, so there's no point in
780 // continuing to run its script and dragging out the process.
781 // This must be done after sending the reply since RenderView can't close
782 // correctly while waiting for a response.
783 if (is_waiting && are_javascript_messages_suppressed_)
784 delegate_->RendererUnresponsive(this, is_waiting);
787 void RenderViewHostImpl::DragSourceEndedAt(
788 int client_x, int client_y, int screen_x, int screen_y,
789 WebDragOperation operation) {
790 Send(new DragMsg_SourceEndedOrMoved(
791 GetRoutingID(),
792 gfx::Point(client_x, client_y),
793 gfx::Point(screen_x, screen_y),
794 true, operation));
797 void RenderViewHostImpl::DragSourceMovedTo(
798 int client_x, int client_y, int screen_x, int screen_y) {
799 Send(new DragMsg_SourceEndedOrMoved(
800 GetRoutingID(),
801 gfx::Point(client_x, client_y),
802 gfx::Point(screen_x, screen_y),
803 false, WebDragOperationNone));
806 void RenderViewHostImpl::DragSourceSystemDragEnded() {
807 Send(new DragMsg_SourceSystemDragEnded(GetRoutingID()));
810 void RenderViewHostImpl::AllowBindings(int bindings_flags) {
811 // Ensure we aren't granting WebUI bindings to a process that has already
812 // been used for non-privileged views.
813 if (bindings_flags & BINDINGS_POLICY_WEB_UI &&
814 GetProcess()->HasConnection() &&
815 !ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
816 GetProcess()->GetID())) {
817 // This process has no bindings yet. Make sure it does not have more
818 // than this single active view.
819 RenderProcessHostImpl* process =
820 static_cast<RenderProcessHostImpl*>(GetProcess());
821 if (process->GetActiveViewCount() > 1)
822 return;
825 // Never grant any bindings to browser plugin guests.
826 if (GetProcess()->IsGuest()) {
827 NOTREACHED() << "Never grant bindings to a guest process.";
828 return;
831 if (bindings_flags & BINDINGS_POLICY_WEB_UI) {
832 ChildProcessSecurityPolicyImpl::GetInstance()->GrantWebUIBindings(
833 GetProcess()->GetID());
836 enabled_bindings_ |= bindings_flags;
837 if (renderer_initialized_)
838 Send(new ViewMsg_AllowBindings(GetRoutingID(), enabled_bindings_));
841 int RenderViewHostImpl::GetEnabledBindings() const {
842 return enabled_bindings_;
845 void RenderViewHostImpl::SetWebUIProperty(const std::string& name,
846 const std::string& value) {
847 // This is just a sanity check before telling the renderer to enable the
848 // property. It could lie and send the corresponding IPC messages anyway,
849 // but we will not act on them if enabled_bindings_ doesn't agree.
850 if (enabled_bindings_ & BINDINGS_POLICY_WEB_UI)
851 Send(new ViewMsg_SetWebUIProperty(GetRoutingID(), name, value));
852 else
853 NOTREACHED() << "WebUI bindings not enabled.";
856 void RenderViewHostImpl::GotFocus() {
857 RenderWidgetHostImpl::GotFocus(); // Notifies the renderer it got focus.
859 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
860 if (view)
861 view->GotFocus();
864 void RenderViewHostImpl::LostCapture() {
865 RenderWidgetHostImpl::LostCapture();
866 delegate_->LostCapture();
869 void RenderViewHostImpl::LostMouseLock() {
870 RenderWidgetHostImpl::LostMouseLock();
871 delegate_->LostMouseLock();
874 void RenderViewHostImpl::SetInitialFocus(bool reverse) {
875 Send(new ViewMsg_SetInitialFocus(GetRoutingID(), reverse));
878 void RenderViewHostImpl::FilesSelectedInChooser(
879 const std::vector<ui::SelectedFileInfo>& files,
880 int permissions) {
881 // Grant the security access requested to the given files.
882 for (size_t i = 0; i < files.size(); ++i) {
883 const ui::SelectedFileInfo& file = files[i];
884 ChildProcessSecurityPolicyImpl::GetInstance()->GrantPermissionsForFile(
885 GetProcess()->GetID(), file.local_path, permissions);
887 Send(new ViewMsg_RunFileChooserResponse(GetRoutingID(), files));
890 void RenderViewHostImpl::DirectoryEnumerationFinished(
891 int request_id,
892 const std::vector<FilePath>& files) {
893 // Grant the security access requested to the given files.
894 for (std::vector<FilePath>::const_iterator file = files.begin();
895 file != files.end(); ++file) {
896 ChildProcessSecurityPolicyImpl::GetInstance()->GrantReadFile(
897 GetProcess()->GetID(), *file);
899 Send(new ViewMsg_EnumerateDirectoryResponse(GetRoutingID(),
900 request_id,
901 files));
904 void RenderViewHostImpl::LoadStateChanged(
905 const GURL& url,
906 const net::LoadStateWithParam& load_state,
907 uint64 upload_position,
908 uint64 upload_size) {
909 delegate_->LoadStateChanged(url, load_state, upload_position, upload_size);
912 bool RenderViewHostImpl::SuddenTerminationAllowed() const {
913 return sudden_termination_allowed_ ||
914 GetProcess()->SuddenTerminationAllowed();
917 ///////////////////////////////////////////////////////////////////////////////
918 // RenderViewHostImpl, IPC message handlers:
920 bool RenderViewHostImpl::OnMessageReceived(const IPC::Message& msg) {
921 // Allow BrowserPluginHostMsg_* sync messages to run on the UI thread.
922 // Platform apps will not support windowed plugins so the deadlock cycle
923 // browser -> plugin -> renderer -> browser referred in
924 // BrowserMessageFilter::CheckCanDispatchOnUI() is not supposed to happen. If
925 // we want to support windowed plugins, sync messages in BrowserPlugin might
926 // need to be changed to async messages.
927 // TODO(fsamuel): Disallow BrowserPluginHostMsg_* sync messages to run on UI
928 // thread and make these messages async: http://crbug.com/149063.
929 if (msg.type() != BrowserPluginHostMsg_HandleInputEvent::ID &&
930 !BrowserMessageFilter::CheckCanDispatchOnUI(msg, this))
931 return true;
933 // Filter out most IPC messages if this renderer is swapped out.
934 // We still want to handle certain ACKs to keep our state consistent.
935 if (is_swapped_out_) {
936 if (!SwappedOutMessages::CanHandleWhileSwappedOut(msg)) {
937 // If this is a synchronous message and we decided not to handle it,
938 // we must send an error reply, or else the renderer will be stuck
939 // and won't respond to future requests.
940 if (msg.is_sync()) {
941 IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
942 reply->set_reply_error();
943 Send(reply);
945 // Don't continue looking for someone to handle it.
946 return true;
950 ObserverListBase<RenderViewHostObserver>::Iterator it(observers_);
951 RenderViewHostObserver* observer;
952 while ((observer = it.GetNext()) != NULL) {
953 if (observer->OnMessageReceived(msg))
954 return true;
957 if (delegate_->OnMessageReceived(this, msg))
958 return true;
960 // TODO(jochen): Consider removing message handlers that only add a this
961 // pointer and forward the messages to the RenderViewHostDelegate. The
962 // respective delegates can handle the messages themselves in their
963 // OnMessageReceived implementation.
964 bool handled = true;
965 bool msg_is_ok = true;
966 IPC_BEGIN_MESSAGE_MAP_EX(RenderViewHostImpl, msg, msg_is_ok)
967 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowView, OnMsgShowView)
968 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowWidget, OnMsgShowWidget)
969 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowFullscreenWidget,
970 OnMsgShowFullscreenWidget)
971 IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_RunModal, OnMsgRunModal)
972 IPC_MESSAGE_HANDLER(ViewHostMsg_RenderViewReady, OnMsgRenderViewReady)
973 IPC_MESSAGE_HANDLER(ViewHostMsg_RenderViewGone, OnMsgRenderViewGone)
974 IPC_MESSAGE_HANDLER(ViewHostMsg_DidStartProvisionalLoadForFrame,
975 OnMsgDidStartProvisionalLoadForFrame)
976 IPC_MESSAGE_HANDLER(ViewHostMsg_DidRedirectProvisionalLoad,
977 OnMsgDidRedirectProvisionalLoad)
978 IPC_MESSAGE_HANDLER(ViewHostMsg_DidFailProvisionalLoadWithError,
979 OnMsgDidFailProvisionalLoadWithError)
980 IPC_MESSAGE_HANDLER_GENERIC(ViewHostMsg_FrameNavigate, OnMsgNavigate(msg))
981 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateState, OnMsgUpdateState)
982 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateTitle, OnMsgUpdateTitle)
983 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateEncoding, OnMsgUpdateEncoding)
984 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateTargetURL, OnMsgUpdateTargetURL)
985 IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateInspectorSetting,
986 OnUpdateInspectorSetting)
987 IPC_MESSAGE_HANDLER(ViewHostMsg_Close, OnMsgClose)
988 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestMove, OnMsgRequestMove)
989 IPC_MESSAGE_HANDLER(ViewHostMsg_DidStartLoading, OnMsgDidStartLoading)
990 IPC_MESSAGE_HANDLER(ViewHostMsg_DidStopLoading, OnMsgDidStopLoading)
991 IPC_MESSAGE_HANDLER(ViewHostMsg_DidChangeLoadProgress,
992 OnMsgDidChangeLoadProgress)
993 IPC_MESSAGE_HANDLER(ViewHostMsg_DocumentAvailableInMainFrame,
994 OnMsgDocumentAvailableInMainFrame)
995 IPC_MESSAGE_HANDLER(ViewHostMsg_DocumentOnLoadCompletedInMainFrame,
996 OnMsgDocumentOnLoadCompletedInMainFrame)
997 IPC_MESSAGE_HANDLER(ViewHostMsg_ContextMenu, OnMsgContextMenu)
998 IPC_MESSAGE_HANDLER(ViewHostMsg_ToggleFullscreen,
999 OnMsgToggleFullscreen)
1000 IPC_MESSAGE_HANDLER(ViewHostMsg_OpenURL, OnMsgOpenURL)
1001 IPC_MESSAGE_HANDLER(ViewHostMsg_DidContentsPreferredSizeChange,
1002 OnMsgDidContentsPreferredSizeChange)
1003 IPC_MESSAGE_HANDLER(ViewHostMsg_DidChangeScrollbarsForMainFrame,
1004 OnMsgDidChangeScrollbarsForMainFrame)
1005 IPC_MESSAGE_HANDLER(ViewHostMsg_DidChangeScrollOffsetPinningForMainFrame,
1006 OnMsgDidChangeScrollOffsetPinningForMainFrame)
1007 IPC_MESSAGE_HANDLER(ViewHostMsg_DidChangeNumWheelEvents,
1008 OnMsgDidChangeNumWheelEvents)
1009 IPC_MESSAGE_HANDLER(ViewHostMsg_RouteCloseEvent,
1010 OnMsgRouteCloseEvent)
1011 IPC_MESSAGE_HANDLER(ViewHostMsg_RouteMessageEvent, OnMsgRouteMessageEvent)
1012 IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_RunJavaScriptMessage,
1013 OnMsgRunJavaScriptMessage)
1014 IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_RunBeforeUnloadConfirm,
1015 OnMsgRunBeforeUnloadConfirm)
1016 IPC_MESSAGE_HANDLER(DragHostMsg_StartDragging, OnMsgStartDragging)
1017 IPC_MESSAGE_HANDLER(DragHostMsg_UpdateDragCursor, OnUpdateDragCursor)
1018 IPC_MESSAGE_HANDLER(DragHostMsg_TargetDrop_ACK, OnTargetDropACK)
1019 IPC_MESSAGE_HANDLER(ViewHostMsg_TakeFocus, OnTakeFocus)
1020 IPC_MESSAGE_HANDLER(ViewHostMsg_FocusedNodeChanged, OnFocusedNodeChanged)
1021 IPC_MESSAGE_HANDLER(ViewHostMsg_AddMessageToConsole, OnAddMessageToConsole)
1022 IPC_MESSAGE_HANDLER(ViewHostMsg_ShouldClose_ACK, OnMsgShouldCloseACK)
1023 IPC_MESSAGE_HANDLER(ViewHostMsg_ClosePage_ACK, OnMsgClosePageACK)
1024 IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionChanged, OnMsgSelectionChanged)
1025 IPC_MESSAGE_HANDLER(ViewHostMsg_SelectionBoundsChanged,
1026 OnMsgSelectionBoundsChanged)
1027 IPC_MESSAGE_HANDLER(ViewHostMsg_ScriptEvalResponse, OnScriptEvalResponse)
1028 IPC_MESSAGE_HANDLER(ViewHostMsg_DidZoomURL, OnDidZoomURL)
1029 IPC_MESSAGE_HANDLER(ViewHostMsg_MediaNotification, OnMediaNotification)
1030 #if defined(OS_ANDROID)
1031 IPC_MESSAGE_HANDLER(ViewHostMsg_StartContentIntent, OnStartContentIntent)
1032 IPC_MESSAGE_HANDLER(ViewHostMsg_DidChangeBodyBackgroundColor,
1033 OnMsgDidChangeBodyBackgroundColor)
1034 #endif
1035 IPC_MESSAGE_HANDLER(DesktopNotificationHostMsg_RequestPermission,
1036 OnRequestDesktopNotificationPermission)
1037 IPC_MESSAGE_HANDLER(DesktopNotificationHostMsg_Show,
1038 OnShowDesktopNotification)
1039 IPC_MESSAGE_HANDLER(DesktopNotificationHostMsg_Cancel,
1040 OnCancelDesktopNotification)
1041 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1042 IPC_MESSAGE_HANDLER(ViewHostMsg_ShowPopup, OnMsgShowPopup)
1043 #endif
1044 IPC_MESSAGE_HANDLER(ViewHostMsg_RunFileChooser, OnRunFileChooser)
1045 IPC_MESSAGE_HANDLER(ViewHostMsg_DomOperationResponse,
1046 OnDomOperationResponse)
1047 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_Notifications,
1048 OnAccessibilityNotifications)
1049 IPC_MESSAGE_HANDLER(ViewHostMsg_FrameTreeUpdated, OnFrameTreeUpdated)
1050 // Have the super handle all other messages.
1051 IPC_MESSAGE_UNHANDLED(
1052 handled = RenderWidgetHostImpl::OnMessageReceived(msg))
1053 IPC_END_MESSAGE_MAP_EX()
1055 if (!msg_is_ok) {
1056 // The message had a handler, but its de-serialization failed.
1057 // Kill the renderer.
1058 RecordAction(UserMetricsAction("BadMessageTerminate_RVH"));
1059 GetProcess()->ReceivedBadMessage();
1062 return handled;
1065 void RenderViewHostImpl::Shutdown() {
1066 // If we are being run modally (see RunModal), then we need to cleanup.
1067 if (run_modal_reply_msg_) {
1068 Send(run_modal_reply_msg_);
1069 run_modal_reply_msg_ = NULL;
1070 RenderViewHostImpl* opener =
1071 RenderViewHostImpl::FromID(GetProcess()->GetID(), run_modal_opener_id_);
1072 if (opener) {
1073 opener->StartHangMonitorTimeout(TimeDelta::FromMilliseconds(
1074 hung_renderer_delay_ms_));
1075 // Balance out the decrement when we got created.
1076 opener->increment_in_flight_event_count();
1078 run_modal_opener_id_ = MSG_ROUTING_NONE;
1081 RenderWidgetHostImpl::Shutdown();
1084 bool RenderViewHostImpl::IsRenderView() const {
1085 return true;
1088 void RenderViewHostImpl::CreateNewWindow(
1089 int route_id,
1090 const ViewHostMsg_CreateWindow_Params& params,
1091 SessionStorageNamespace* session_storage_namespace) {
1092 delegate_->CreateNewWindow(route_id, params, session_storage_namespace);
1095 void RenderViewHostImpl::CreateNewWidget(int route_id,
1096 WebKit::WebPopupType popup_type) {
1097 delegate_->CreateNewWidget(route_id, popup_type);
1100 void RenderViewHostImpl::CreateNewFullscreenWidget(int route_id) {
1101 delegate_->CreateNewFullscreenWidget(route_id);
1104 void RenderViewHostImpl::OnMsgShowView(int route_id,
1105 WindowOpenDisposition disposition,
1106 const gfx::Rect& initial_pos,
1107 bool user_gesture) {
1108 if (!is_swapped_out_) {
1109 delegate_->ShowCreatedWindow(
1110 route_id, disposition, initial_pos, user_gesture);
1112 Send(new ViewMsg_Move_ACK(route_id));
1115 void RenderViewHostImpl::OnMsgShowWidget(int route_id,
1116 const gfx::Rect& initial_pos) {
1117 if (!is_swapped_out_)
1118 delegate_->ShowCreatedWidget(route_id, initial_pos);
1119 Send(new ViewMsg_Move_ACK(route_id));
1122 void RenderViewHostImpl::OnMsgShowFullscreenWidget(int route_id) {
1123 if (!is_swapped_out_)
1124 delegate_->ShowCreatedFullscreenWidget(route_id);
1125 Send(new ViewMsg_Move_ACK(route_id));
1128 void RenderViewHostImpl::OnMsgRunModal(int opener_id, IPC::Message* reply_msg) {
1129 DCHECK(!run_modal_reply_msg_);
1130 run_modal_reply_msg_ = reply_msg;
1131 run_modal_opener_id_ = opener_id;
1133 RecordAction(UserMetricsAction("ShowModalDialog"));
1135 RenderViewHostImpl* opener =
1136 RenderViewHostImpl::FromID(GetProcess()->GetID(), run_modal_opener_id_);
1137 if (opener) {
1138 opener->StopHangMonitorTimeout();
1139 // The ack for the mouse down won't come until the dialog closes, so fake it
1140 // so that we don't get a timeout.
1141 opener->decrement_in_flight_event_count();
1144 // TODO(darin): Bug 1107929: Need to inform our delegate to show this view in
1145 // an app-modal fashion.
1148 void RenderViewHostImpl::OnMsgRenderViewReady() {
1149 render_view_termination_status_ = base::TERMINATION_STATUS_STILL_RUNNING;
1150 SendScreenRects();
1151 WasResized();
1152 delegate_->RenderViewReady(this);
1155 void RenderViewHostImpl::OnMsgRenderViewGone(int status, int exit_code) {
1156 // Keep the termination status so we can get at it later when we
1157 // need to know why it died.
1158 render_view_termination_status_ =
1159 static_cast<base::TerminationStatus>(status);
1161 // Reset state.
1162 ClearPowerSaveBlockers();
1164 // Our base class RenderWidgetHost needs to reset some stuff.
1165 RendererExited(render_view_termination_status_, exit_code);
1167 delegate_->RenderViewGone(this,
1168 static_cast<base::TerminationStatus>(status),
1169 exit_code);
1172 void RenderViewHostImpl::OnMsgDidStartProvisionalLoadForFrame(
1173 int64 frame_id,
1174 int64 parent_frame_id,
1175 bool is_main_frame,
1176 const GURL& url) {
1177 delegate_->DidStartProvisionalLoadForFrame(
1178 this, frame_id, parent_frame_id, is_main_frame, url);
1181 void RenderViewHostImpl::OnMsgDidRedirectProvisionalLoad(
1182 int32 page_id,
1183 const GURL& source_url,
1184 const GURL& target_url) {
1185 delegate_->DidRedirectProvisionalLoad(
1186 this, page_id, source_url, target_url);
1189 void RenderViewHostImpl::OnMsgDidFailProvisionalLoadWithError(
1190 const ViewHostMsg_DidFailProvisionalLoadWithError_Params& params) {
1191 delegate_->DidFailProvisionalLoadWithError(this, params);
1194 // Called when the renderer navigates. For every frame loaded, we'll get this
1195 // notification containing parameters identifying the navigation.
1197 // Subframes are identified by the page transition type. For subframes loaded
1198 // as part of a wider page load, the page_id will be the same as for the top
1199 // level frame. If the user explicitly requests a subframe navigation, we will
1200 // get a new page_id because we need to create a new navigation entry for that
1201 // action.
1202 void RenderViewHostImpl::OnMsgNavigate(const IPC::Message& msg) {
1203 // Read the parameters out of the IPC message directly to avoid making another
1204 // copy when we filter the URLs.
1205 PickleIterator iter(msg);
1206 ViewHostMsg_FrameNavigate_Params validated_params;
1207 if (!IPC::ParamTraits<ViewHostMsg_FrameNavigate_Params>::
1208 Read(&msg, &iter, &validated_params))
1209 return;
1211 // If we're waiting for a cross-site beforeunload ack from this renderer and
1212 // we receive a Navigate message from the main frame, then the renderer was
1213 // navigating already and sent it before hearing the ViewMsg_Stop message.
1214 // We do not want to cancel the pending navigation in this case, since the
1215 // old page will soon be stopped. Instead, treat this as a beforeunload ack
1216 // to allow the pending navigation to continue.
1217 if (is_waiting_for_beforeunload_ack_ &&
1218 unload_ack_is_for_cross_site_transition_ &&
1219 PageTransitionIsMainFrame(validated_params.transition)) {
1220 OnMsgShouldCloseACK(true, send_should_close_start_time_,
1221 base::TimeTicks::Now());
1222 return;
1225 // If we're waiting for an unload ack from this renderer and we receive a
1226 // Navigate message, then the renderer was navigating before it received the
1227 // unload request. It will either respond to the unload request soon or our
1228 // timer will expire. Either way, we should ignore this message, because we
1229 // have already committed to closing this renderer.
1230 if (is_waiting_for_unload_ack_)
1231 return;
1233 RenderProcessHost* process = GetProcess();
1234 ChildProcessSecurityPolicyImpl* policy =
1235 ChildProcessSecurityPolicyImpl::GetInstance();
1236 // Without this check, an evil renderer can trick the browser into creating
1237 // a navigation entry for a banned URL. If the user clicks the back button
1238 // followed by the forward button (or clicks reload, or round-trips through
1239 // session restore, etc), we'll think that the browser commanded the
1240 // renderer to load the URL and grant the renderer the privileges to request
1241 // the URL. To prevent this attack, we block the renderer from inserting
1242 // banned URLs into the navigation controller in the first place.
1243 FilterURL(policy, process, false, &validated_params.url);
1244 FilterURL(policy, process, true, &validated_params.referrer.url);
1245 for (std::vector<GURL>::iterator it(validated_params.redirects.begin());
1246 it != validated_params.redirects.end(); ++it) {
1247 FilterURL(policy, process, false, &(*it));
1249 FilterURL(policy, process, true, &validated_params.searchable_form_url);
1250 FilterURL(policy, process, true, &validated_params.password_form.origin);
1251 FilterURL(policy, process, true, &validated_params.password_form.action);
1253 delegate_->DidNavigate(this, validated_params);
1255 // TODO(nasko): Send frame tree update for the top level frame, once
1256 // http://crbug.com/153701 is fixed.
1259 void RenderViewHostImpl::OnMsgUpdateState(int32 page_id,
1260 const std::string& state) {
1261 delegate_->UpdateState(this, page_id, state);
1264 void RenderViewHostImpl::OnMsgUpdateTitle(
1265 int32 page_id,
1266 const string16& title,
1267 WebKit::WebTextDirection title_direction) {
1268 if (title.length() > kMaxTitleChars) {
1269 NOTREACHED() << "Renderer sent too many characters in title.";
1270 return;
1273 delegate_->UpdateTitle(this, page_id, title,
1274 WebTextDirectionToChromeTextDirection(
1275 title_direction));
1278 void RenderViewHostImpl::OnMsgUpdateEncoding(const std::string& encoding_name) {
1279 delegate_->UpdateEncoding(this, encoding_name);
1282 void RenderViewHostImpl::OnMsgUpdateTargetURL(int32 page_id,
1283 const GURL& url) {
1284 if (!is_swapped_out_)
1285 delegate_->UpdateTargetURL(page_id, url);
1287 // Send a notification back to the renderer that we are ready to
1288 // receive more target urls.
1289 Send(new ViewMsg_UpdateTargetURL_ACK(GetRoutingID()));
1292 void RenderViewHostImpl::OnUpdateInspectorSetting(
1293 const std::string& key, const std::string& value) {
1294 GetContentClient()->browser()->UpdateInspectorSetting(
1295 this, key, value);
1298 void RenderViewHostImpl::OnMsgClose() {
1299 // If the renderer is telling us to close, it has already run the unload
1300 // events, and we can take the fast path.
1301 ClosePageIgnoringUnloadEvents();
1304 void RenderViewHostImpl::OnMsgRequestMove(const gfx::Rect& pos) {
1305 if (!is_swapped_out_)
1306 delegate_->RequestMove(pos);
1307 Send(new ViewMsg_Move_ACK(GetRoutingID()));
1310 void RenderViewHostImpl::OnMsgDidStartLoading() {
1311 delegate_->DidStartLoading(this);
1314 void RenderViewHostImpl::OnMsgDidStopLoading() {
1315 delegate_->DidStopLoading(this);
1318 void RenderViewHostImpl::OnMsgDidChangeLoadProgress(double load_progress) {
1319 delegate_->DidChangeLoadProgress(load_progress);
1322 void RenderViewHostImpl::OnMsgDocumentAvailableInMainFrame() {
1323 delegate_->DocumentAvailableInMainFrame(this);
1326 void RenderViewHostImpl::OnMsgDocumentOnLoadCompletedInMainFrame(
1327 int32 page_id) {
1328 delegate_->DocumentOnLoadCompletedInMainFrame(this, page_id);
1331 void RenderViewHostImpl::OnMsgContextMenu(const ContextMenuParams& params) {
1332 // Validate the URLs in |params|. If the renderer can't request the URLs
1333 // directly, don't show them in the context menu.
1334 ContextMenuParams validated_params(params);
1335 RenderProcessHost* process = GetProcess();
1336 ChildProcessSecurityPolicyImpl* policy =
1337 ChildProcessSecurityPolicyImpl::GetInstance();
1339 // We don't validate |unfiltered_link_url| so that this field can be used
1340 // when users want to copy the original link URL.
1341 FilterURL(policy, process, true, &validated_params.link_url);
1342 FilterURL(policy, process, true, &validated_params.src_url);
1343 FilterURL(policy, process, false, &validated_params.page_url);
1344 FilterURL(policy, process, true, &validated_params.frame_url);
1346 ContextMenuSourceType type = CONTEXT_MENU_SOURCE_MOUSE;
1347 if (!in_process_event_types_.empty()) {
1348 WebKit::WebInputEvent::Type event_type = in_process_event_types_.front();
1349 if (WebKit::WebInputEvent::isGestureEventType(event_type))
1350 type = CONTEXT_MENU_SOURCE_TOUCH;
1351 else if (WebKit::WebInputEvent::isKeyboardEventType(event_type))
1352 type = CONTEXT_MENU_SOURCE_KEYBOARD;
1354 delegate_->ShowContextMenu(validated_params, type);
1357 void RenderViewHostImpl::OnMsgToggleFullscreen(bool enter_fullscreen) {
1358 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1359 delegate_->ToggleFullscreenMode(enter_fullscreen);
1360 WasResized();
1363 void RenderViewHostImpl::OnMsgOpenURL(
1364 const ViewHostMsg_OpenURL_Params& params) {
1365 GURL validated_url(params.url);
1366 FilterURL(ChildProcessSecurityPolicyImpl::GetInstance(),
1367 GetProcess(), false, &validated_url);
1369 delegate_->RequestOpenURL(
1370 this, validated_url, params.referrer, params.disposition, params.frame_id,
1371 params.is_cross_site_redirect);
1374 void RenderViewHostImpl::OnMsgDidContentsPreferredSizeChange(
1375 const gfx::Size& new_size) {
1376 delegate_->UpdatePreferredSize(new_size);
1379 void RenderViewHostImpl::OnRenderAutoResized(const gfx::Size& new_size) {
1380 delegate_->ResizeDueToAutoResize(new_size);
1383 void RenderViewHostImpl::OnMsgDidChangeScrollbarsForMainFrame(
1384 bool has_horizontal_scrollbar, bool has_vertical_scrollbar) {
1385 if (view_)
1386 view_->SetHasHorizontalScrollbar(has_horizontal_scrollbar);
1389 void RenderViewHostImpl::OnMsgDidChangeScrollOffsetPinningForMainFrame(
1390 bool is_pinned_to_left, bool is_pinned_to_right) {
1391 if (view_)
1392 view_->SetScrollOffsetPinning(is_pinned_to_left, is_pinned_to_right);
1395 void RenderViewHostImpl::OnMsgDidChangeNumWheelEvents(int count) {
1398 void RenderViewHostImpl::OnMsgSelectionChanged(const string16& text,
1399 size_t offset,
1400 const ui::Range& range) {
1401 if (view_)
1402 view_->SelectionChanged(text, offset, range);
1405 void RenderViewHostImpl::OnMsgSelectionBoundsChanged(
1406 const gfx::Rect& start_rect,
1407 WebKit::WebTextDirection start_direction,
1408 const gfx::Rect& end_rect,
1409 WebKit::WebTextDirection end_direction) {
1410 if (view_) {
1411 view_->SelectionBoundsChanged(start_rect, start_direction,
1412 end_rect, end_direction);
1416 void RenderViewHostImpl::OnMsgRouteCloseEvent() {
1417 // Have the delegate route this to the active RenderViewHost.
1418 delegate_->RouteCloseEvent(this);
1421 void RenderViewHostImpl::OnMsgRouteMessageEvent(
1422 const ViewMsg_PostMessage_Params& params) {
1423 // Give to the delegate to route to the active RenderViewHost.
1424 delegate_->RouteMessageEvent(this, params);
1427 void RenderViewHostImpl::OnMsgRunJavaScriptMessage(
1428 const string16& message,
1429 const string16& default_prompt,
1430 const GURL& frame_url,
1431 JavaScriptMessageType type,
1432 IPC::Message* reply_msg) {
1433 // While a JS message dialog is showing, tabs in the same process shouldn't
1434 // process input events.
1435 GetProcess()->SetIgnoreInputEvents(true);
1436 StopHangMonitorTimeout();
1437 delegate_->RunJavaScriptMessage(this, message, default_prompt, frame_url,
1438 type, reply_msg,
1439 &are_javascript_messages_suppressed_);
1442 void RenderViewHostImpl::OnMsgRunBeforeUnloadConfirm(const GURL& frame_url,
1443 const string16& message,
1444 bool is_reload,
1445 IPC::Message* reply_msg) {
1446 // While a JS before unload dialog is showing, tabs in the same process
1447 // shouldn't process input events.
1448 GetProcess()->SetIgnoreInputEvents(true);
1449 StopHangMonitorTimeout();
1450 delegate_->RunBeforeUnloadConfirm(this, message, is_reload, reply_msg);
1453 void RenderViewHostImpl::OnMsgStartDragging(
1454 const WebDropData& drop_data,
1455 WebDragOperationsMask drag_operations_mask,
1456 const SkBitmap& bitmap,
1457 const gfx::Vector2d& bitmap_offset_in_dip,
1458 const DragEventSourceInfo& event_info) {
1459 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1460 if (!view)
1461 return;
1463 WebDropData filtered_data(drop_data);
1464 RenderProcessHost* process = GetProcess();
1465 ChildProcessSecurityPolicyImpl* policy =
1466 ChildProcessSecurityPolicyImpl::GetInstance();
1468 // Allow drag of Javascript URLs to enable bookmarklet drag to bookmark bar.
1469 if (!filtered_data.url.SchemeIs(chrome::kJavaScriptScheme))
1470 FilterURL(policy, process, true, &filtered_data.url);
1471 FilterURL(policy, process, false, &filtered_data.html_base_url);
1472 // Filter out any paths that the renderer didn't have access to. This prevents
1473 // the following attack on a malicious renderer:
1474 // 1. StartDragging IPC sent with renderer-specified filesystem paths that it
1475 // doesn't have read permissions for.
1476 // 2. We initiate a native DnD operation.
1477 // 3. DnD operation immediately ends since mouse is not held down. DnD events
1478 // still fire though, which causes read permissions to be granted to the
1479 // renderer for any file paths in the drop.
1480 filtered_data.filenames.clear();
1481 for (std::vector<WebDropData::FileInfo>::const_iterator it =
1482 drop_data.filenames.begin();
1483 it != drop_data.filenames.end(); ++it) {
1484 FilePath path(FilePath::FromUTF8Unsafe(UTF16ToUTF8(it->path)));
1485 if (policy->CanReadFile(GetProcess()->GetID(), path))
1486 filtered_data.filenames.push_back(*it);
1488 ui::ScaleFactor scale_factor = GetScaleFactorForView(GetView());
1489 gfx::ImageSkia image(gfx::ImageSkiaRep(bitmap, scale_factor));
1490 view->StartDragging(filtered_data, drag_operations_mask, image,
1491 bitmap_offset_in_dip, event_info);
1494 void RenderViewHostImpl::OnUpdateDragCursor(WebDragOperation current_op) {
1495 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1496 if (view)
1497 view->UpdateDragCursor(current_op);
1500 void RenderViewHostImpl::OnTargetDropACK() {
1501 NotificationService::current()->Notify(
1502 NOTIFICATION_RENDER_VIEW_HOST_DID_RECEIVE_DRAG_TARGET_DROP_ACK,
1503 Source<RenderViewHost>(this),
1504 NotificationService::NoDetails());
1507 void RenderViewHostImpl::OnTakeFocus(bool reverse) {
1508 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1509 if (view)
1510 view->TakeFocus(reverse);
1513 void RenderViewHostImpl::OnFocusedNodeChanged(bool is_editable_node) {
1514 NotificationService::current()->Notify(
1515 NOTIFICATION_FOCUS_CHANGED_IN_PAGE,
1516 Source<RenderViewHost>(this),
1517 Details<const bool>(&is_editable_node));
1520 void RenderViewHostImpl::OnAddMessageToConsole(
1521 int32 level,
1522 const string16& message,
1523 int32 line_no,
1524 const string16& source_id) {
1525 if (delegate_->AddMessageToConsole(level, message, line_no, source_id))
1526 return;
1527 // Pass through log level only on WebUI pages to limit console spew.
1528 int32 resolved_level =
1529 (enabled_bindings_ & BINDINGS_POLICY_WEB_UI) ? level : 0;
1531 if (resolved_level >= ::logging::GetMinLogLevel()) {
1532 logging::LogMessage("CONSOLE", line_no, resolved_level).stream() << "\"" <<
1533 message << "\", source: " << source_id << " (" << line_no << ")";
1537 void RenderViewHostImpl::AddObserver(RenderViewHostObserver* observer) {
1538 observers_.AddObserver(observer);
1541 void RenderViewHostImpl::RemoveObserver(RenderViewHostObserver* observer) {
1542 observers_.RemoveObserver(observer);
1545 void RenderViewHostImpl::OnUserGesture() {
1546 delegate_->OnUserGesture();
1549 void RenderViewHostImpl::OnMsgShouldCloseACK(
1550 bool proceed,
1551 const base::TimeTicks& renderer_before_unload_start_time,
1552 const base::TimeTicks& renderer_before_unload_end_time) {
1553 decrement_in_flight_event_count();
1554 StopHangMonitorTimeout();
1555 // If this renderer navigated while the beforeunload request was in flight, we
1556 // may have cleared this state in OnMsgNavigate, in which case we can ignore
1557 // this message.
1558 if (!is_waiting_for_beforeunload_ack_ || is_swapped_out_)
1559 return;
1561 is_waiting_for_beforeunload_ack_ = false;
1563 RenderViewHostDelegate::RendererManagement* management_delegate =
1564 delegate_->GetRendererManagementDelegate();
1565 if (management_delegate) {
1566 base::TimeTicks before_unload_end_time;
1567 if (!send_should_close_start_time_.is_null() &&
1568 !renderer_before_unload_start_time.is_null() &&
1569 !renderer_before_unload_end_time.is_null()) {
1570 // When passing TimeTicks across process boundaries, we need to compensate
1571 // for any skew between the processes. Here we are converting the
1572 // renderer's notion of before_unload_end_time to TimeTicks in the browser
1573 // process. See comments in inter_process_time_ticks_converter.h for more.
1574 InterProcessTimeTicksConverter converter(
1575 LocalTimeTicks::FromTimeTicks(send_should_close_start_time_),
1576 LocalTimeTicks::FromTimeTicks(base::TimeTicks::Now()),
1577 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_start_time),
1578 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time));
1579 LocalTimeTicks browser_before_unload_end_time =
1580 converter.ToLocalTimeTicks(
1581 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time));
1582 before_unload_end_time = browser_before_unload_end_time.ToTimeTicks();
1584 management_delegate->ShouldClosePage(
1585 unload_ack_is_for_cross_site_transition_, proceed,
1586 before_unload_end_time);
1589 // If canceled, notify the delegate to cancel its pending navigation entry.
1590 if (!proceed)
1591 delegate_->DidCancelLoading();
1594 void RenderViewHostImpl::OnMsgClosePageACK() {
1595 decrement_in_flight_event_count();
1596 ClosePageIgnoringUnloadEvents();
1599 void RenderViewHostImpl::NotifyRendererUnresponsive() {
1600 delegate_->RendererUnresponsive(
1601 this, is_waiting_for_beforeunload_ack_ || is_waiting_for_unload_ack_);
1604 void RenderViewHostImpl::NotifyRendererResponsive() {
1605 delegate_->RendererResponsive(this);
1608 void RenderViewHostImpl::RequestToLockMouse(bool user_gesture,
1609 bool last_unlocked_by_target) {
1610 delegate_->RequestToLockMouse(user_gesture, last_unlocked_by_target);
1613 bool RenderViewHostImpl::IsFullscreen() const {
1614 return delegate_->IsFullscreenForCurrentTab();
1617 void RenderViewHostImpl::OnMsgFocus() {
1618 // Note: We allow focus and blur from swapped out RenderViewHosts, even when
1619 // the active RenderViewHost is in a different BrowsingInstance (e.g., WebUI).
1620 delegate_->Activate();
1623 void RenderViewHostImpl::OnMsgBlur() {
1624 delegate_->Deactivate();
1627 gfx::Rect RenderViewHostImpl::GetRootWindowResizerRect() const {
1628 return delegate_->GetRootWindowResizerRect();
1631 void RenderViewHostImpl::ForwardMouseEvent(
1632 const WebKit::WebMouseEvent& mouse_event) {
1634 // We make a copy of the mouse event because
1635 // RenderWidgetHost::ForwardMouseEvent will delete |mouse_event|.
1636 WebKit::WebMouseEvent event_copy(mouse_event);
1637 RenderWidgetHostImpl::ForwardMouseEvent(event_copy);
1639 switch (event_copy.type) {
1640 case WebInputEvent::MouseMove:
1641 delegate_->HandleMouseMove();
1642 break;
1643 case WebInputEvent::MouseLeave:
1644 delegate_->HandleMouseLeave();
1645 break;
1646 case WebInputEvent::MouseDown:
1647 delegate_->HandleMouseDown();
1648 break;
1649 case WebInputEvent::MouseWheel:
1650 if (ignore_input_events())
1651 delegate_->OnIgnoredUIEvent();
1652 break;
1653 case WebInputEvent::MouseUp:
1654 delegate_->HandleMouseUp();
1655 default:
1656 // For now, we don't care about the rest.
1657 break;
1661 void RenderViewHostImpl::OnPointerEventActivate() {
1662 delegate_->HandlePointerActivate();
1665 void RenderViewHostImpl::ForwardKeyboardEvent(
1666 const NativeWebKeyboardEvent& key_event) {
1667 if (ignore_input_events()) {
1668 if (key_event.type == WebInputEvent::RawKeyDown)
1669 delegate_->OnIgnoredUIEvent();
1670 return;
1672 RenderWidgetHostImpl::ForwardKeyboardEvent(key_event);
1675 #if defined(OS_ANDROID)
1676 void RenderViewHostImpl::DidSelectPopupMenuItems(
1677 const std::vector<int>& selected_indices) {
1678 Send(new ViewMsg_SelectPopupMenuItems(GetRoutingID(), false,
1679 selected_indices));
1682 void RenderViewHostImpl::DidCancelPopupMenu() {
1683 Send(new ViewMsg_SelectPopupMenuItems(GetRoutingID(), true,
1684 std::vector<int>()));
1686 #endif
1688 #if defined(OS_MACOSX)
1689 void RenderViewHostImpl::DidSelectPopupMenuItem(int selected_index) {
1690 Send(new ViewMsg_SelectPopupMenuItem(GetRoutingID(), selected_index));
1693 void RenderViewHostImpl::DidCancelPopupMenu() {
1694 Send(new ViewMsg_SelectPopupMenuItem(GetRoutingID(), -1));
1696 #endif
1698 void RenderViewHostImpl::SendOrientationChangeEvent(int orientation) {
1699 Send(new ViewMsg_OrientationChangeEvent(GetRoutingID(), orientation));
1702 void RenderViewHostImpl::ToggleSpeechInput() {
1703 Send(new InputTagSpeechMsg_ToggleSpeechInput(GetRoutingID()));
1706 void RenderViewHostImpl::FilterURL(ChildProcessSecurityPolicyImpl* policy,
1707 const RenderProcessHost* process,
1708 bool empty_allowed,
1709 GURL* url) {
1710 if (empty_allowed && url->is_empty())
1711 return;
1713 // The browser process should never hear the swappedout:// URL from any
1714 // of the renderer's messages. Temporarily CHECK on a canary build to see if
1715 // it's still happening in the wild.
1716 CHECK(GURL(kSwappedOutURL) != *url);
1718 if (!url->is_valid()) {
1719 // Have to use about:blank for the denied case, instead of an empty GURL.
1720 // This is because the browser treats navigation to an empty GURL as a
1721 // navigation to the home page. This is often a privileged page
1722 // (chrome://newtab/) which is exactly what we don't want.
1723 *url = GURL(chrome::kAboutBlankURL);
1724 return;
1727 if (url->SchemeIs(chrome::kAboutScheme)) {
1728 // The renderer treats all URLs in the about: scheme as being about:blank.
1729 // Canonicalize about: URLs to about:blank.
1730 *url = GURL(chrome::kAboutBlankURL);
1733 // Do not allow browser plugin guests to navigate to non-web URLs, since they
1734 // cannot swap processes or grant bindings.
1735 bool non_web_url_in_guest = process->IsGuest() &&
1736 !(url->is_valid() && policy->IsWebSafeScheme(url->scheme()));
1738 if (non_web_url_in_guest || !policy->CanRequestURL(process->GetID(), *url)) {
1739 // If this renderer is not permitted to request this URL, we invalidate the
1740 // URL. This prevents us from storing the blocked URL and becoming confused
1741 // later.
1742 VLOG(1) << "Blocked URL " << url->spec();
1743 *url = GURL(chrome::kAboutBlankURL);
1747 void RenderViewHostImpl::SetAltErrorPageURL(const GURL& url) {
1748 Send(new ViewMsg_SetAltErrorPageURL(GetRoutingID(), url));
1751 void RenderViewHostImpl::ExitFullscreen() {
1752 RejectMouseLockOrUnlockIfNecessary();
1753 // We need to notify the contents that its fullscreen state has changed. This
1754 // is done as part of the resize message.
1755 WasResized();
1758 webkit_glue::WebPreferences RenderViewHostImpl::GetWebkitPreferences() {
1759 return delegate_->GetWebkitPrefs();
1762 void RenderViewHostImpl::UpdateFrameTree(
1763 int process_id,
1764 int route_id,
1765 const std::string& frame_tree) {
1766 frame_tree_ = frame_tree;
1767 Send(new ViewMsg_UpdateFrameTree(GetRoutingID(),
1768 process_id,
1769 route_id,
1770 frame_tree_));
1773 void RenderViewHostImpl::UpdateWebkitPreferences(
1774 const webkit_glue::WebPreferences& prefs) {
1775 Send(new ViewMsg_UpdateWebPreferences(GetRoutingID(), prefs));
1778 void RenderViewHostImpl::NotifyTimezoneChange() {
1779 Send(new ViewMsg_TimezoneChange(GetRoutingID()));
1782 void RenderViewHostImpl::ClearFocusedNode() {
1783 Send(new ViewMsg_ClearFocusedNode(GetRoutingID()));
1786 void RenderViewHostImpl::SetZoomLevel(double level) {
1787 Send(new ViewMsg_SetZoomLevel(GetRoutingID(), level));
1790 void RenderViewHostImpl::Zoom(PageZoom zoom) {
1791 Send(new ViewMsg_Zoom(GetRoutingID(), zoom));
1794 void RenderViewHostImpl::ReloadFrame() {
1795 Send(new ViewMsg_ReloadFrame(GetRoutingID()));
1798 void RenderViewHostImpl::Find(int request_id,
1799 const string16& search_text,
1800 const WebKit::WebFindOptions& options) {
1801 Send(new ViewMsg_Find(GetRoutingID(), request_id, search_text, options));
1804 void RenderViewHostImpl::InsertCSS(const string16& frame_xpath,
1805 const std::string& css) {
1806 Send(new ViewMsg_CSSInsertRequest(GetRoutingID(), frame_xpath, css));
1809 void RenderViewHostImpl::DisableScrollbarsForThreshold(const gfx::Size& size) {
1810 Send(new ViewMsg_DisableScrollbarsForSmallWindows(GetRoutingID(), size));
1813 void RenderViewHostImpl::EnablePreferredSizeMode() {
1814 Send(new ViewMsg_EnablePreferredSizeChangedMode(GetRoutingID()));
1817 void RenderViewHostImpl::EnableAutoResize(const gfx::Size& min_size,
1818 const gfx::Size& max_size) {
1819 SetShouldAutoResize(true);
1820 Send(new ViewMsg_EnableAutoResize(GetRoutingID(), min_size, max_size));
1823 void RenderViewHostImpl::DisableAutoResize(const gfx::Size& new_size) {
1824 SetShouldAutoResize(false);
1825 Send(new ViewMsg_DisableAutoResize(GetRoutingID(), new_size));
1828 void RenderViewHostImpl::ExecuteCustomContextMenuCommand(
1829 int action, const CustomContextMenuContext& context) {
1830 Send(new ViewMsg_CustomContextMenuAction(GetRoutingID(), context, action));
1833 void RenderViewHostImpl::NotifyContextMenuClosed(
1834 const CustomContextMenuContext& context) {
1835 Send(new ViewMsg_ContextMenuClosed(GetRoutingID(), context));
1838 void RenderViewHostImpl::CopyImageAt(int x, int y) {
1839 Send(new ViewMsg_CopyImageAt(GetRoutingID(), x, y));
1842 void RenderViewHostImpl::ExecuteMediaPlayerActionAtLocation(
1843 const gfx::Point& location, const WebKit::WebMediaPlayerAction& action) {
1844 Send(new ViewMsg_MediaPlayerActionAt(GetRoutingID(), location, action));
1847 void RenderViewHostImpl::ExecutePluginActionAtLocation(
1848 const gfx::Point& location, const WebKit::WebPluginAction& action) {
1849 Send(new ViewMsg_PluginActionAt(GetRoutingID(), location, action));
1852 void RenderViewHostImpl::DisassociateFromPopupCount() {
1853 Send(new ViewMsg_DisassociateFromPopupCount(GetRoutingID()));
1856 void RenderViewHostImpl::NotifyMoveOrResizeStarted() {
1857 Send(new ViewMsg_MoveOrResizeStarted(GetRoutingID()));
1860 void RenderViewHostImpl::StopFinding(StopFindAction action) {
1861 Send(new ViewMsg_StopFinding(GetRoutingID(), action));
1864 void RenderViewHostImpl::OnAccessibilityNotifications(
1865 const std::vector<AccessibilityHostMsg_NotificationParams>& params) {
1866 if (view_ && !is_swapped_out_)
1867 view_->OnAccessibilityNotifications(params);
1869 for (unsigned i = 0; i < params.size(); i++) {
1870 const AccessibilityHostMsg_NotificationParams& param = params[i];
1871 AccessibilityNotification src_type = param.notification_type;
1873 if ((src_type == AccessibilityNotificationLayoutComplete ||
1874 src_type == AccessibilityNotificationLoadComplete) &&
1875 save_accessibility_tree_for_testing_) {
1876 accessibility_tree_ = param.acc_tree;
1879 NotificationType dst_type;
1880 if (src_type == AccessibilityNotificationLoadComplete)
1881 dst_type = NOTIFICATION_ACCESSIBILITY_LOAD_COMPLETE;
1882 else if (src_type == AccessibilityNotificationLayoutComplete)
1883 dst_type = NOTIFICATION_ACCESSIBILITY_LAYOUT_COMPLETE;
1884 else
1885 dst_type = NOTIFICATION_ACCESSIBILITY_OTHER;
1886 NotificationService::current()->Notify(
1887 dst_type,
1888 Source<RenderViewHost>(this),
1889 NotificationService::NoDetails());
1892 Send(new AccessibilityMsg_Notifications_ACK(GetRoutingID()));
1895 void RenderViewHostImpl::OnScriptEvalResponse(int id, const ListValue& result) {
1896 const Value* result_value;
1897 if (!result.Get(0, &result_value)) {
1898 // Programming error or rogue renderer.
1899 NOTREACHED() << "Got bad arguments for OnScriptEvalResponse";
1900 return;
1902 std::pair<int, const Value*> details(id, result_value);
1903 NotificationService::current()->Notify(
1904 NOTIFICATION_EXECUTE_JAVASCRIPT_RESULT,
1905 Source<RenderViewHost>(this),
1906 Details<std::pair<int, const Value*> >(&details));
1909 void RenderViewHostImpl::OnDidZoomURL(double zoom_level,
1910 bool remember,
1911 const GURL& url) {
1912 HostZoomMapImpl* host_zoom_map = static_cast<HostZoomMapImpl*>(
1913 HostZoomMap::GetForBrowserContext(GetProcess()->GetBrowserContext()));
1914 if (remember) {
1915 host_zoom_map->SetZoomLevel(net::GetHostOrSpecFromURL(url), zoom_level);
1916 } else {
1917 host_zoom_map->SetTemporaryZoomLevel(
1918 GetProcess()->GetID(), GetRoutingID(), zoom_level);
1922 void RenderViewHostImpl::OnMediaNotification(int64 player_cookie,
1923 bool has_video,
1924 bool has_audio,
1925 bool is_playing) {
1926 if (is_playing) {
1927 PowerSaveBlocker* blocker = NULL;
1928 if (has_video) {
1929 blocker = new PowerSaveBlocker(
1930 PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep,
1931 "Playing video");
1932 } else if (has_audio) {
1933 blocker = new PowerSaveBlocker(
1934 PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension,
1935 "Playing audio");
1938 if (blocker)
1939 power_save_blockers_[player_cookie] = blocker;
1940 } else {
1941 delete power_save_blockers_[player_cookie];
1942 power_save_blockers_.erase(player_cookie);
1946 #if defined(OS_ANDROID)
1947 void RenderViewHostImpl::OnMsgDidChangeBodyBackgroundColor(SkColor color) {
1948 if (GetView())
1949 GetView()->SetCachedBackgroundColor(color);
1952 void RenderViewHostImpl::OnStartContentIntent(const GURL& content_url) {
1953 if (GetView())
1954 GetView()->StartContentIntent(content_url);
1956 #endif
1958 void RenderViewHostImpl::OnRequestDesktopNotificationPermission(
1959 const GURL& source_origin, int callback_context) {
1960 GetContentClient()->browser()->RequestDesktopNotificationPermission(
1961 source_origin, callback_context, GetProcess()->GetID(), GetRoutingID());
1964 void RenderViewHostImpl::OnShowDesktopNotification(
1965 const ShowDesktopNotificationHostMsgParams& params) {
1966 // Disallow HTML notifications from javascript: and file: schemes as this
1967 // allows unwanted cross-domain access.
1968 GURL url = params.contents_url;
1969 if (params.is_html &&
1970 (url.SchemeIs(chrome::kJavaScriptScheme) ||
1971 url.SchemeIs(chrome::kFileScheme))) {
1972 return;
1975 GetContentClient()->browser()->ShowDesktopNotification(
1976 params, GetProcess()->GetID(), GetRoutingID(), false);
1979 void RenderViewHostImpl::OnCancelDesktopNotification(int notification_id) {
1980 GetContentClient()->browser()->CancelDesktopNotification(
1981 GetProcess()->GetID(), GetRoutingID(), notification_id);
1984 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1985 void RenderViewHostImpl::OnMsgShowPopup(
1986 const ViewHostMsg_ShowPopup_Params& params) {
1987 RenderViewHostDelegateView* view = delegate_->GetDelegateView();
1988 if (view) {
1989 view->ShowPopupMenu(params.bounds,
1990 params.item_height,
1991 params.item_font_size,
1992 params.selected_item,
1993 params.popup_items,
1994 params.right_aligned,
1995 params.allow_multiple_selection);
1998 #endif
2000 void RenderViewHostImpl::OnRunFileChooser(const FileChooserParams& params) {
2001 delegate_->RunFileChooser(this, params);
2004 void RenderViewHostImpl::OnDomOperationResponse(
2005 const std::string& json_string, int automation_id) {
2006 DomOperationNotificationDetails details(json_string, automation_id);
2007 NotificationService::current()->Notify(
2008 NOTIFICATION_DOM_OPERATION_RESPONSE,
2009 Source<RenderViewHost>(this),
2010 Details<DomOperationNotificationDetails>(&details));
2013 void RenderViewHostImpl::OnFrameTreeUpdated(const std::string& frame_tree) {
2014 // TODO(nasko): Remove once http://crbug.com/153701 is fixed.
2015 DCHECK(false);
2016 frame_tree_ = frame_tree;
2017 delegate_->DidUpdateFrameTree(this);
2020 void RenderViewHostImpl::SetSwappedOut(bool is_swapped_out) {
2021 is_swapped_out_ = is_swapped_out;
2023 // Whenever we change swap out state, we should not be waiting for
2024 // beforeunload or unload acks. We clear them here to be safe, since they
2025 // can cause navigations to be ignored in OnMsgNavigate.
2026 is_waiting_for_beforeunload_ack_ = false;
2027 is_waiting_for_unload_ack_ = false;
2028 has_timed_out_on_unload_ = false;
2031 void RenderViewHostImpl::ClearPowerSaveBlockers() {
2032 STLDeleteValues(&power_save_blockers_);
2035 } // namespace content