cc: Make picture pile base thread safe.
[chromium-blink-merge.git] / content / browser / frame_host / render_frame_host_impl.cc
blob2b38c1866e59927ba1552aec5115424b264a0696
1 // Copyright 2013 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/frame_host/render_frame_host_impl.h"
7 #include "base/bind.h"
8 #include "base/command_line.h"
9 #include "base/containers/hash_tables.h"
10 #include "base/lazy_instance.h"
11 #include "base/metrics/histogram.h"
12 #include "base/metrics/user_metrics_action.h"
13 #include "base/time/time.h"
14 #include "content/browser/accessibility/accessibility_mode_helper.h"
15 #include "content/browser/accessibility/browser_accessibility_manager.h"
16 #include "content/browser/accessibility/browser_accessibility_state_impl.h"
17 #include "content/browser/child_process_security_policy_impl.h"
18 #include "content/browser/frame_host/cross_process_frame_connector.h"
19 #include "content/browser/frame_host/cross_site_transferring_request.h"
20 #include "content/browser/frame_host/frame_accessibility.h"
21 #include "content/browser/frame_host/frame_tree.h"
22 #include "content/browser/frame_host/frame_tree_node.h"
23 #include "content/browser/frame_host/navigator.h"
24 #include "content/browser/frame_host/render_frame_host_delegate.h"
25 #include "content/browser/frame_host/render_frame_proxy_host.h"
26 #include "content/browser/frame_host/render_widget_host_view_child_frame.h"
27 #include "content/browser/renderer_host/input/input_router.h"
28 #include "content/browser/renderer_host/input/timeout_monitor.h"
29 #include "content/browser/renderer_host/render_process_host_impl.h"
30 #include "content/browser/renderer_host/render_view_host_delegate.h"
31 #include "content/browser/renderer_host/render_view_host_delegate_view.h"
32 #include "content/browser/renderer_host/render_view_host_impl.h"
33 #include "content/browser/renderer_host/render_widget_host_impl.h"
34 #include "content/browser/renderer_host/render_widget_host_view_base.h"
35 #include "content/browser/transition_request_manager.h"
36 #include "content/common/accessibility_messages.h"
37 #include "content/common/desktop_notification_messages.h"
38 #include "content/common/frame_messages.h"
39 #include "content/common/input_messages.h"
40 #include "content/common/inter_process_time_ticks_converter.h"
41 #include "content/common/navigation_params.h"
42 #include "content/common/platform_notification_messages.h"
43 #include "content/common/render_frame_setup.mojom.h"
44 #include "content/common/swapped_out_messages.h"
45 #include "content/public/browser/ax_event_notification_details.h"
46 #include "content/public/browser/browser_accessibility_state.h"
47 #include "content/public/browser/browser_context.h"
48 #include "content/public/browser/browser_plugin_guest_manager.h"
49 #include "content/public/browser/browser_thread.h"
50 #include "content/public/browser/content_browser_client.h"
51 #include "content/public/browser/desktop_notification_delegate.h"
52 #include "content/public/browser/render_process_host.h"
53 #include "content/public/browser/render_widget_host_view.h"
54 #include "content/public/browser/stream_handle.h"
55 #include "content/public/browser/user_metrics.h"
56 #include "content/public/common/content_constants.h"
57 #include "content/public/common/content_switches.h"
58 #include "content/public/common/url_constants.h"
59 #include "content/public/common/url_utils.h"
60 #include "ui/accessibility/ax_tree.h"
61 #include "url/gurl.h"
63 #if defined(OS_MACOSX)
64 #include "content/browser/frame_host/popup_menu_helper_mac.h"
65 #endif
67 using base::TimeDelta;
69 namespace content {
71 namespace {
73 // The next value to use for the accessibility reset token.
74 int g_next_accessibility_reset_token = 1;
76 // The (process id, routing id) pair that identifies one RenderFrame.
77 typedef std::pair<int32, int32> RenderFrameHostID;
78 typedef base::hash_map<RenderFrameHostID, RenderFrameHostImpl*>
79 RoutingIDFrameMap;
80 base::LazyInstance<RoutingIDFrameMap> g_routing_id_frame_map =
81 LAZY_INSTANCE_INITIALIZER;
83 class DesktopNotificationDelegateImpl : public DesktopNotificationDelegate {
84 public:
85 DesktopNotificationDelegateImpl(RenderFrameHost* render_frame_host,
86 int notification_id)
87 : render_process_id_(render_frame_host->GetProcess()->GetID()),
88 render_frame_id_(render_frame_host->GetRoutingID()),
89 notification_id_(notification_id) {}
91 ~DesktopNotificationDelegateImpl() override {}
93 void NotificationDisplayed() override {
94 RenderFrameHost* rfh =
95 RenderFrameHost::FromID(render_process_id_, render_frame_id_);
96 if (!rfh)
97 return;
99 rfh->Send(new DesktopNotificationMsg_PostDisplay(
100 rfh->GetRoutingID(), notification_id_));
103 void NotificationError() override {
104 RenderFrameHost* rfh =
105 RenderFrameHost::FromID(render_process_id_, render_frame_id_);
106 if (!rfh)
107 return;
109 rfh->Send(new DesktopNotificationMsg_PostError(
110 rfh->GetRoutingID(), notification_id_));
113 void NotificationClosed(bool by_user) override {
114 RenderFrameHost* rfh =
115 RenderFrameHost::FromID(render_process_id_, render_frame_id_);
116 if (!rfh)
117 return;
119 rfh->Send(new DesktopNotificationMsg_PostClose(
120 rfh->GetRoutingID(), notification_id_, by_user));
121 static_cast<RenderFrameHostImpl*>(rfh)->NotificationClosed(
122 notification_id_);
125 void NotificationClick() override {
126 RenderFrameHost* rfh =
127 RenderFrameHost::FromID(render_process_id_, render_frame_id_);
128 if (!rfh)
129 return;
131 rfh->Send(new DesktopNotificationMsg_PostClick(
132 rfh->GetRoutingID(), notification_id_));
135 private:
136 int render_process_id_;
137 int render_frame_id_;
138 int notification_id_;
141 // Translate a WebKit text direction into a base::i18n one.
142 base::i18n::TextDirection WebTextDirectionToChromeTextDirection(
143 blink::WebTextDirection dir) {
144 switch (dir) {
145 case blink::WebTextDirectionLeftToRight:
146 return base::i18n::LEFT_TO_RIGHT;
147 case blink::WebTextDirectionRightToLeft:
148 return base::i18n::RIGHT_TO_LEFT;
149 default:
150 NOTREACHED();
151 return base::i18n::UNKNOWN_DIRECTION;
155 } // namespace
157 // static
158 bool RenderFrameHostImpl::IsRFHStateActive(RenderFrameHostImplState rfh_state) {
159 return rfh_state == STATE_DEFAULT;
162 // static
163 RenderFrameHost* RenderFrameHost::FromID(int render_process_id,
164 int render_frame_id) {
165 return RenderFrameHostImpl::FromID(render_process_id, render_frame_id);
168 // static
169 RenderFrameHostImpl* RenderFrameHostImpl::FromID(int process_id,
170 int routing_id) {
171 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
172 RoutingIDFrameMap* frames = g_routing_id_frame_map.Pointer();
173 RoutingIDFrameMap::iterator it = frames->find(
174 RenderFrameHostID(process_id, routing_id));
175 return it == frames->end() ? NULL : it->second;
178 RenderFrameHostImpl::RenderFrameHostImpl(RenderViewHostImpl* render_view_host,
179 RenderFrameHostDelegate* delegate,
180 FrameTree* frame_tree,
181 FrameTreeNode* frame_tree_node,
182 int routing_id,
183 bool is_swapped_out)
184 : render_view_host_(render_view_host),
185 delegate_(delegate),
186 cross_process_frame_connector_(NULL),
187 render_frame_proxy_host_(NULL),
188 frame_tree_(frame_tree),
189 frame_tree_node_(frame_tree_node),
190 routing_id_(routing_id),
191 render_frame_created_(false),
192 navigations_suspended_(false),
193 is_waiting_for_beforeunload_ack_(false),
194 unload_ack_is_for_cross_site_transition_(false),
195 accessibility_reset_token_(0),
196 accessibility_reset_count_(0),
197 no_create_browser_accessibility_manager_for_testing_(false),
198 weak_ptr_factory_(this) {
199 frame_tree_->RegisterRenderFrameHost(this);
200 GetProcess()->AddRoute(routing_id_, this);
201 g_routing_id_frame_map.Get().insert(std::make_pair(
202 RenderFrameHostID(GetProcess()->GetID(), routing_id_),
203 this));
205 if (is_swapped_out) {
206 rfh_state_ = STATE_SWAPPED_OUT;
207 } else {
208 rfh_state_ = STATE_DEFAULT;
209 GetSiteInstance()->increment_active_frame_count();
212 SetUpMojoIfNeeded();
214 swapout_event_monitor_timeout_.reset(new TimeoutMonitor(base::Bind(
215 &RenderFrameHostImpl::OnSwappedOut, weak_ptr_factory_.GetWeakPtr())));
218 RenderFrameHostImpl::~RenderFrameHostImpl() {
219 GetProcess()->RemoveRoute(routing_id_);
220 g_routing_id_frame_map.Get().erase(
221 RenderFrameHostID(GetProcess()->GetID(), routing_id_));
223 if (delegate_)
224 delegate_->RenderFrameDeleted(this);
226 FrameAccessibility::GetInstance()->OnRenderFrameHostDestroyed(this);
228 // If this was swapped out, it already decremented the active frame count of
229 // the SiteInstance it belongs to.
230 if (IsRFHStateActive(rfh_state_))
231 GetSiteInstance()->decrement_active_frame_count();
233 // Notify the FrameTree that this RFH is going away, allowing it to shut down
234 // the corresponding RenderViewHost if it is no longer needed.
235 frame_tree_->UnregisterRenderFrameHost(this);
238 int RenderFrameHostImpl::GetRoutingID() {
239 return routing_id_;
242 SiteInstanceImpl* RenderFrameHostImpl::GetSiteInstance() {
243 return render_view_host_->GetSiteInstance();
246 RenderProcessHost* RenderFrameHostImpl::GetProcess() {
247 // TODO(nasko): This should return its own process, once we have working
248 // cross-process navigation for subframes.
249 return render_view_host_->GetProcess();
252 RenderFrameHost* RenderFrameHostImpl::GetParent() {
253 FrameTreeNode* parent_node = frame_tree_node_->parent();
254 if (!parent_node)
255 return NULL;
256 return parent_node->current_frame_host();
259 const std::string& RenderFrameHostImpl::GetFrameName() {
260 return frame_tree_node_->frame_name();
263 bool RenderFrameHostImpl::IsCrossProcessSubframe() {
264 FrameTreeNode* parent_node = frame_tree_node_->parent();
265 if (!parent_node)
266 return false;
267 return GetSiteInstance() !=
268 parent_node->current_frame_host()->GetSiteInstance();
271 GURL RenderFrameHostImpl::GetLastCommittedURL() {
272 return frame_tree_node_->current_url();
275 gfx::NativeView RenderFrameHostImpl::GetNativeView() {
276 RenderWidgetHostView* view = render_view_host_->GetView();
277 if (!view)
278 return NULL;
279 return view->GetNativeView();
282 void RenderFrameHostImpl::ExecuteJavaScript(
283 const base::string16& javascript) {
284 Send(new FrameMsg_JavaScriptExecuteRequest(routing_id_,
285 javascript,
286 0, false));
289 void RenderFrameHostImpl::ExecuteJavaScript(
290 const base::string16& javascript,
291 const JavaScriptResultCallback& callback) {
292 static int next_id = 1;
293 int key = next_id++;
294 Send(new FrameMsg_JavaScriptExecuteRequest(routing_id_,
295 javascript,
296 key, true));
297 javascript_callbacks_.insert(std::make_pair(key, callback));
300 void RenderFrameHostImpl::ExecuteJavaScriptForTests(
301 const base::string16& javascript) {
302 Send(new FrameMsg_JavaScriptExecuteRequestForTests(routing_id_,
303 javascript,
304 0, false));
307 RenderViewHost* RenderFrameHostImpl::GetRenderViewHost() {
308 return render_view_host_;
311 ServiceRegistry* RenderFrameHostImpl::GetServiceRegistry() {
312 return service_registry_.get();
315 bool RenderFrameHostImpl::Send(IPC::Message* message) {
316 if (IPC_MESSAGE_ID_CLASS(message->type()) == InputMsgStart) {
317 return render_view_host_->input_router()->SendInput(
318 make_scoped_ptr(message));
321 // Route IPCs through the RenderFrameProxyHost when in swapped out state.
322 // Note: For subframes in --site-per-process mode, we don't use swapped out
323 // RenderFrameHosts.
324 if (frame_tree_node_->IsMainFrame() && is_swapped_out()) {
325 DCHECK(render_frame_proxy_host_);
326 return render_frame_proxy_host_->Send(message);
329 return GetProcess()->Send(message);
332 bool RenderFrameHostImpl::OnMessageReceived(const IPC::Message &msg) {
333 // Filter out most IPC messages if this frame is swapped out.
334 // We still want to handle certain ACKs to keep our state consistent.
335 if (is_swapped_out()) {
336 if (!SwappedOutMessages::CanHandleWhileSwappedOut(msg)) {
337 // If this is a synchronous message and we decided not to handle it,
338 // we must send an error reply, or else the renderer will be stuck
339 // and won't respond to future requests.
340 if (msg.is_sync()) {
341 IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
342 reply->set_reply_error();
343 Send(reply);
345 // Don't continue looking for someone to handle it.
346 return true;
350 if (delegate_->OnMessageReceived(this, msg))
351 return true;
353 RenderFrameProxyHost* proxy =
354 frame_tree_node_->render_manager()->GetProxyToParent();
355 if (proxy && proxy->cross_process_frame_connector() &&
356 proxy->cross_process_frame_connector()->OnMessageReceived(msg))
357 return true;
359 bool handled = true;
360 IPC_BEGIN_MESSAGE_MAP(RenderFrameHostImpl, msg)
361 IPC_MESSAGE_HANDLER(FrameHostMsg_AddMessageToConsole, OnAddMessageToConsole)
362 IPC_MESSAGE_HANDLER(FrameHostMsg_Detach, OnDetach)
363 IPC_MESSAGE_HANDLER(FrameHostMsg_FrameFocused, OnFrameFocused)
364 IPC_MESSAGE_HANDLER(FrameHostMsg_DidStartProvisionalLoadForFrame,
365 OnDidStartProvisionalLoadForFrame)
366 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailProvisionalLoadWithError,
367 OnDidFailProvisionalLoadWithError)
368 IPC_MESSAGE_HANDLER(FrameHostMsg_DidFailLoadWithError,
369 OnDidFailLoadWithError)
370 IPC_MESSAGE_HANDLER_GENERIC(FrameHostMsg_DidCommitProvisionalLoad,
371 OnDidCommitProvisionalLoad(msg))
372 IPC_MESSAGE_HANDLER(FrameHostMsg_OpenURL, OnOpenURL)
373 IPC_MESSAGE_HANDLER(FrameHostMsg_DocumentOnLoadCompleted,
374 OnDocumentOnLoadCompleted)
375 IPC_MESSAGE_HANDLER(FrameHostMsg_BeforeUnload_ACK, OnBeforeUnloadACK)
376 IPC_MESSAGE_HANDLER(FrameHostMsg_SwapOut_ACK, OnSwapOutACK)
377 IPC_MESSAGE_HANDLER(FrameHostMsg_ContextMenu, OnContextMenu)
378 IPC_MESSAGE_HANDLER(FrameHostMsg_JavaScriptExecuteResponse,
379 OnJavaScriptExecuteResponse)
380 IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunJavaScriptMessage,
381 OnRunJavaScriptMessage)
382 IPC_MESSAGE_HANDLER_DELAY_REPLY(FrameHostMsg_RunBeforeUnloadConfirm,
383 OnRunBeforeUnloadConfirm)
384 IPC_MESSAGE_HANDLER(FrameHostMsg_DidAccessInitialDocument,
385 OnDidAccessInitialDocument)
386 IPC_MESSAGE_HANDLER(FrameHostMsg_DidDisownOpener, OnDidDisownOpener)
387 IPC_MESSAGE_HANDLER(FrameHostMsg_DidAssignPageId, OnDidAssignPageId)
388 IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateTitle, OnUpdateTitle)
389 IPC_MESSAGE_HANDLER(FrameHostMsg_UpdateEncoding, OnUpdateEncoding)
390 IPC_MESSAGE_HANDLER(FrameHostMsg_BeginNavigation,
391 OnBeginNavigation)
392 IPC_MESSAGE_HANDLER(PlatformNotificationHostMsg_RequestPermission,
393 OnRequestPlatformNotificationPermission)
394 IPC_MESSAGE_HANDLER(DesktopNotificationHostMsg_Show,
395 OnShowDesktopNotification)
396 IPC_MESSAGE_HANDLER(DesktopNotificationHostMsg_Cancel,
397 OnCancelDesktopNotification)
398 IPC_MESSAGE_HANDLER(FrameHostMsg_TextSurroundingSelectionResponse,
399 OnTextSurroundingSelectionResponse)
400 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_Events, OnAccessibilityEvents)
401 IPC_MESSAGE_HANDLER(AccessibilityHostMsg_LocationChanges,
402 OnAccessibilityLocationChanges)
403 #if defined(OS_MACOSX) || defined(OS_ANDROID)
404 IPC_MESSAGE_HANDLER(FrameHostMsg_ShowPopup, OnShowPopup)
405 IPC_MESSAGE_HANDLER(FrameHostMsg_HidePopup, OnHidePopup)
406 #endif
407 IPC_END_MESSAGE_MAP()
409 // No further actions here, since we may have been deleted.
410 return handled;
413 void RenderFrameHostImpl::AccessibilitySetFocus(int object_id) {
414 Send(new AccessibilityMsg_SetFocus(routing_id_, object_id));
417 void RenderFrameHostImpl::AccessibilityDoDefaultAction(int object_id) {
418 Send(new AccessibilityMsg_DoDefaultAction(routing_id_, object_id));
421 void RenderFrameHostImpl::AccessibilityShowMenu(
422 const gfx::Point& global_point) {
423 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
424 render_view_host_->GetView());
425 if (view)
426 view->AccessibilityShowMenu(global_point);
429 void RenderFrameHostImpl::AccessibilityScrollToMakeVisible(
430 int acc_obj_id, const gfx::Rect& subfocus) {
431 Send(new AccessibilityMsg_ScrollToMakeVisible(
432 routing_id_, acc_obj_id, subfocus));
435 void RenderFrameHostImpl::AccessibilityScrollToPoint(
436 int acc_obj_id, const gfx::Point& point) {
437 Send(new AccessibilityMsg_ScrollToPoint(
438 routing_id_, acc_obj_id, point));
441 void RenderFrameHostImpl::AccessibilitySetTextSelection(
442 int object_id, int start_offset, int end_offset) {
443 Send(new AccessibilityMsg_SetTextSelection(
444 routing_id_, object_id, start_offset, end_offset));
447 bool RenderFrameHostImpl::AccessibilityViewHasFocus() const {
448 RenderWidgetHostView* view = render_view_host_->GetView();
449 if (view)
450 return view->HasFocus();
451 return false;
454 gfx::Rect RenderFrameHostImpl::AccessibilityGetViewBounds() const {
455 RenderWidgetHostView* view = render_view_host_->GetView();
456 if (view)
457 return view->GetViewBounds();
458 return gfx::Rect();
461 gfx::Point RenderFrameHostImpl::AccessibilityOriginInScreen(
462 const gfx::Rect& bounds) const {
463 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
464 render_view_host_->GetView());
465 if (view)
466 return view->AccessibilityOriginInScreen(bounds);
467 return gfx::Point();
470 void RenderFrameHostImpl::AccessibilityHitTest(const gfx::Point& point) {
471 Send(new AccessibilityMsg_HitTest(routing_id_, point));
474 void RenderFrameHostImpl::AccessibilityFatalError() {
475 browser_accessibility_manager_.reset(NULL);
476 if (accessibility_reset_token_)
477 return;
479 accessibility_reset_count_++;
480 if (accessibility_reset_count_ >= kMaxAccessibilityResets) {
481 Send(new AccessibilityMsg_FatalError(routing_id_));
482 } else {
483 accessibility_reset_token_ = g_next_accessibility_reset_token++;
484 UMA_HISTOGRAM_COUNTS("Accessibility.FrameResetCount", 1);
485 Send(new AccessibilityMsg_Reset(routing_id_, accessibility_reset_token_));
489 gfx::AcceleratedWidget
490 RenderFrameHostImpl::AccessibilityGetAcceleratedWidget() {
491 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
492 render_view_host_->GetView());
493 if (view)
494 return view->AccessibilityGetAcceleratedWidget();
495 return gfx::kNullAcceleratedWidget;
498 gfx::NativeViewAccessible
499 RenderFrameHostImpl::AccessibilityGetNativeViewAccessible() {
500 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
501 render_view_host_->GetView());
502 if (view)
503 return view->AccessibilityGetNativeViewAccessible();
504 return NULL;
507 BrowserAccessibilityManager* RenderFrameHostImpl::AccessibilityGetChildFrame(
508 int accessibility_node_id) {
509 RenderFrameHostImpl* child_frame =
510 FrameAccessibility::GetInstance()->GetChild(this, accessibility_node_id);
511 if (!child_frame)
512 return NULL;
514 // Return NULL if this isn't an out-of-process iframe. Same-process iframes
515 // are already part of the accessibility tree.
516 if (child_frame->GetProcess()->GetID() == GetProcess()->GetID())
517 return NULL;
519 // As a sanity check, make sure the frame we're going to return belongs
520 // to the same BrowserContext.
521 if (GetSiteInstance()->GetBrowserContext() !=
522 child_frame->GetSiteInstance()->GetBrowserContext()) {
523 NOTREACHED();
524 return NULL;
527 return child_frame->GetOrCreateBrowserAccessibilityManager();
530 BrowserAccessibility* RenderFrameHostImpl::AccessibilityGetParentFrame() {
531 RenderFrameHostImpl* parent_frame = NULL;
532 int parent_node_id = 0;
533 if (!FrameAccessibility::GetInstance()->GetParent(
534 this, &parent_frame, &parent_node_id)) {
535 return NULL;
538 // As a sanity check, make sure the frame we're going to return belongs
539 // to the same BrowserContext.
540 if (GetSiteInstance()->GetBrowserContext() !=
541 parent_frame->GetSiteInstance()->GetBrowserContext()) {
542 NOTREACHED();
543 return NULL;
546 BrowserAccessibilityManager* manager =
547 parent_frame->browser_accessibility_manager();
548 if (!manager)
549 return NULL;
551 return manager->GetFromID(parent_node_id);
554 bool RenderFrameHostImpl::CreateRenderFrame(int parent_routing_id) {
555 TRACE_EVENT0("navigation", "RenderFrameHostImpl::CreateRenderFrame");
556 DCHECK(!IsRenderFrameLive()) << "Creating frame twice";
558 // The process may (if we're sharing a process with another host that already
559 // initialized it) or may not (we have our own process or the old process
560 // crashed) have been initialized. Calling Init multiple times will be
561 // ignored, so this is safe.
562 if (!GetProcess()->Init())
563 return false;
565 DCHECK(GetProcess()->HasConnection());
567 Send(new FrameMsg_NewFrame(routing_id_, parent_routing_id));
569 // The renderer now has a RenderFrame for this RenderFrameHost. Note that
570 // this path is only used for out-of-process iframes. Main frame RenderFrames
571 // are created with their RenderView, and same-site iframes are created at the
572 // time of OnCreateChildFrame.
573 set_render_frame_created(true);
575 return true;
578 bool RenderFrameHostImpl::IsRenderFrameLive() {
579 // RenderFrames are created for main frames at the same time as RenderViews,
580 // so we rely on IsRenderViewLive. For subframes, we keep track of each
581 // RenderFrame individually with render_frame_created_.
582 bool is_live = !GetParent() ?
583 render_view_host_->IsRenderViewLive() :
584 GetProcess()->HasConnection() && render_frame_created_;
586 // Sanity check: the RenderView should always be live if the RenderFrame is.
587 DCHECK(!is_live || render_view_host_->IsRenderViewLive());
589 return is_live;
592 void RenderFrameHostImpl::Init() {
593 GetProcess()->ResumeRequestsForView(routing_id_);
596 void RenderFrameHostImpl::OnAddMessageToConsole(
597 int32 level,
598 const base::string16& message,
599 int32 line_no,
600 const base::string16& source_id) {
601 if (delegate_->AddMessageToConsole(level, message, line_no, source_id))
602 return;
604 // Pass through log level only on WebUI pages to limit console spew.
605 int32 resolved_level =
606 HasWebUIScheme(delegate_->GetMainFrameLastCommittedURL()) ? level : 0;
608 if (resolved_level >= ::logging::GetMinLogLevel()) {
609 logging::LogMessage("CONSOLE", line_no, resolved_level).stream() << "\"" <<
610 message << "\", source: " << source_id << " (" << line_no << ")";
614 void RenderFrameHostImpl::OnCreateChildFrame(int new_routing_id,
615 const std::string& frame_name) {
616 // It is possible that while a new RenderFrameHost was committed, the
617 // RenderFrame corresponding to this host sent an IPC message to create a
618 // frame and it is delivered after this host is swapped out.
619 // Ignore such messages, as we know this RenderFrameHost is going away.
620 if (rfh_state_ != RenderFrameHostImpl::STATE_DEFAULT)
621 return;
623 RenderFrameHostImpl* new_frame = frame_tree_->AddFrame(
624 frame_tree_node_, GetProcess()->GetID(), new_routing_id, frame_name);
625 if (!new_frame)
626 return;
628 // We know that the RenderFrame has been created in this case, immediately
629 // after the CreateChildFrame IPC was sent.
630 new_frame->set_render_frame_created(true);
632 if (delegate_)
633 delegate_->RenderFrameCreated(new_frame);
636 void RenderFrameHostImpl::OnDetach() {
637 frame_tree_->RemoveFrame(frame_tree_node_);
640 void RenderFrameHostImpl::OnFrameFocused() {
641 frame_tree_->SetFocusedFrame(frame_tree_node_);
644 void RenderFrameHostImpl::OnOpenURL(
645 const FrameHostMsg_OpenURL_Params& params) {
646 GURL validated_url(params.url);
647 GetProcess()->FilterURL(false, &validated_url);
649 TRACE_EVENT1("navigation", "RenderFrameHostImpl::OnOpenURL",
650 "url", validated_url.possibly_invalid_spec());
651 frame_tree_node_->navigator()->RequestOpenURL(
652 this, validated_url, params.referrer, params.disposition,
653 params.should_replace_current_entry, params.user_gesture);
656 void RenderFrameHostImpl::OnDocumentOnLoadCompleted() {
657 // This message is only sent for top-level frames. TODO(avi): when frame tree
658 // mirroring works correctly, add a check here to enforce it.
659 delegate_->DocumentOnLoadCompleted(this);
662 void RenderFrameHostImpl::OnDidStartProvisionalLoadForFrame(
663 const GURL& url,
664 bool is_transition_navigation) {
665 frame_tree_node_->navigator()->DidStartProvisionalLoad(
666 this, url, is_transition_navigation);
669 void RenderFrameHostImpl::OnDidFailProvisionalLoadWithError(
670 const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) {
671 frame_tree_node_->navigator()->DidFailProvisionalLoadWithError(this, params);
674 void RenderFrameHostImpl::OnDidFailLoadWithError(
675 const GURL& url,
676 int error_code,
677 const base::string16& error_description) {
678 GURL validated_url(url);
679 GetProcess()->FilterURL(false, &validated_url);
681 frame_tree_node_->navigator()->DidFailLoadWithError(
682 this, validated_url, error_code, error_description);
685 // Called when the renderer navigates. For every frame loaded, we'll get this
686 // notification containing parameters identifying the navigation.
688 // Subframes are identified by the page transition type. For subframes loaded
689 // as part of a wider page load, the page_id will be the same as for the top
690 // level frame. If the user explicitly requests a subframe navigation, we will
691 // get a new page_id because we need to create a new navigation entry for that
692 // action.
693 void RenderFrameHostImpl::OnDidCommitProvisionalLoad(const IPC::Message& msg) {
694 // Read the parameters out of the IPC message directly to avoid making another
695 // copy when we filter the URLs.
696 PickleIterator iter(msg);
697 FrameHostMsg_DidCommitProvisionalLoad_Params validated_params;
698 if (!IPC::ParamTraits<FrameHostMsg_DidCommitProvisionalLoad_Params>::
699 Read(&msg, &iter, &validated_params))
700 return;
701 TRACE_EVENT1("navigation", "RenderFrameHostImpl::OnDidCommitProvisionalLoad",
702 "url", validated_params.url.possibly_invalid_spec());
704 // If we're waiting for a cross-site beforeunload ack from this renderer and
705 // we receive a Navigate message from the main frame, then the renderer was
706 // navigating already and sent it before hearing the FrameMsg_Stop message.
707 // We do not want to cancel the pending navigation in this case, since the
708 // old page will soon be stopped. Instead, treat this as a beforeunload ack
709 // to allow the pending navigation to continue.
710 if (is_waiting_for_beforeunload_ack_ &&
711 unload_ack_is_for_cross_site_transition_ &&
712 ui::PageTransitionIsMainFrame(validated_params.transition)) {
713 base::TimeTicks approx_renderer_start_time = send_before_unload_start_time_;
714 OnBeforeUnloadACK(true, approx_renderer_start_time, base::TimeTicks::Now());
715 return;
718 // If we're waiting for an unload ack from this renderer and we receive a
719 // Navigate message, then the renderer was navigating before it received the
720 // unload request. It will either respond to the unload request soon or our
721 // timer will expire. Either way, we should ignore this message, because we
722 // have already committed to closing this renderer.
723 if (IsWaitingForUnloadACK())
724 return;
726 RenderProcessHost* process = GetProcess();
728 // Attempts to commit certain off-limits URL should be caught more strictly
729 // than our FilterURL checks below. If a renderer violates this policy, it
730 // should be killed.
731 if (!CanCommitURL(validated_params.url)) {
732 VLOG(1) << "Blocked URL " << validated_params.url.spec();
733 validated_params.url = GURL(url::kAboutBlankURL);
734 RecordAction(base::UserMetricsAction("CanCommitURL_BlockedAndKilled"));
735 // Kills the process.
736 process->ReceivedBadMessage();
739 // Without this check, an evil renderer can trick the browser into creating
740 // a navigation entry for a banned URL. If the user clicks the back button
741 // followed by the forward button (or clicks reload, or round-trips through
742 // session restore, etc), we'll think that the browser commanded the
743 // renderer to load the URL and grant the renderer the privileges to request
744 // the URL. To prevent this attack, we block the renderer from inserting
745 // banned URLs into the navigation controller in the first place.
746 process->FilterURL(false, &validated_params.url);
747 process->FilterURL(true, &validated_params.referrer.url);
748 for (std::vector<GURL>::iterator it(validated_params.redirects.begin());
749 it != validated_params.redirects.end(); ++it) {
750 process->FilterURL(false, &(*it));
752 process->FilterURL(true, &validated_params.searchable_form_url);
754 // Without this check, the renderer can trick the browser into using
755 // filenames it can't access in a future session restore.
756 if (!render_view_host_->CanAccessFilesOfPageState(
757 validated_params.page_state)) {
758 GetProcess()->ReceivedBadMessage();
759 return;
762 accessibility_reset_count_ = 0;
763 frame_tree_node()->navigator()->DidNavigate(this, validated_params);
766 RenderWidgetHostImpl* RenderFrameHostImpl::GetRenderWidgetHost() {
767 return static_cast<RenderWidgetHostImpl*>(render_view_host_);
770 int RenderFrameHostImpl::GetEnabledBindings() {
771 return render_view_host_->GetEnabledBindings();
774 void RenderFrameHostImpl::OnCrossSiteResponse(
775 const GlobalRequestID& global_request_id,
776 scoped_ptr<CrossSiteTransferringRequest> cross_site_transferring_request,
777 const std::vector<GURL>& transfer_url_chain,
778 const Referrer& referrer,
779 ui::PageTransition page_transition,
780 bool should_replace_current_entry) {
781 frame_tree_node_->render_manager()->OnCrossSiteResponse(
782 this, global_request_id, cross_site_transferring_request.Pass(),
783 transfer_url_chain, referrer, page_transition,
784 should_replace_current_entry);
787 void RenderFrameHostImpl::OnDeferredAfterResponseStarted(
788 const GlobalRequestID& global_request_id,
789 const TransitionLayerData& transition_data) {
790 frame_tree_node_->render_manager()->OnDeferredAfterResponseStarted(
791 global_request_id, this);
793 if (GetParent() || !delegate_->WillHandleDeferAfterResponseStarted())
794 frame_tree_node_->render_manager()->ResumeResponseDeferredAtStart();
795 else
796 delegate_->DidDeferAfterResponseStarted(transition_data);
799 void RenderFrameHostImpl::SwapOut(RenderFrameProxyHost* proxy) {
800 // The end of this event is in OnSwapOutACK when the RenderFrame has completed
801 // the operation and sends back an IPC message.
802 // The trace event may not end properly if the ACK times out. We expect this
803 // to be fixed when RenderViewHostImpl::OnSwapOut moves to RenderFrameHost.
804 TRACE_EVENT_ASYNC_BEGIN0("navigation", "RenderFrameHostImpl::SwapOut", this);
806 // If this RenderFrameHost is not in the default state, it must have already
807 // gone through this, therefore just return.
808 if (rfh_state_ != RenderFrameHostImpl::STATE_DEFAULT) {
809 NOTREACHED() << "RFH should be in default state when calling SwapOut.";
810 return;
813 SetState(RenderFrameHostImpl::STATE_PENDING_SWAP_OUT);
814 swapout_event_monitor_timeout_->Start(
815 base::TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS));
817 // There may be no proxy if there are no active views in the process.
818 int proxy_routing_id = MSG_ROUTING_NONE;
819 if (proxy) {
820 set_render_frame_proxy_host(proxy);
821 proxy_routing_id = proxy->GetRoutingID();
824 if (IsRenderFrameLive())
825 Send(new FrameMsg_SwapOut(routing_id_, proxy_routing_id));
827 if (!GetParent())
828 delegate_->SwappedOut(this);
831 void RenderFrameHostImpl::OnBeforeUnloadACK(
832 bool proceed,
833 const base::TimeTicks& renderer_before_unload_start_time,
834 const base::TimeTicks& renderer_before_unload_end_time) {
835 TRACE_EVENT_ASYNC_END0(
836 "navigation", "RenderFrameHostImpl::BeforeUnload", this);
837 DCHECK(!GetParent());
838 render_view_host_->decrement_in_flight_event_count();
839 render_view_host_->StopHangMonitorTimeout();
840 // If this renderer navigated while the beforeunload request was in flight, we
841 // may have cleared this state in OnDidCommitProvisionalLoad, in which case we
842 // can ignore this message.
843 // However renderer might also be swapped out but we still want to proceed
844 // with navigation, otherwise it would block future navigations. This can
845 // happen when pending cross-site navigation is canceled by a second one just
846 // before OnDidCommitProvisionalLoad while current RVH is waiting for commit
847 // but second navigation is started from the beginning.
848 if (!is_waiting_for_beforeunload_ack_) {
849 return;
851 DCHECK(!send_before_unload_start_time_.is_null());
853 // Sets a default value for before_unload_end_time so that the browser
854 // survives a hacked renderer.
855 base::TimeTicks before_unload_end_time = renderer_before_unload_end_time;
856 if (!renderer_before_unload_start_time.is_null() &&
857 !renderer_before_unload_end_time.is_null()) {
858 // When passing TimeTicks across process boundaries, we need to compensate
859 // for any skew between the processes. Here we are converting the
860 // renderer's notion of before_unload_end_time to TimeTicks in the browser
861 // process. See comments in inter_process_time_ticks_converter.h for more.
862 base::TimeTicks receive_before_unload_ack_time = base::TimeTicks::Now();
863 InterProcessTimeTicksConverter converter(
864 LocalTimeTicks::FromTimeTicks(send_before_unload_start_time_),
865 LocalTimeTicks::FromTimeTicks(receive_before_unload_ack_time),
866 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_start_time),
867 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time));
868 LocalTimeTicks browser_before_unload_end_time =
869 converter.ToLocalTimeTicks(
870 RemoteTimeTicks::FromTimeTicks(renderer_before_unload_end_time));
871 before_unload_end_time = browser_before_unload_end_time.ToTimeTicks();
873 // Collect UMA on the inter-process skew.
874 bool is_skew_additive = false;
875 if (converter.IsSkewAdditiveForMetrics()) {
876 is_skew_additive = true;
877 base::TimeDelta skew = converter.GetSkewForMetrics();
878 if (skew >= base::TimeDelta()) {
879 UMA_HISTOGRAM_TIMES(
880 "InterProcessTimeTicks.BrowserBehind_RendererToBrowser", skew);
881 } else {
882 UMA_HISTOGRAM_TIMES(
883 "InterProcessTimeTicks.BrowserAhead_RendererToBrowser", -skew);
886 UMA_HISTOGRAM_BOOLEAN(
887 "InterProcessTimeTicks.IsSkewAdditive_RendererToBrowser",
888 is_skew_additive);
890 base::TimeDelta on_before_unload_overhead_time =
891 (receive_before_unload_ack_time - send_before_unload_start_time_) -
892 (renderer_before_unload_end_time - renderer_before_unload_start_time);
893 UMA_HISTOGRAM_TIMES("Navigation.OnBeforeUnloadOverheadTime",
894 on_before_unload_overhead_time);
896 frame_tree_node_->navigator()->LogBeforeUnloadTime(
897 renderer_before_unload_start_time, renderer_before_unload_end_time);
899 // Resets beforeunload waiting state.
900 is_waiting_for_beforeunload_ack_ = false;
901 send_before_unload_start_time_ = base::TimeTicks();
903 frame_tree_node_->render_manager()->OnBeforeUnloadACK(
904 unload_ack_is_for_cross_site_transition_, proceed,
905 before_unload_end_time);
907 // If canceled, notify the delegate to cancel its pending navigation entry.
908 if (!proceed)
909 render_view_host_->GetDelegate()->DidCancelLoading();
912 bool RenderFrameHostImpl::IsWaitingForUnloadACK() const {
913 return render_view_host_->is_waiting_for_close_ack_ ||
914 rfh_state_ == STATE_PENDING_SWAP_OUT;
917 void RenderFrameHostImpl::OnSwapOutACK() {
918 OnSwappedOut();
921 void RenderFrameHostImpl::OnSwappedOut() {
922 // Ignore spurious swap out ack.
923 if (rfh_state_ != STATE_PENDING_SWAP_OUT)
924 return;
926 TRACE_EVENT_ASYNC_END0("navigation", "RenderFrameHostImpl::SwapOut", this);
927 swapout_event_monitor_timeout_->Stop();
929 if (frame_tree_node_->render_manager()->DeleteFromPendingList(this)) {
930 // We are now deleted.
931 return;
934 // If this RFH wasn't pending deletion, then it is now swapped out.
935 SetState(RenderFrameHostImpl::STATE_SWAPPED_OUT);
938 void RenderFrameHostImpl::OnContextMenu(const ContextMenuParams& params) {
939 // Validate the URLs in |params|. If the renderer can't request the URLs
940 // directly, don't show them in the context menu.
941 ContextMenuParams validated_params(params);
942 RenderProcessHost* process = GetProcess();
944 // We don't validate |unfiltered_link_url| so that this field can be used
945 // when users want to copy the original link URL.
946 process->FilterURL(true, &validated_params.link_url);
947 process->FilterURL(true, &validated_params.src_url);
948 process->FilterURL(false, &validated_params.page_url);
949 process->FilterURL(true, &validated_params.frame_url);
951 delegate_->ShowContextMenu(this, validated_params);
954 void RenderFrameHostImpl::OnJavaScriptExecuteResponse(
955 int id, const base::ListValue& result) {
956 const base::Value* result_value;
957 if (!result.Get(0, &result_value)) {
958 // Programming error or rogue renderer.
959 NOTREACHED() << "Got bad arguments for OnJavaScriptExecuteResponse";
960 return;
963 std::map<int, JavaScriptResultCallback>::iterator it =
964 javascript_callbacks_.find(id);
965 if (it != javascript_callbacks_.end()) {
966 it->second.Run(result_value);
967 javascript_callbacks_.erase(it);
968 } else {
969 NOTREACHED() << "Received script response for unknown request";
973 void RenderFrameHostImpl::OnRunJavaScriptMessage(
974 const base::string16& message,
975 const base::string16& default_prompt,
976 const GURL& frame_url,
977 JavaScriptMessageType type,
978 IPC::Message* reply_msg) {
979 // While a JS message dialog is showing, tabs in the same process shouldn't
980 // process input events.
981 GetProcess()->SetIgnoreInputEvents(true);
982 render_view_host_->StopHangMonitorTimeout();
983 delegate_->RunJavaScriptMessage(this, message, default_prompt,
984 frame_url, type, reply_msg);
987 void RenderFrameHostImpl::OnRunBeforeUnloadConfirm(
988 const GURL& frame_url,
989 const base::string16& message,
990 bool is_reload,
991 IPC::Message* reply_msg) {
992 // While a JS beforeunload dialog is showing, tabs in the same process
993 // shouldn't process input events.
994 GetProcess()->SetIgnoreInputEvents(true);
995 render_view_host_->StopHangMonitorTimeout();
996 delegate_->RunBeforeUnloadConfirm(this, message, is_reload, reply_msg);
999 void RenderFrameHostImpl::OnRequestPlatformNotificationPermission(
1000 const GURL& origin, int request_id) {
1001 base::Callback<void(bool)> done_callback = base::Bind(
1002 &RenderFrameHostImpl::PlatformNotificationPermissionRequestDone,
1003 weak_ptr_factory_.GetWeakPtr(),
1004 request_id);
1006 if (!delegate()->GetAsWebContents())
1007 return;
1009 // TODO(peter): plumb user_gesture and bridge_id.
1010 GetContentClient()->browser()->RequestPermission(
1011 content::PERMISSION_NOTIFICATIONS,
1012 delegate()->GetAsWebContents(),
1013 routing_id_,
1014 origin,
1015 true, // user_gesture,
1016 done_callback);
1019 void RenderFrameHostImpl::OnShowDesktopNotification(
1020 int notification_id,
1021 const ShowDesktopNotificationHostMsgParams& params) {
1022 scoped_ptr<DesktopNotificationDelegateImpl> delegate(
1023 new DesktopNotificationDelegateImpl(this, notification_id));
1025 base::Closure cancel_callback;
1026 GetContentClient()->browser()->ShowDesktopNotification(
1027 params,
1028 GetSiteInstance()->GetBrowserContext(),
1029 GetProcess()->GetID(),
1030 delegate.Pass(),
1031 &cancel_callback);
1033 cancel_notification_callbacks_[notification_id] = cancel_callback;
1036 void RenderFrameHostImpl::OnCancelDesktopNotification(int notification_id) {
1037 if (!cancel_notification_callbacks_.count(notification_id)) {
1038 NOTREACHED();
1039 return;
1041 cancel_notification_callbacks_[notification_id].Run();
1042 cancel_notification_callbacks_.erase(notification_id);
1045 void RenderFrameHostImpl::OnTextSurroundingSelectionResponse(
1046 const base::string16& content,
1047 size_t start_offset,
1048 size_t end_offset) {
1049 render_view_host_->OnTextSurroundingSelectionResponse(
1050 content, start_offset, end_offset);
1053 void RenderFrameHostImpl::OnDidAccessInitialDocument() {
1054 delegate_->DidAccessInitialDocument();
1057 void RenderFrameHostImpl::OnDidDisownOpener() {
1058 // This message is only sent for top-level frames. TODO(avi): when frame tree
1059 // mirroring works correctly, add a check here to enforce it.
1060 delegate_->DidDisownOpener(this);
1063 void RenderFrameHostImpl::OnDidAssignPageId(int32 page_id) {
1064 // Update the RVH's current page ID so that future IPCs from the renderer
1065 // correspond to the new page.
1066 render_view_host_->page_id_ = page_id;
1069 void RenderFrameHostImpl::OnUpdateTitle(
1070 int32 page_id,
1071 const base::string16& title,
1072 blink::WebTextDirection title_direction) {
1073 // This message is only sent for top-level frames. TODO(avi): when frame tree
1074 // mirroring works correctly, add a check here to enforce it.
1075 if (title.length() > kMaxTitleChars) {
1076 NOTREACHED() << "Renderer sent too many characters in title.";
1077 return;
1080 delegate_->UpdateTitle(this, page_id, title,
1081 WebTextDirectionToChromeTextDirection(
1082 title_direction));
1085 void RenderFrameHostImpl::OnUpdateEncoding(const std::string& encoding_name) {
1086 // This message is only sent for top-level frames. TODO(avi): when frame tree
1087 // mirroring works correctly, add a check here to enforce it.
1088 delegate_->UpdateEncoding(this, encoding_name);
1091 void RenderFrameHostImpl::OnBeginNavigation(
1092 const FrameHostMsg_BeginNavigation_Params& params,
1093 const CommonNavigationParams& common_params) {
1094 CHECK(CommandLine::ForCurrentProcess()->HasSwitch(
1095 switches::kEnableBrowserSideNavigation));
1096 frame_tree_node()->navigator()->OnBeginNavigation(
1097 frame_tree_node(), params, common_params);
1100 void RenderFrameHostImpl::OnAccessibilityEvents(
1101 const std::vector<AccessibilityHostMsg_EventParams>& params,
1102 int reset_token) {
1103 // Don't process this IPC if either we're waiting on a reset and this
1104 // IPC doesn't have the matching token ID, or if we're not waiting on a
1105 // reset but this message includes a reset token.
1106 if (accessibility_reset_token_ != reset_token) {
1107 Send(new AccessibilityMsg_Events_ACK(routing_id_));
1108 return;
1110 accessibility_reset_token_ = 0;
1112 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1113 render_view_host_->GetView());
1115 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1116 if ((accessibility_mode != AccessibilityModeOff) && view &&
1117 RenderFrameHostImpl::IsRFHStateActive(rfh_state())) {
1118 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1119 GetOrCreateBrowserAccessibilityManager();
1120 if (browser_accessibility_manager_)
1121 browser_accessibility_manager_->OnAccessibilityEvents(params);
1124 if (browser_accessibility_manager_) {
1125 // Get the frame routing ids from out-of-process iframes and
1126 // browser plugin instance ids from guests and update the mappings in
1127 // FrameAccessibility.
1128 for (unsigned int i = 0; i < params.size(); ++i) {
1129 const AccessibilityHostMsg_EventParams& param = params[i];
1130 UpdateCrossProcessIframeAccessibility(
1131 param.node_to_frame_routing_id_map);
1132 UpdateGuestFrameAccessibility(
1133 param.node_to_browser_plugin_instance_id_map);
1137 // Send the updates to the automation extension API.
1138 std::vector<AXEventNotificationDetails> details;
1139 details.reserve(params.size());
1140 for (size_t i = 0; i < params.size(); ++i) {
1141 const AccessibilityHostMsg_EventParams& param = params[i];
1142 AXEventNotificationDetails detail(param.update.node_id_to_clear,
1143 param.update.nodes,
1144 param.event_type,
1145 param.id,
1146 GetProcess()->GetID(),
1147 routing_id_);
1148 details.push_back(detail);
1151 delegate_->AccessibilityEventReceived(details);
1154 // Always send an ACK or the renderer can be in a bad state.
1155 Send(new AccessibilityMsg_Events_ACK(routing_id_));
1157 // The rest of this code is just for testing; bail out if we're not
1158 // in that mode.
1159 if (accessibility_testing_callback_.is_null())
1160 return;
1162 for (size_t i = 0; i < params.size(); i++) {
1163 const AccessibilityHostMsg_EventParams& param = params[i];
1164 if (static_cast<int>(param.event_type) < 0)
1165 continue;
1167 if (!ax_tree_for_testing_) {
1168 if (browser_accessibility_manager_) {
1169 ax_tree_for_testing_.reset(new ui::AXTree(
1170 browser_accessibility_manager_->SnapshotAXTreeForTesting()));
1171 } else {
1172 ax_tree_for_testing_.reset(new ui::AXTree());
1173 CHECK(ax_tree_for_testing_->Unserialize(param.update))
1174 << ax_tree_for_testing_->error();
1176 } else {
1177 CHECK(ax_tree_for_testing_->Unserialize(param.update))
1178 << ax_tree_for_testing_->error();
1180 accessibility_testing_callback_.Run(param.event_type, param.id);
1184 void RenderFrameHostImpl::OnAccessibilityLocationChanges(
1185 const std::vector<AccessibilityHostMsg_LocationChangeParams>& params) {
1186 if (accessibility_reset_token_)
1187 return;
1189 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1190 render_view_host_->GetView());
1191 if (view && RenderFrameHostImpl::IsRFHStateActive(rfh_state())) {
1192 AccessibilityMode accessibility_mode = delegate_->GetAccessibilityMode();
1193 if (accessibility_mode & AccessibilityModeFlagPlatform) {
1194 BrowserAccessibilityManager* manager =
1195 GetOrCreateBrowserAccessibilityManager();
1196 if (manager)
1197 manager->OnLocationChanges(params);
1199 // TODO(aboxhall): send location change events to web contents observers too
1203 #if defined(OS_MACOSX) || defined(OS_ANDROID)
1204 void RenderFrameHostImpl::OnShowPopup(
1205 const FrameHostMsg_ShowPopup_Params& params) {
1206 RenderViewHostDelegateView* view =
1207 render_view_host_->delegate_->GetDelegateView();
1208 if (view) {
1209 view->ShowPopupMenu(this,
1210 params.bounds,
1211 params.item_height,
1212 params.item_font_size,
1213 params.selected_item,
1214 params.popup_items,
1215 params.right_aligned,
1216 params.allow_multiple_selection);
1220 void RenderFrameHostImpl::OnHidePopup() {
1221 RenderViewHostDelegateView* view =
1222 render_view_host_->delegate_->GetDelegateView();
1223 if (view)
1224 view->HidePopupMenu();
1226 #endif
1228 void RenderFrameHostImpl::SetState(RenderFrameHostImplState rfh_state) {
1229 // Only main frames should be swapped out and retained inside a proxy host.
1230 if (rfh_state == STATE_SWAPPED_OUT)
1231 CHECK(!GetParent());
1233 // We update the number of RenderFrameHosts in a SiteInstance when the swapped
1234 // out status of a RenderFrameHost gets flipped to/from active.
1235 if (!IsRFHStateActive(rfh_state_) && IsRFHStateActive(rfh_state))
1236 GetSiteInstance()->increment_active_frame_count();
1237 else if (IsRFHStateActive(rfh_state_) && !IsRFHStateActive(rfh_state))
1238 GetSiteInstance()->decrement_active_frame_count();
1240 // The active and swapped out state of the RVH is determined by its main
1241 // frame, since subframes should have their own widgets.
1242 if (frame_tree_node_->IsMainFrame()) {
1243 render_view_host_->set_is_active(IsRFHStateActive(rfh_state));
1244 render_view_host_->set_is_swapped_out(rfh_state == STATE_SWAPPED_OUT);
1247 // Whenever we change the RFH state to and from active or swapped out state,
1248 // we should not be waiting for beforeunload or close acks. We clear them
1249 // here to be safe, since they can cause navigations to be ignored in
1250 // OnDidCommitProvisionalLoad.
1251 // TODO(creis): Move is_waiting_for_beforeunload_ack_ into the state machine.
1252 if (rfh_state == STATE_DEFAULT ||
1253 rfh_state == STATE_SWAPPED_OUT ||
1254 rfh_state_ == STATE_DEFAULT ||
1255 rfh_state_ == STATE_SWAPPED_OUT) {
1256 is_waiting_for_beforeunload_ack_ = false;
1257 send_before_unload_start_time_ = base::TimeTicks();
1258 render_view_host_->is_waiting_for_close_ack_ = false;
1260 rfh_state_ = rfh_state;
1263 bool RenderFrameHostImpl::CanCommitURL(const GURL& url) {
1264 // TODO(creis): We should also check for WebUI pages here. Also, when the
1265 // out-of-process iframes implementation is ready, we should check for
1266 // cross-site URLs that are not allowed to commit in this process.
1268 // Give the client a chance to disallow URLs from committing.
1269 return GetContentClient()->browser()->CanCommitURL(GetProcess(), url);
1272 void RenderFrameHostImpl::Navigate(const FrameMsg_Navigate_Params& params) {
1273 TRACE_EVENT0("navigation", "RenderFrameHostImpl::Navigate");
1274 // Browser plugin guests are not allowed to navigate outside web-safe schemes,
1275 // so do not grant them the ability to request additional URLs.
1276 if (!GetProcess()->IsIsolatedGuest()) {
1277 ChildProcessSecurityPolicyImpl::GetInstance()->GrantRequestURL(
1278 GetProcess()->GetID(), params.common_params.url);
1279 if (params.common_params.url.SchemeIs(url::kDataScheme) &&
1280 params.base_url_for_data_url.SchemeIs(url::kFileScheme)) {
1281 // If 'data:' is used, and we have a 'file:' base url, grant access to
1282 // local files.
1283 ChildProcessSecurityPolicyImpl::GetInstance()->GrantRequestURL(
1284 GetProcess()->GetID(), params.base_url_for_data_url);
1288 // Only send the message if we aren't suspended at the start of a cross-site
1289 // request.
1290 if (navigations_suspended_) {
1291 // Shouldn't be possible to have a second navigation while suspended, since
1292 // navigations will only be suspended during a cross-site request. If a
1293 // second navigation occurs, RenderFrameHostManager will cancel this pending
1294 // RFH and create a new pending RFH.
1295 DCHECK(!suspended_nav_params_.get());
1296 suspended_nav_params_.reset(new FrameMsg_Navigate_Params(params));
1297 } else {
1298 // Get back to a clean state, in case we start a new navigation without
1299 // completing a RFH swap or unload handler.
1300 SetState(RenderFrameHostImpl::STATE_DEFAULT);
1302 Send(new FrameMsg_Navigate(routing_id_, params));
1305 // Force the throbber to start. We do this because Blink's "started
1306 // loading" message will be received asynchronously from the UI of the
1307 // browser. But we want to keep the throbber in sync with what's happening
1308 // in the UI. For example, we want to start throbbing immediately when the
1309 // user naivgates even if the renderer is delayed. There is also an issue
1310 // with the throbber starting because the WebUI (which controls whether the
1311 // favicon is displayed) happens synchronously. If the start loading
1312 // messages was asynchronous, then the default favicon would flash in.
1314 // Blink doesn't send throb notifications for JavaScript URLs, so we
1315 // don't want to either.
1316 if (!params.common_params.url.SchemeIs(url::kJavaScriptScheme))
1317 delegate_->DidStartLoading(this, true);
1320 void RenderFrameHostImpl::NavigateToURL(const GURL& url) {
1321 FrameMsg_Navigate_Params params;
1322 params.common_params.url = url;
1323 params.common_params.transition = ui::PAGE_TRANSITION_LINK;
1324 params.common_params.navigation_type = FrameMsg_Navigate_Type::NORMAL;
1325 params.commit_params.browser_navigation_start = base::TimeTicks::Now();
1326 params.page_id = -1;
1327 params.pending_history_list_offset = -1;
1328 params.current_history_list_offset = -1;
1329 params.current_history_list_length = 0;
1330 Navigate(params);
1333 void RenderFrameHostImpl::OpenURL(const FrameHostMsg_OpenURL_Params& params) {
1334 OnOpenURL(params);
1337 void RenderFrameHostImpl::Stop() {
1338 Send(new FrameMsg_Stop(routing_id_));
1341 void RenderFrameHostImpl::DispatchBeforeUnload(bool for_cross_site_transition) {
1342 // TODO(creis): Support beforeunload on subframes. For now just pretend that
1343 // the handler ran and allowed the navigation to proceed.
1344 if (GetParent() || !IsRenderFrameLive()) {
1345 // We don't have a live renderer, so just skip running beforeunload.
1346 frame_tree_node_->render_manager()->OnBeforeUnloadACK(
1347 for_cross_site_transition, true, base::TimeTicks::Now());
1348 return;
1350 TRACE_EVENT_ASYNC_BEGIN0(
1351 "navigation", "RenderFrameHostImpl::BeforeUnload", this);
1353 // This may be called more than once (if the user clicks the tab close button
1354 // several times, or if she clicks the tab close button then the browser close
1355 // button), and we only send the message once.
1356 if (is_waiting_for_beforeunload_ack_) {
1357 // Some of our close messages could be for the tab, others for cross-site
1358 // transitions. We always want to think it's for closing the tab if any
1359 // of the messages were, since otherwise it might be impossible to close
1360 // (if there was a cross-site "close" request pending when the user clicked
1361 // the close button). We want to keep the "for cross site" flag only if
1362 // both the old and the new ones are also for cross site.
1363 unload_ack_is_for_cross_site_transition_ =
1364 unload_ack_is_for_cross_site_transition_ && for_cross_site_transition;
1365 } else {
1366 // Start the hang monitor in case the renderer hangs in the beforeunload
1367 // handler.
1368 is_waiting_for_beforeunload_ack_ = true;
1369 unload_ack_is_for_cross_site_transition_ = for_cross_site_transition;
1370 // Increment the in-flight event count, to ensure that input events won't
1371 // cancel the timeout timer.
1372 render_view_host_->increment_in_flight_event_count();
1373 render_view_host_->StartHangMonitorTimeout(
1374 TimeDelta::FromMilliseconds(RenderViewHostImpl::kUnloadTimeoutMS));
1375 send_before_unload_start_time_ = base::TimeTicks::Now();
1376 Send(new FrameMsg_BeforeUnload(routing_id_));
1380 void RenderFrameHostImpl::DisownOpener() {
1381 Send(new FrameMsg_DisownOpener(GetRoutingID()));
1384 void RenderFrameHostImpl::ExtendSelectionAndDelete(size_t before,
1385 size_t after) {
1386 Send(new InputMsg_ExtendSelectionAndDelete(routing_id_, before, after));
1389 void RenderFrameHostImpl::JavaScriptDialogClosed(
1390 IPC::Message* reply_msg,
1391 bool success,
1392 const base::string16& user_input,
1393 bool dialog_was_suppressed) {
1394 GetProcess()->SetIgnoreInputEvents(false);
1395 bool is_waiting = is_waiting_for_beforeunload_ack_ || IsWaitingForUnloadACK();
1397 // If we are executing as part of (before)unload event handling, we don't
1398 // want to use the regular hung_renderer_delay_ms_ if the user has agreed to
1399 // leave the current page. In this case, use the regular timeout value used
1400 // during the (before)unload handling.
1401 if (is_waiting) {
1402 render_view_host_->StartHangMonitorTimeout(TimeDelta::FromMilliseconds(
1403 success ? RenderViewHostImpl::kUnloadTimeoutMS
1404 : render_view_host_->hung_renderer_delay_ms_));
1407 FrameHostMsg_RunJavaScriptMessage::WriteReplyParams(reply_msg,
1408 success, user_input);
1409 Send(reply_msg);
1411 // If we are waiting for an unload or beforeunload ack and the user has
1412 // suppressed messages, kill the tab immediately; a page that's spamming
1413 // alerts in onbeforeunload is presumably malicious, so there's no point in
1414 // continuing to run its script and dragging out the process.
1415 // This must be done after sending the reply since RenderView can't close
1416 // correctly while waiting for a response.
1417 if (is_waiting && dialog_was_suppressed)
1418 render_view_host_->delegate_->RendererUnresponsive(render_view_host_);
1421 void RenderFrameHostImpl::NotificationClosed(int notification_id) {
1422 cancel_notification_callbacks_.erase(notification_id);
1425 // PlzNavigate
1426 void RenderFrameHostImpl::CommitNavigation(
1427 ResourceResponse* response,
1428 scoped_ptr<StreamHandle> body,
1429 const CommonNavigationParams& common_params,
1430 const CommitNavigationParams& commit_params) {
1431 // TODO(clamy): Check if we have to add security checks for the browser plugin
1432 // guests.
1434 Send(new FrameMsg_CommitNavigation(
1435 routing_id_, response->head, body->GetURL(),
1436 common_params, commit_params));
1437 // TODO(clamy): Check if we should start the throbber for non javascript urls
1438 // here.
1440 // TODO(clamy): Release the stream handle once the renderer has finished
1441 // reading it.
1442 stream_handle_ = body.Pass();
1445 void RenderFrameHostImpl::SetUpMojoIfNeeded() {
1446 if (service_registry_.get())
1447 return;
1449 service_registry_.reset(new ServiceRegistryImpl());
1450 if (!GetProcess()->GetServiceRegistry())
1451 return;
1453 RenderFrameSetupPtr setup;
1454 GetProcess()->GetServiceRegistry()->ConnectToRemoteService(&setup);
1455 mojo::ServiceProviderPtr service_provider;
1456 setup->GetServiceProviderForFrame(routing_id_,
1457 mojo::GetProxy(&service_provider));
1458 service_registry_->BindRemoteServiceProvider(
1459 service_provider.PassMessagePipe());
1461 #if defined(OS_ANDROID)
1462 service_registry_android_.reset(
1463 new ServiceRegistryAndroid(service_registry_.get()));
1464 #endif
1467 void RenderFrameHostImpl::InvalidateMojoConnection() {
1468 service_registry_.reset();
1469 #if defined(OS_ANDROID)
1470 service_registry_android_.reset();
1471 #endif
1474 void RenderFrameHostImpl::PlatformNotificationPermissionRequestDone(
1475 int request_id,
1476 bool granted) {
1477 blink::WebNotificationPermission permission =
1478 granted ? blink::WebNotificationPermissionAllowed
1479 : blink::WebNotificationPermissionDenied;
1481 Send(new PlatformNotificationMsg_PermissionRequestComplete(
1482 routing_id_, request_id, permission));
1485 void RenderFrameHostImpl::UpdateCrossProcessIframeAccessibility(
1486 const std::map<int32, int> node_to_frame_routing_id_map) {
1487 std::map<int32, int>::const_iterator iter;
1488 for (iter = node_to_frame_routing_id_map.begin();
1489 iter != node_to_frame_routing_id_map.end();
1490 ++iter) {
1491 // This is the id of the accessibility node that has a child frame.
1492 int32 node_id = iter->first;
1493 // The routing id from either a RenderFrame or a RenderFrameProxy.
1494 int frame_routing_id = iter->second;
1496 FrameTree* frame_tree = frame_tree_node()->frame_tree();
1497 FrameTreeNode* child_frame_tree_node = frame_tree->FindByRoutingID(
1498 GetProcess()->GetID(), frame_routing_id);
1499 if (child_frame_tree_node) {
1500 FrameAccessibility::GetInstance()->AddChildFrame(
1501 this, node_id, child_frame_tree_node->frame_tree_node_id());
1506 void RenderFrameHostImpl::UpdateGuestFrameAccessibility(
1507 const std::map<int32, int> node_to_browser_plugin_instance_id_map) {
1508 std::map<int32, int>::const_iterator iter;
1509 for (iter = node_to_browser_plugin_instance_id_map.begin();
1510 iter != node_to_browser_plugin_instance_id_map.end();
1511 ++iter) {
1512 // This is the id of the accessibility node that hosts a plugin.
1513 int32 node_id = iter->first;
1514 // The id of the browser plugin.
1515 int browser_plugin_instance_id = iter->second;
1516 FrameAccessibility::GetInstance()->AddGuestWebContents(
1517 this, node_id, browser_plugin_instance_id);
1521 void RenderFrameHostImpl::SetAccessibilityMode(AccessibilityMode mode) {
1522 Send(new FrameMsg_SetAccessibilityMode(routing_id_, mode));
1525 void RenderFrameHostImpl::SetAccessibilityCallbackForTesting(
1526 const base::Callback<void(ui::AXEvent, int)>& callback) {
1527 accessibility_testing_callback_ = callback;
1530 const ui::AXTree* RenderFrameHostImpl::GetAXTreeForTesting() {
1531 return ax_tree_for_testing_.get();
1534 BrowserAccessibilityManager*
1535 RenderFrameHostImpl::GetOrCreateBrowserAccessibilityManager() {
1536 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1537 render_view_host_->GetView());
1538 if (view &&
1539 !browser_accessibility_manager_ &&
1540 !no_create_browser_accessibility_manager_for_testing_) {
1541 browser_accessibility_manager_.reset(
1542 view->CreateBrowserAccessibilityManager(this));
1543 if (browser_accessibility_manager_)
1544 UMA_HISTOGRAM_COUNTS("Accessibility.FrameEnabledCount", 1);
1545 else
1546 UMA_HISTOGRAM_COUNTS("Accessibility.FrameDidNotEnableCount", 1);
1548 return browser_accessibility_manager_.get();
1551 #if defined(OS_WIN)
1553 void RenderFrameHostImpl::SetParentNativeViewAccessible(
1554 gfx::NativeViewAccessible accessible_parent) {
1555 RenderWidgetHostViewBase* view = static_cast<RenderWidgetHostViewBase*>(
1556 render_view_host_->GetView());
1557 if (view)
1558 view->SetParentNativeViewAccessible(accessible_parent);
1561 gfx::NativeViewAccessible
1562 RenderFrameHostImpl::GetParentNativeViewAccessible() const {
1563 return delegate_->GetParentNativeViewAccessible();
1566 #elif defined(OS_MACOSX)
1568 void RenderFrameHostImpl::DidSelectPopupMenuItem(int selected_index) {
1569 Send(new FrameMsg_SelectPopupMenuItem(routing_id_, selected_index));
1572 void RenderFrameHostImpl::DidCancelPopupMenu() {
1573 Send(new FrameMsg_SelectPopupMenuItem(routing_id_, -1));
1576 #elif defined(OS_ANDROID)
1578 void RenderFrameHostImpl::DidSelectPopupMenuItems(
1579 const std::vector<int>& selected_indices) {
1580 Send(new FrameMsg_SelectPopupMenuItems(routing_id_, false, selected_indices));
1583 void RenderFrameHostImpl::DidCancelPopupMenu() {
1584 Send(new FrameMsg_SelectPopupMenuItems(
1585 routing_id_, true, std::vector<int>()));
1588 #endif
1590 void RenderFrameHostImpl::ClearPendingTransitionRequestData() {
1591 BrowserThread::PostTask(
1592 BrowserThread::IO,
1593 FROM_HERE,
1594 base::Bind(
1595 &TransitionRequestManager::ClearPendingTransitionRequestData,
1596 base::Unretained(TransitionRequestManager::GetInstance()),
1597 GetProcess()->GetID(),
1598 routing_id_));
1601 void RenderFrameHostImpl::SetNavigationsSuspended(
1602 bool suspend,
1603 const base::TimeTicks& proceed_time) {
1604 // This should only be called to toggle the state.
1605 DCHECK(navigations_suspended_ != suspend);
1607 navigations_suspended_ = suspend;
1608 if (navigations_suspended_) {
1609 TRACE_EVENT_ASYNC_BEGIN0("navigation",
1610 "RenderFrameHostImpl navigation suspended", this);
1611 } else {
1612 TRACE_EVENT_ASYNC_END0("navigation",
1613 "RenderFrameHostImpl navigation suspended", this);
1616 if (!suspend && suspended_nav_params_) {
1617 // There's navigation message params waiting to be sent. Now that we're not
1618 // suspended anymore, resume navigation by sending them. If we were swapped
1619 // out, we should also stop filtering out the IPC messages now.
1620 SetState(RenderFrameHostImpl::STATE_DEFAULT);
1622 DCHECK(!proceed_time.is_null());
1623 suspended_nav_params_->commit_params.browser_navigation_start =
1624 proceed_time;
1625 Send(new FrameMsg_Navigate(routing_id_, *suspended_nav_params_));
1626 suspended_nav_params_.reset();
1630 void RenderFrameHostImpl::CancelSuspendedNavigations() {
1631 // Clear any state if a pending navigation is canceled or preempted.
1632 if (suspended_nav_params_)
1633 suspended_nav_params_.reset();
1635 TRACE_EVENT_ASYNC_END0("navigation",
1636 "RenderFrameHostImpl navigation suspended", this);
1637 navigations_suspended_ = false;
1640 } // namespace content